目前我有一个评论部分,人们可以在帖子上发表评论:
<li ng-repeat="comment in post.comments" class="list-group-item comment">
<span>
<a ui-sref="user-profile({id: comment.userId})" class="postLink"><strong>{{comment.author}}</strong></a> {{comment.body}} <span>
<p class="commentActions">
<span am-time-ago="comment.created_at"></span> ·
<span ng-if="comment.userId == auth.profile.user_id" ng-click="deleteComment(comment._id)" class="commentDelete">Delete</span>
</p>
</li>
我想要完成的是,在添加新评论时刷新上面的列表:
<form name="addComments">
<div class="form-group">
<label for="comment">Comment</label>
<textarea class="form-control" id="comment" rows="2" ng-model="body" required></textarea>
</div>
<div class="form-group">
<button ng-click="addComment()" class="btn margin-left btn-success" ng-disabled="addComments.$invalid">Comment</button>
</div>
</form>
使用以下内容,我只需将注释添加到数据库,并将其链接到OP:
$scope.addComment = function(){
var dataObj = {
body : $scope.body,
userId : $scope.auth.profile.user_id,
author : $scope.auth.profile.name
};
postApi.postComment(id, dataObj)
.then(function(res){
$scope.post.comments.push(res);
});
$scope.body = "";
};
我的问题:如何刷新评论列表,以便我可以立即看到评论,而且我不需要刷新页面?
答案 0 :(得分:1)
以下是使用上述代码工作的一个非常简单的示例。我扯掉了&#34; postApi&#34;打电话,因为我不确定你是否使用服务/工厂/或其他东西来打电话给你。
http://codepen.io/jonathanburris/pen/EyjPgP
HTML
<div ng-app="app" ng-controller="controller">
<li ng-repeat="comment in post.comments" class="list-group-item comment">
<span>
<a ui-sref="user-profile({id: comment.userId})" class="postLink"><strong>{{comment.author}}</strong></a> {{comment.body}} <span>
<p class="commentActions">
<span am-time-ago="comment.created_at"></span> ·
<span ng-if="comment.userId == auth.profile.user_id" ng-click="deleteComment(comment._id)" class="commentDelete">Delete</span>
</p>
</li>
<form name="addComments">
<div class="form-group">
<label for="comment">Comment</label>
<textarea class="form-control" id="comment" rows="2" ng-model="body" required></textarea>
</div>
<div class="form-group">
<button ng-click="addComment()" class="btn margin-left btn-success" ng-disabled="addComments.$invalid">Comment</button>
</div>
</form>
</div>
的JavaScript
var app = angular.module('app', []);
app.controller('controller', function Controller($scope) {
$scope.post = {
comments: [
{
body: 'Some text',
userId: 'someId',
author: 'Some User',
created_at: 'today'
},
{
body: 'Some text',
userId: 'someId',
author: 'Some User',
created_at: 'yesterday'
}
]
}
$scope.addComment = function() {
var dataObj = {
body: $scope.body,
userId: 'someId',
author: 'Some User'
};
$scope.post.comments.push(dataObj);
$scope.body = "";
};
});
我建议如果您遵循此模式并且问题仍然存在,那么您的api调用可能会出错。如果是这种情况,那么&#34;然后&#34;从未开火。在api调用中添加一个catch,您可以轻松地将其作为您的问题消除。