Watch variable and change it

前端 未结 5 1672
广开言路
广开言路 2020-12-24 07:10

In AngularJS I have a directive that watches a scope variable. When the variable contains certain data then I need to alter that variable a bit. The problem is that when I c

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-24 07:20

    When a variable is watched for changes using $scope.$watch, angular checks if the reference has changed. If it has, then the $watch handler is executed to update the view.

    If you plan on changing the scope variable within the $watch handler, it will trigger an infinite $digest loop because the scope variable reference changes every time that it is called.

    The trick to getting around the infinite digest issue is to preserve the reference inside your $watch handler using angular.copy (docs):

    scope.$watch('someVar', function(newValue, oldValue) {
        console.log(newValue);
        var someVar = [Do something with someVar];
    
        // angular copy will preserve the reference of $scope.someVar
        // so it will not trigger another digest 
        angular.copy(someVar, $scope.someVar);
    
    });
    

    Note: This trick only works for object references. It will not work with primitives.

    In general, its not a good idea to update a $watched variable within its own $watch listener. However, sometimes it may be unavoidable.

提交回复
热议问题