To add the capability to handle changes to scope values, you simply need to add a $watch
to the variable in the scope using the $watch
functionality built into AngularJS. The $watch
function in the scope uses the following syntax:
$watch(watchExpression, listener, [objectEquality])
The watchExpression is the expression in the scope to watch. This expression is called on every $digest()
and will return the value that will be watched. The listener defines a function that will be called when the value of the watchExpression changes to a new value. The listener will not be called if the watchExpression is changed to the value it is already set to. The objectEquality is a Boolean that when true will use the angular.equals()
function to determine equality instead of the more strict ==!
operator. You should be careful when using objectEquality because on complex objects it can result in increases in memory and performance usage.
The following shows an example of adding $watch
on the scope variable score:
$scope.score = 0;
$scope.$watch('score', function(newValue, oldValue) {
if(newValue > 10){
$scope.status = 'win';
}
});