0

I am trying to create new object and insert it in database, but also show it on my page immediately. Here is my function for showing all the questions on the page:

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

And here is my function for creating new question:

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

I am creating new object Question, and then insert in the $scope.questions list, but new question doesn't showing on the view. When I call $scope.$apply I get the error: 'digest already in progress'

neeev
  • 23
  • 8

2 Answers2

0

Try use angular $timeout service

$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);
        });
      });
    }
Maciej Wojsław
  • 403
  • 2
  • 10
0

One more way is to define the following function and use it.

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

Your code will look like this.

$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);
        });
      });
    }
SaiGiridhar
  • 886
  • 1
  • 13
  • 28