$apply already in progress error

后端 未结 11 1262
暗喜
暗喜 2020-11-29 17:53

Stack trace:

Error: $apply already in progress
at Error ()
at beginPhase (file:///android_asset/www/built.min.js:7:22740)
at Object.Scope.$a         


        
11条回答
  •  长情又很酷
    2020-11-29 18:27

    In my case i use $apply with angular calendar UI to link some event:

    $scope.eventClick = function(event){           
        $scope.$apply( function() {
            $location.path('/event/' + event.id);
        });
    };
    

    After reading the doc of the problem: https://docs.angularjs.org/error/$rootScope/inprog

    The part Inconsistent API (Sync/Async) is very interesting:

    For example, imagine a 3rd party library that has a method which will retrieve data for us. Since it may be making an asynchronous call to a server, it accepts a callback function, which will be called when the data arrives.

    Since, the MyController constructor is always instantiated from within an $apply call, our handler is trying to enter a new $apply block from within one.

    I change the code to :

    $scope.eventClick = function(event){           
        $timeout(function() {
            $location.path('/event/' + event.id);
        }, 0);
    };
    

    Works like a charm !

    Here we have used $timeout to schedule the changes to the scope in a future call stack. By providing a timeout period of 0ms, this will occur as soon as possible and $timeout will ensure that the code will be called in a single $apply block.

提交回复
热议问题