Is it advisable to use $ watch instead of binding to a function in a large angular app for better performance?

I tried:

<div ng-show="isDirty()" />

$scope.isDirty = function() {
    console.log('isDirty');
    return field.isDirty;
}

      

and

<div ng-show="isDirty" />

$scope.$watch('field.isDirty', function(oldValue, newValue) {
    console.log('isDirty');
    $scope.isDirty = newValue;
});

      

The first option works many times than the second. The first option also works when I did things unrelated to field.isDirty.

+3


source to share


1 answer


The first option fires more times because you actually fire it on different occasions. In the first case, there is an observer for the result of your function. It runs each digest to get the new value and compare it with the old one. In the second options there is very close to the first observer. But you just don't see that it shoots every digest. You only see when the result has really changed.

To make the experiment fair, you should use a no-expression observer ( From AngularJS docs ):



If you want to be notified whenever $digest is called, you can register a watchExpression function with no listener. (Since watchExpression can execute multiple times per $digest cycle when a change is detected, be prepared for multiple calls to your listener.)

0


source







All Articles