AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

前端 未结 28 2786
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 22:31

I\'m finding that I need to update my page to my scope manually more and more since building an application in angular.

The only way I know of to do this is to call

28条回答
  •  臣服心动
    2020-11-21 23:24

    First of all, don’t fix it this way

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

    It does not make sense because $phase is just a boolean flag for the $digest cycle, so your $apply() sometimes won’t run. And remember it’s a bad practice.

    Instead, use $timeout

        $timeout(function(){ 
      // Any code in here will automatically have an $scope.apply() run afterwards 
    $scope.myvar = newValue; 
      // And it just works! 
    });
    

    If you are using underscore or lodash, you can use defer():

    _.defer(function(){ 
      $scope.$apply(); 
    });
    

提交回复
热议问题