Encountering a minor issue with Angular at the moment.
Employing the $ngResource
module to fetch "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();
});
Utilizing the ngRepeat
directive for displaying all comments:
<li ng-repeat="comment in comments">
{{ comment.comment }}
</li>
All seems well thus far.
The goal is to have the view automatically update when a new comment is submitted to the server. To achieve this, I added a method named submitComment
to the commentsController
$scope
, which gets triggered by 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);
});
};
});
Upon invoking this method, the comment is successfully sent to the server but the view doesn't update properly. The ngRepeat
directive is set on a li
. On submission of a comment, a new li
is generated (i.e. a new bullet point appears), however, it turns up empty. What could be causing this discrepancy?
Update: I've observed that if I move
$scope.comments.push(commentToSave);
outside the $save
callback, the view updates as expected. It seems like there may be alterations made to commentToSave
upon calling $save
, just a hunch.