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.
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!
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With