我正在服务器端使用 Java 编写一个网上商店,在客户端使用 Angular 编写。我在使用评论部分后遇到了问题。我的评论列表在我第二次单击发送按钮后刷新,其中包含之前写的评论。因此,要查看我的评论,我需要首先单击将其发送到服务器,然后单击刷新评论数组(但第二次单击后它将发送新评论但不会渲染它)。 请帮忙,我是 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();
}]);
模板:
<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>
最佳答案
似乎您正在并行运行这两个函数:
$scope.send = function () {
sendComment();
getAllComments();
};
根据您的评论,您将在发送(存储)新消息之前收到消息。 您应该做出 promise 来解决此问题:
$scope.send = function () {
sendComment();
};
var sendComment = function () {
var comment = {'userName': 'danko', 'content': $scope.comment};
$http.post(url, comment).then(function(){
getAllComments();
})
};
关于javascript - Angular 代码在第二次单击后起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41212561/