What gets added to $scope.$$watchers by default in Angular? And what triggers $digests?

后端 未结 2 457
粉色の甜心
粉色の甜心 2020-12-22 10:53

I\'m reading Build Your Own AngularJS and have a decent understanding of how $scopes, $watch and $digest work. I understand how it wor

2条回答
  •  不思量自难忘°
    2020-12-22 11:33

    Some of the common directives that use $watch / $watchCollection / $watchGroup internally:

    1. ng-model
    2. ng-bind / {{ }}
    3. ng-show & ng-hide
    4. ng-class
    5. ng-repeat
    6. ng-if
    7. ng-switch
    8. ng-include

    Note that the only one that sets up a two-way binding is ng-model (scope -> view & view -> scope).

    The others set up a one-way binding (scope -> view).

    Simply exposing something on for example a controller´s $scope will not add a watcher.

    For example, the following will not result in a watcher being added:

    angular.module('myApp', []).controller('Controller', function MyCtrl($scope) {
      $scope.value = 1;
    });
    

    Together with:

    
    
    

    But if you replace the HTML with the following one watcher will be added:

    
      
    {{value}}

    Some common scenarios when the digest cycle is triggered:

    1. When ng-click is evaluated
    2. When ng-model changes (for example when typing in an input)
    3. By the $http service
    4. In $timeout and $interval

    Note that there is one big difference between $apply and $digest:

    Calling scope.$digest() will execute the watchers only on that scope and its children.

    Calling scope.$apply() will trigger $digest on the $rootScope, which means all the scopes will be traversed and all watchers executed.

    $apply also accepts an expression as an argument. This expression will be evaluated inside a try-catch statement and any exception will be passed on to the $exceptionHandler service.

    $digest does not accept any arguments.

    Usually you only call $digest instead of $apply when you are chasing micro optimizations and really know what you are doing.

提交回复
热议问题