简体   繁体   中英

trying to use $scope.$apply result in “$digest already in progress” error

I'm having an array of blog posts on my controller and each time I'm updating the array I want the view to change accordingly.

This is the partial html (The only thing that relevant is that I'm using ng-repeat):

<div ng-repeat="blog in blogCtrl.blogs">
    <blog author="blog.author" title="blog.title" content="blog.content"></blog>    
    <button ng-click="blogCtrl.like(blog._id)" class="btn btn-info glyphicon glyphicon-thumbs-up">{{blog.likes}}</button>
    <button ng-click="blogCtrl.remove()" class="btn btn-danger glyphicon glyphicon-remove"></button>
</div>

This is my controller:

like(blogId){
        this.BlogsDao.like(blogId).then(response => {
            // replacing the old blog with the updated one
            this.$scope.$apply(function(){
                var itemIndex = _.findIndex(this.blogs, function(item){
                    return item._id === blogId;
                });
                this.blogs.splice(itemIndex, 1, response.data); 
            });

        });
    }

Now when I'm clicking on the like button which triggers the like function on my controller.

console output is:

Error: [$rootScope:inprog] $digest already in progress
http://errors.angularjs.org/1.4.5/$rootScope/inprog?p0=%24digest
    at REGEX_STRING_REGEXP (angular.js:68)
    at beginPhase (angular.js:16235)
    at Scope.parent.$get.Scope.$apply (angular.js:15976)
    at blogs.ctrl.js:22
    at processQueue (angular.js:14634)
    at angular.js:14650
    at Scope.parent.$get.Scope.$eval (angular.js:15878)
    at Scope.parent.$get.Scope.$digest (angular.js:15689)
    at Scope.parent.$get.Scope.$apply (angular.js:15986)
    at done (angular.js:10511)

I was searching for the solution on other posts, but although there are many posts on this issue, no one gave my a clue on what is happening here.

What am I doing wrong?

You can check if a $digest is already in progress by checking $scope.$$phase.

Try this

  if(!$scope.$$phase) {
       this.$scope.$apply(function(){
                    var itemIndex = _.findIndex(this.blogs, function(item){
                        return item._id === blogId;
                    });
                    this.blogs.splice(itemIndex, 1, response.data); 
                });

    }

More details, Please checkout this discussions : AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM