尝试使用$ scope。$ apply结果“$ digest has in progress”错误

时间:2015-09-15 10:36:44

标签: javascript angularjs

我的控制器上有一系列博客帖子,每次我更新数组时都希望视图相应更改。

这是部分html(唯一相关的是我使用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>

这是我的控制者:

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); 
            });

        });
    }

现在,当我点击我的控制器上触发类似功能的like按钮时。

控制台输出是:

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)

我正在其他帖子上搜索解决方案,但是虽然这个问题有很多帖子,但是没有人给出我在这里发生的事情的线索。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

  

您可以通过检查$ scope。$$阶段来检查$ digest是否已在进行中。

试试这个

  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); 
                });

    }

更多详情,请查看此讨论:AngularJS : Prevent error $digest already in progress when calling $scope.$apply()