2015-09-10 109 views
0

我想創建新的對象,並將其插入數據庫,但也立即顯示在我的網頁上。這裏是我在網頁上展示的所有問題的功能:

$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列表,但新的問題沒有在視圖中顯示。當我調用$範圍$申請我得到的錯誤:「已經在進行中消化」

+0

你能說明你在哪裏定義問題嗎? – IfTrue

+0

問題是在定義數據庫模型後使用strongloop創建的服務。 – neeev

+0

你是如何解決這個問題的? – user2099451

回答

0

嘗試使用角$超時服務

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

還有一個方法是定義如下的功能和使用它。

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