【问题标题】:AngularJS $scope is not updating but returns 'digest already in progress'AngularJS $scope 没有更新,但返回“摘要已经在进行中”
【发布时间】:2015-09-10 13:18:00
【问题描述】:

我正在尝试创建新对象并将其插入数据库,但也会立即将其显示在我的页面上。这是我在页面上显示所有问题的功能:

$scope.questions = Question.find({
  filter: {
    order: 'timestamp DESC',
    include: ['account', 'category']
  }
}, function(questions, err){
  console.log(questions);
});

这是我创建新问题的函数:

$scope.sendQuestion = function(question){
  Question.create({
    title: $scope.question.title, 
    text: $scope.question.text,
    isAnonymous: $scope.question.isAnonymous,
    accountId: $scope.question.accountId, 
    categoryId: $scope.question.category.id, 
    timestamp: new Date()
  },function(question, err){
    $scope.questions.push(question);  //scope should update here?!
    //$scope.$apply();
  });
}

我正在创建新对象问题,然后插入 $scope.questions 列表,但新问题未显示在视图中。当我调用 $scope.$apply 时,我收到错误消息:'digest already in progress'

【问题讨论】:

  • 你能说明你定义问题的地方吗?
  • 问题是strongloop在定义数据库模型后创建的服务。
  • 你是怎么解决这个问题的?

标签: javascript angularjs angularjs-scope strongloop


【解决方案1】:

尝试使用 angular $timeout 服务

$scope.sendQuestion = function(question){
      Question.create({
        title: $scope.question.title, 
        text: $scope.question.text,
        isAnonymous: $scope.question.isAnonymous,
        accountId: $scope.question.accountId, 
        categoryId: $scope.question.category.id, 
        timestamp: new Date()
      },function(question, err){
        // use $timeout service
        $timeout(function()
        {
           $scope.questions.push(question);
        });
      });
    }

【讨论】:

    【解决方案2】:

    另一种方法是定义以下函数并使用它。

    $scope.safeApply = function (fn) {
        var phase = this.$root.$$phase;
        if (phase == '$apply' || phase == '$digest') {
            if (fn && (typeof (fn) === 'function')) {
                fn();
            }
        } else {
            this.$apply(fn);
        }
    };
    

    您的代码将如下所示。

    $scope.sendQuestion = function(question){
          Question.create({
            title: $scope.question.title, 
            text: $scope.question.text,
            isAnonymous: $scope.question.isAnonymous,
            accountId: $scope.question.accountId, 
            categoryId: $scope.question.category.id, 
            timestamp: new Date()
          },function(question, err){
            $scope.safeApply(function()
            {
               $scope.questions.push(question);
            });
          });
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2014-05-11
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多