Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to watch all changes on a Scope in AngularJS?

Angular's $watch function allows events to be fired when the specified attribute changes, as shown below. Is there is a similar way to listen for events when any change happens on the scope?

// works
$scope.$watch("someval", function() { }, true);
$scope.$watch(function(scope){ return scope.someval; }, function() { }, true);

// doesn't work
$scope.$watch("this", function() { }, true);
$scope.$watch(function(scope){ return scope; }, function() { }, true);
like image 487
Luke Dennis Avatar asked Jan 27 '13 09:01

Luke Dennis


People also ask

What is scope watch AngularJS?

A watch means that AngularJS watches changes in the variable on the $scope object. The framework is "watching" the variable. Watches are created using the $scope. $watch() function which I will cover later in this text. At key points in your application AngularJS calls the $scope.

How are apply () Watch () Digest () different in AngularJS?

$apply() function will execute custom code and then it will call $scope. $digest() function forcefully to check all watch list variables and update variable values in view if any changes found for watch list variables. In most of the time angularjs will use $scope.

How does $Watch work in AngularJS?

The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.

How does scope inheritance work in AngularJS?

Scope InheritanceIf we define nested controllers, then the child controller inherits the scope of its parent controller. We assign values to the models in shapeController. We override message in child controller named circleController.


1 Answers

I believe you cannot watch for changes on the $scope (apart from using @ValentynShybanov's sugestion). The closest thing you can do is to watch for digest calls:

$scope.$watch(function() { 
    console.log("digest called"); 
});

The above function will be called each time a $digest is invoked on the scope, even if there were no changes on the scope's properties.

like image 181
bmleite Avatar answered Sep 18 '22 15:09

bmleite