Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribe to Property Change in AngularJS

In knockoutJS it is possible to subscribe to a change of an observable viewmodel property, e.g., like:

myViewModel.personName.subscribe(function(newValue) {     alert("The person's new name is " + newValue); }); 

I am currently learning AngularJS, and I was wondering if there is an equivalent to this in AngularJS? I have tried searching for this, but without any luck.

like image 589
Lasse Christiansen Avatar asked Jun 19 '13 19:06

Lasse Christiansen


2 Answers

The scope object in AngularJS has a special method called $watch for 'watching' scope properties.

It accepts a callback that receives the new and the old value of the model:

$scope.$watch('modelName', function(newValue, oldValue){     // Do anything you like here }); 

The callback is on initialization and each time the model changes. Therefore it may be good to add an extra check for equality like this:

$scope.$watch('modelName', function(newValue, oldValue){      // Check if value has changes     if(newValue === oldValue){         return;     }      // Do anything you like here }); 

This allows you to 'watch' your model and perform some action if needed.

One extra remark: if you're watching a model that contains an object, you should use an extra third parameter that tells AngularJS to compare both values by object equality and not by reference (as the reference would not change and thus not trigger the watcher) like this:

$scope.$watch('modelName', function(newValue, oldValue){     // Do anything you like here }, true); // Add extra 'true' parameter to check for object equality 

You can read more documentation on the AngularJS scope page.

Hope that helps!

like image 82
jvandemo Avatar answered Oct 09 '22 10:10

jvandemo


For API calls and async data triggered by user actions or application events, you are better off using

$rootScope.$broadcast('updateSearch', value); 

directly in the callback of the service function and leveraging it in your controllers like:

$scope.$on('updateSearch', function(event,value) {   $scope.search = value; }); 
like image 28
Dan Kanze Avatar answered Oct 09 '22 10:10

Dan Kanze