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

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

    try using

    $scope.applyAsync(function() {
        // your code
    });
    

    instead of

    if(!$scope.$$phase) {
      //$digest or $apply
    }
    

    $applyAsync Schedule the invocation of $apply to occur at a later time. This can be used to queue up multiple expressions which need to be evaluated in the same digest.

    NOTE: Within the $digest, $applyAsync() will only flush if the current scope is the $rootScope. This means that if you call $digest on a child scope, it will not implicitly flush the $applyAsync() queue.

    Exmaple:

      $scope.$applyAsync(function () {
                    if (!authService.authenticated) {
                        return;
                    }
    
                    if (vm.file !== null) {
                        loadService.setState(SignWizardStates.SIGN);
                    } else {
                        loadService.setState(SignWizardStates.UPLOAD_FILE);
                    }
                });
    

    References:

    1.Scope.$applyAsync() vs. Scope.$evalAsync() in AngularJS 1.3

    1. AngularJs Docs

提交回复
热议问题