Reputation: 17
I'm writing an internet shop using Java on the server-side, and angular on the client. I ran into a problem after working with the comment section. My comment list refreshes after the second time I click on send button, with the comment written before. So, to see my comment I need to click first to send it to server, and second to refresh comment array (but after second click it will send new comment but not render it). Please help, I’m newbie to angular
var productApp = angular.module('productApp', []);
productApp.controller('productCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
var url = $location.absUrl() + '/comments';
$scope.comments = [];
function getAllComments() {
$http.get(url).then(function (response) {
$scope.comments = response.data;
});
}
var sendComment = function () {
var comment = {'userName': 'danko', 'content': $scope.comment};
$http.post(url, comment);
};
$scope.send = function () {
sendComment();
getAllComments();
};
getAllComments();
}]);
Template:
<ul class="media-list">
<li class="media">
<div ng-repeat="comment in comments" class="media">
<a class="pull-left">
<img class="media-object img-circle" src="/resources/img/user.png"
style="width: 64px; height: 64px;">
</a>
<div class="media-body">
<h4 class="media-heading">{{comment.userName}}</h4>
{{comment.content}}
</div>
</div>
</li>
<br>
<div class="input-group">
<textarea class="form-control custom-control" ng-model="comment" placeholder="Leave feedback" rows="3"
style="resize:none"></textarea>
<span class="input-group-addon btn btn-success" ng-click="send()">Send</span>
</div>
</ul>
Upvotes: 0
Views: 1467
Reputation: 2304
Seems like you are running this two functions in parallel:
$scope.send = function () {
sendComment();
getAllComments();
};
Based on your comments, you are getting the meesages before the new message is sent (stored). You should make a promise, to resolve this:
$scope.send = function () {
sendComment();
};
var sendComment = function () {
var comment = {'userName': 'danko', 'content': $scope.comment};
$http.post(url, comment).then(function(){
getAllComments();
})
};
Upvotes: 6