发送评论后的AngularJS刷新视图

时间:2016-03-28 11:47:12

标签: angularjs

我在AngularJS中创建了控制器,以显示并向我的休息端发送评论。如何在用户点击并发送评论后刷新评论列表?

我的控制器:

.controller('CommentController',
    function($scope, $routeParams, NewsModel){

      var newsId = $routeParams.id;
      path = 'getCommetnsByNewsId/'+newsId;

      var comm = this;

      var data = new Date().toLocaleString();

      $scope.createComm = function(comment){
        NewsModel.createComment(angular.extend({},
          {data: data, newsId: newsId}, comment)).then(function (result){
          initCreateComm();

        })
      }
      function initCreateComm(){
        comm.newComm = { comment: '', author: ''};
      }

      NewsModel.getCommentById().then(function (result){
        $scope.comments = result.data;
        console.log($scope.comments);
      });

    })

服务:

.service('NewsModel', function($http, ENDPOINT_URI){

    var service = this;

    function getUrl(){
      return ENDPOINT_URI + path;
    }

    service.all = function(){
      return $http.get(getUrl());
    }

    service.getCommentById = function(){
      return $http.get(getUrl());
    }

    service.createComment = function(comment){
      return $http.post(getUrl(),comment);
    }

  });

和HTML:

<!-- Comments Form -->
  <div class="well">
    <h4>Leave comment:</h4>
    <form role="form" ng-submit="createComm(newComment)">
      <div class="form-group">
        <input type="text" class="form-control" ng-model="newComment.author"  placeholder="Autor">
      </div>
      <div class="form-group">
        <textarea class="form-control" ng-model="newComment.comment" rows="3"></textarea>
      </div>
      <button type="submit" class="btn btn-primary">Wyślij</button>
    </form>
  </div>

  <hr>


  <div ng-repeat="comm in comments">

  <div class="media">

    <div class="media-body">
      <h4 class="media-heading">{{comm.author}}
        <small>{{comm.data}}</small>
      </h4>
      {{comm.comment}}
    </div>
  </div>

  </div>

</div>

怎么做?

2 个答案:

答案 0 :(得分:0)

当您需要刷新评论列表时,只需致电您的服务器以检索所有评论。

function fetchComments(){
    NewsModel.all().then(function(res){
        $scope.comments = res;
    });
}

然后在想要更新注释时调用fetchComments()。

答案 1 :(得分:0)

以下是您收到评论的方式:

NewsModel.getCommentById().then(function (result){
    $scope.comments = result.data;
    console.log($scope.comments);
});

所以你需要将它包装在一个函数中并在添加新注释后调用它:

$scope.getComments = function() {
    NewsModel.getCommentById().then(function (result){
        $scope.comments = result.data;
        console.log($scope.comments);
    });
};
$scope.getComments(); // Init the comments as the controller loades

并在$scope.createComm = function(comment){

的末尾添加此内容
$scope.createComm = function(comment){
    NewsModel.createComment(angular.extend({},
      {data: data, newsId: newsId}, comment)).then(function (result){
      initCreateComm();
      $scope.getComments(); // Update comments
    })
}