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

前端 未结 28 2757
伪装坚强ぢ
伪装坚强ぢ 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:02

    The digest cycle is a synchronous call. It won't yield control to the browser's event loop until it is done. There are a few ways to deal with this. The easiest way to deal with this is to use the built in $timeout, and a second way is if you are using underscore or lodash (and you should be), call the following:

    $timeout(function(){
        //any code in here will automatically have an apply run afterwards
    });
    

    or if you have lodash:

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

    We tried several workarounds, and we hated injecting $rootScope into all of our controllers, directives, and even some factories. So, the $timeout and _.defer have been our favorite so far. These methods successfully tell angular to wait until the next animation loop, which will guarantee that the current scope.$apply is over.

提交回复
热议问题