How to 'unwatch' an expression

前端 未结 5 520
情深已故
情深已故 2020-11-30 19:21

Say I have an ng-repeat with a big array.

When ng-repeat runs, it adds every element of that array to an isolated scope, as well as having the array itself in a scop

5条回答
  •  旧巷少年郎
    2020-11-30 19:23

    Edit: see the other answer I posted.

    I've gone and implemented blesh's idea in a seperable way. My ngOnce directive just destroys the child scope that ngRepeat creates on each item. This means the scope doesn't get reached from its parents' scope.$digest and the watchers are never executed.

    Source and example on JSFiddle

    The directive itself:

    angular.module('transclude', [])
     .directive('ngOnce', ['$timeout', function($timeout){
        return {
          restrict: 'EA',
          priority: 500,
          transclude: true,
          template: '
    ', compile: function (tElement, tAttrs, transclude) { return function postLink(scope, iElement, iAttrs, controller) { $timeout(scope.$destroy.bind(scope), 0); } } }; }]);

    Using it:

          
  • {{item.title}}: {{item.text}}
  • Note ng-once doesn't create its own scope which means it can affect sibling elements. These all do the same thing:

      
  • {{item.title}}: {{item.text}}
  • {{item.title}}: {{item.text}}
  • {{item.title}}: {{item.text}}
  • Note this may be a bad idea

提交回复
热议问题