When is it safe to use $scope.$apply()?

前端 未结 7 1779
执笔经年
执笔经年 2020-12-09 17:47

I guess the title is pretty much clear what I am asking. I have created this fiddle : http://jsfiddle.net/Sourabh_/HB7LU/13142/

In the fiddle I have tried to replica

7条回答
  •  猫巷女王i
    2020-12-09 18:29

    The $apply, should be used when the code is not executed in a angular digest loop. In normal circumstances we will not need to use it, but we might have to use it if we have a code that is called from a jQuery event handler or from methods like setTimeout(). Even if you have a function that is called from another angular function like a watch or angular event handlers you need not use $apply() as those scripts are executed in the digest cycle.

    One safe way is to check the $scope.$$phase param before calling $scope.$apply() like

    if($scope.$$phase){
        $scope.$apply();
    }
    

    In your case but you can use $timeout as suggested in the another answer

    • What is $$phase in AngularJS?
    • Why is using if(!$scope.$$phase) $scope.$apply() an anti-pattern?

提交回复
热议问题