![]() |
VOOZH | about |
$scope acts as a built-in object in AngularJs.
It consists of application data and methods. The $scope is acts as a link between a controller and view (HTML).
$scope is used to transfer the data.
$watch:
Scope in AngularJs object has $watch event which comes into picture when the model property gets changed or altered.
When a data binding is created from some point of program in the view to a variable on the $scope object, a watch is created internally in AngularJs.
The digest gets called multiple times, when we $watch() a function.
Every time when we bind the UI, We insert $watch in $watch list.
User: <input type="text" ng-model="user" /> Password: <input type="password" ng-model="pass" />
Example:
$watch in AngularJs is a service.
It is used to keep the track of the changes on specific properties within a given scope. It is similar to an event listener. e changes are made in the value of specified variables.
When we register a watch we pass two functions as parameters to the $watch() function.These functions are:
Example:
$scope.$watch(function() {}, //value function
function() {} //listener function
);
A watcher can change in responses on:
Methods Used: $scope.$watchGroup
$watchGroup() is a shortcut to set up watchers with the same callback, passing an array of watchExpressions.
$scope.$watchGroup(['obj.a', 'obj.b.bb[4]', 'letters[8]'], function(newValues, oldValues, scope) { //... });
$scope.$watchCollection is a shortcut to watch arrays or objects. In arrays, the listener is called when any of the elements are replaced, deleted, or added.
The $watch keeps track of the variable. This function takes two arguments:
new value
$scope.$watch('expression', function (newvalue, oldvalue) { //expression parameter //Code });
old value
$scope.$watch(function () {}, function (newvalue, oldvalue) { //Function Parameter // Code });
Example:
Others:
$digest()
We call the $digest() function when AngularJS thinks it is necessary.
For example, after a button click handler is executed, or after an AJAX call returns.
$apply():
The $scope.$apply() function takes a function as parameter which it is executed, and after that $scope.$digest() is called internally. That makes it helpful to all the watches are checked
$scope.$apply(function() {
$scope.data.myVar = "value";
});
Example of $Watch:
CSS: