How to 'unwatch' an expression

前端 未结 5 511
情深已故
情深已故 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: '<div ng-transclude></div>',
            compile: function (tElement, tAttrs, transclude) {
                return function postLink(scope, iElement, iAttrs, controller) {
                    $timeout(scope.$destroy.bind(scope), 0);
                }
            }
        };
    }]);
    

    Using it:

          <li ng-repeat="item in contents" ng-once>
              {{item.title}}: {{item.text}}
          </li>
    

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

      <li ng-repeat="item in contents" ng-once>
          {{item.title}}: {{item.text}}
      </li>
      <li ng-repeat="item in contents">
          <ng-once>
              {{item.title}}: {{item.text}}
          </ng-once>
      </li>
      <li ng-repeat="item in contents">
          {{item.title}}: {{item.text}} <ng-once></ng-once>
      </li>
    

    Note this may be a bad idea

    0 讨论(0)
  • 2020-11-30 19:24

    To have a repeater with a large array that you don't watch to watch every item.

    You'll need to create a custom directive that takes one argument, and expression to your array, then in the linking function you'd just watch that array, and you'd have the linking function programmatically refresh the HTML (rather than using an ng-repeat)

    something like (psuedo-code):

    app.directive('leanRepeat', function() {
        return {
            restrict: 'E',
            scope: {
               'data' : '='
            },
            link: function(scope, elem, attr) {
               scope.$watch('data', function(value) {
                  elem.empty(); //assuming jquery here.
                  angular.forEach(scope.data, function(d) {
                      //write it however you're going to write it out here.
                      elem.append('<div>' + d + '</div>');
                  });
               });
            }
        };
    });
    

    ... which seems like a pain in the butt.

    Alternate hackish method

    You might be able to loop through $scope.$$watchers and examine $scope.$$watchers[0].exp.exp to see if it matches the expression you'd like to remove, then remove it with a simple splice() call. The PITA here, is that things like Blah {{whatever}} Blah between tags will be the expression, and will even include carriage returns.

    On the upside, you might be able to just loop through the $scope of your ng-repeat and just remove everything, then explicitly add the watch you want... I dunno.

    Either way, it seems like a hack.

    To remove a watcher made by $scope.$watch

    You can unregister a $watch with the function returned by the $watch call:

    For example, to have a $watch only fire once:

    var unregister = $scope.$watch('whatever', function(){ 
         alert('once!');
         unregister();
    });
    

    You can, of course call the unregister function any time you want... that was just an example.

    Conclusion: There isn't really a great way to do exactly what you're asking

    But one thing to consider: Is it even worth worrying about? Furthermore is it truly a good idea to have thousands of records loaded into dozens of DOMElements each? Food for thought.

    I hope that helps.


    EDIT 2 (removed bad idea)

    0 讨论(0)
  • 2020-11-30 19:31

    $watch returns a function that unbinds the $watch when called. So this is all you need for "watchOnce":

    var unwatchValue = scope.$watch('value', function(newValue, oldValue) {
      // Do your thing
      unwatchValue();
    });
    
    0 讨论(0)
  • 2020-11-30 19:31

    If you are using angularjs 1.3 or above, you can use the single bind syntax as

    <li ng-repeat="item in ::contents">{{item}}</li>
    

    This will bind the value and will remove the watchers once the first digest cycle is run and the value changes from undefined to defined for the first time.

    A very helpful BLOG on this.

    0 讨论(0)
  • 2020-11-30 19:40

    You can add the bindonce directive to your ng-repeat. You'll need to download it from https://github.com/pasvaz/bindonce.

    edit: a few caveats:

    If you're using {{}} interpolation in your template, you need to replace it with <span bo-text>.

    If you're using ng- directives, you need to replace them with the right bo- directives.

    Also, if you're putting bindonce and ng-repeat on the same element, you should try either moving the bindonce to a parent element (see https://github.com/Pasvaz/bindonce/issues/25#issuecomment-25457970 ) or adding track by to your ng-repeat.

    0 讨论(0)
提交回复
热议问题