4

I have AngularJS application that use $resource service to retrieve data using query() method and create new data using model.$save() method. This works fine exactly as the docs say it should.

My question is how to update my local data fetched using MyService.query() in the first place after I've changed it?

I took the most simple approach for now and I simply call the query() method again. I know this is the worst way efficiency-wise but it's the simplest one.

In my server-side I return the whole state-representation of the new model. How can I add the newly created model to the array of the local data?

UPDATE
I've end up simply pushing the model return from the server but I'll still be happy to know if that's the way to go. From what I can understand from the source code the return array is plan-old-javascript-array that I can manipulate myself.

This is the code I used

$scope.save = function () {
    var newComment = new CommentsDataSource();
    newComment.Content = $scope.todoText;
    newComment.$save({ id: "1" }, function (savedComment) {
        $scope.comments.push(savedComment);
    });
}
Ido Ran
  • 10,584
  • 17
  • 80
  • 143
  • 1
    I would get the whole data again. That allows seeing all the modifications that some other users could have made as well. – JB Nizet Jul 20 '13 at 13:26
  • I agree but that will still be very limited solution. For now I want to simplest solution not the one that cover all the bases. In the future I think I'll use WebSocket to get "real-time" updates which will solve the problem but that's outside the scope of this prof-of-concept. Thank you – Ido Ran Jul 20 '13 at 13:35
  • Then what's your question? You found a solution that suits your needs. Use it. – JB Nizet Jul 20 '13 at 13:37
  • There seem to be no information about this, I want to make sure I'm doing things right. – Ido Ran Jul 20 '13 at 13:51
  • You're doing it right. Angular uses bare-bones JavaScript objects. Adding a new instance to a list in the scope will refresh the list displayed on the page. – JB Nizet Jul 20 '13 at 13:56
  • Please write it as answer and I'll mark it as answered. Thank you – Ido Ran Jul 20 '13 at 14:08
  • Not an answer but a hack, Angular doesnot provide any way to refresh "$scope.comments" because this object is a promise that gets resolved once. – Thomas Decaux Jun 04 '16 at 09:02

1 Answers1

3

I would simply get the whole list again, to be able to see the modifications brought to the list by other users.

But if the solution you're using suits you, then use it. It's corrrect. Angular uses bare-bones JavaScript objects. Adding a new instance to a list in the scope will refresh the list displayed on the page.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255