Sunday, April 5, 2015

Watching multiple $scope attributes using $watchGroup

We all know that $scope.$watch() provides a mechanism to observe changes on a particular attribute or expression and allows us to handle the changes by registering to the callback event. A good example of using this is to calculate the elapsed date (date difference) between a user entered date and today’s date. In my scenario there is a datepicker where the user picks a date and I have to show the date difference between that date and current date. So I added watch on the user picked date and in that $watch callback I calculated the difference using my DateDiff routine as shown below

$scope.$watch('vm.model.ExamDate, function (newValue, oldValue) {
    var diff = utility.dateDiff(newValue, todayDate);
    //rest of my code

After this I had to extend my datediff routine to show the difference between two user entered dates, in this scenario I have to show difference between the ExamDate and DateOfBirth. For this exact purpose AngularJS introduced the watchGroup which can be used to observe changes in multiple variables and accordingly run the code. Here is my code using watchGroup to observe changes in ExamDate and DateOfBirth and whenever either one changed I am calculating the difference between these two dates. Here is my code for this:

$scope.$watchGroup(['vm.model.ExamDate', 'vm.model.DOB'], function (newValues, oldValues, scope) {
    var diff = utility.dateDiff(newValues[1], newValues[0]);

So as you see $watchGroup provides the capability of wating multiple $scope attributes.
Finally AngularJS also has $watchCollection which is used to watch changes to the properties of an object and fire the change event.

No comments:

Post a Comment