How to stop digest cycle manually in angularjs

后端 未结 3 2045
盖世英雄少女心
盖世英雄少女心 2020-12-29 07:17

As digest cycle do the dirty checking of the variable that is if there are 100 scope variables and if I change one variable then it will run watch of all the variables.

3条回答
  •  自闭症患者
    2020-12-29 07:53

    Surprisingly, this is usually not a problem, Browsers don’t have problems even with thousands of bindings, unless the expressions are complex. The common answer for how many watchers are ok to have is 2000.

    Solutions :

    It is fairly easy onwards from AngularJS 1.3, since one-time bindings are in core now.

    1. One time Binding of the variables.

    We can use One time binding(::) directive to prevent the watcher to watch the unwanted variables. Here, variable will be watch only once & after that it will not update that variable.

    1. Stop the digest cycle manually.

    HTML :

    • {{lots of bindings}}

    Controller Code :

    app.controller('myCtrl', function ($scope, $element) {
      $element.on('scroll', function () {
        $scope.Lists = getVisibleElements();
        $scope.$digest();
      });
    });
    

    During the $digest, you are only interested in changes to Lists object, not changes to individual items. Yet, Angular will still interrogate every single watcher for changes.

    directive for stop and pause the digest:

    app.directive('stopDigest', function () {
      return {
        link: function (scope) {
          var watchers;
    
          scope.$on('stop', function () {
            watchers = scope.$$watchers;
            scope.$$watchers = [];
          });
    
          scope.$on('resume', function () {
            if (watchers)
              scope.$$watchers = watchers;
          });
        }
      };
    });
    

    Now, Controller code should be changed :

    • {{lots of bindings}}
    app.controller('myCtrl', function ($scope, $element) { $element.on('scroll', function () { $scope.visibleList = getVisibleElements(); $scope.$broadcast('stop'); $scope.$digest(); $scope.$broadcast('resume'); }); });

    Reference Doc : https://coderwall.com/p/d_aisq/speeding-up-angularjs-s-digest-loop

    Thanks.

提交回复
热议问题