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

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

    This is my utils service:

    angular.module('myApp', []).service('Utils', function Utils($timeout) {
        var Super = this;
    
        this.doWhenReady = function(scope, callback, args) {
            if(!scope.$$phase) {
                if (args instanceof Array)
                    callback.apply(scope, Array.prototype.slice.call(args))
                else
                    callback();
            }
            else {
                $timeout(function() {
                    Super.doWhenReady(scope, callback, args);
                }, 250);
            }
        };
    });
    

    and this is an example for it's usage:

    angular.module('myApp').controller('MyCtrl', function ($scope, Utils) {
        $scope.foo = function() {
            // some code here . . .
        };
    
        Utils.doWhenReady($scope, $scope.foo);
    
        $scope.fooWithParams = function(p1, p2) {
            // some code here . . .
        };
    
        Utils.doWhenReady($scope, $scope.fooWithParams, ['value1', 'value2']);
    };
    

提交回复
热议问题