How to 'unwatch' an expression

前端 未结 5 522
情深已故
情深已故 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: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('
    ' + d + '
    '); }); }); } }; });

    ... 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)

提交回复
热议问题