samedi 18 avril 2015

When using the ngResource module, my model is not updating properly

I have a small problem with Angular. I am using the $ngResource module to resolve "comments" from my server:



var app = angular.module('app', ['ngResource']);
app.factory('comment', function($resource) {
return $resource('/comments');
});
app.controller('commentsController', function($scope, comment) {
$scope.comments = comment.query();
});


I use the ngRepeat directive to show all comments:



<li ng-repeat="comment in comments">
{{ comment.comment }}
</li>


So far, so good.


I want to make it so that, when a comment is submitted to the server, the $scope.comments property is updated, updating the view. I updated the commentsController $scope to have a method: submitComment which is invoked from an ngSubmit directive:



app.controller('commentsController', function($scope, comment) {

$scope.comments = comment.query();

$scope.submitComment = function() {
var commentToSave = new comment();
angular.copy($scope.comment, commentToSave);
commentToSave.$save(function() {
$scope.comments.push(commentToSave);
});
};
});


When this method is invoked, the "comment" is successfully sent to the server however, the view is not updated properly. Recall that my ngRepeat directive is defined on a li. When I submit a "comment", a new li is created (i.e. a new bullet point is rendered), but the body is empty. What am I doing wrong?


Update: I noticed that, if I call $scope.comments.push(commentToSave); outside the $save callback, the view is updated correctly. I think commentToSave is being changed when I call $save, something like that anyway.


Aucun commentaire:

Enregistrer un commentaire