AngularJS - POST后刷新

时间:2014-07-23 16:02:52

标签: javascript angularjs http-post

在Angular中使用http POST请求后刷新内容的正确方法是什么?

//controller.js
var hudControllers = angular.module('hudControllers', []);

hudControllers.controller('PropertyDetailsCtrl', 
  ['$scope','$window','$http', function ($scope,$window,$http) {

   //I want to reload this once the newCommentForm below has been submitted
   $http.get('/api/comments')
    .success(function(data) {$scope.comments = {"data":data};}})
    .error(function(data) {...);

   $scope.newCommentForm = function(){

      newComment=$scope.newComment;
      requestUrl='/api/comments';
      var request = $http({method: "post",url: requestUrl,data: {...}});
      request.success(function(){
        //How do I refresh/reload the comments?
        $scope.comments.push({'comment':'test'}); //Returns error - "TypeError: undefined is not a function"
      });
  };

}]);

//template.ejs
<div class="comment">
  <ul>
     <li ng-repeat="comment in comments.data">{{comment.comment}}</li>
 </ul>
</div>

感谢。

2 个答案:

答案 0 :(得分:6)

有很多方法可以做到。我还想告诉你最简单的方法(根据你的需要)。

让我们说你有&#39; first.html&#39;页面和&#39; PropertyDetailsCtrl&#39;与它相关联。 现在,在html中你可以这样写,

 with very first-div 
 <div ng-controller="PropertyDetailsCtrl" ng-init="initFirst()"> 
.... Your page contents...
</div>   (This will initialize your controller and you will have execution of your first method 'initFirst()'.

在你的.js方面......

var hudControllers = angular.module('hudControllers', []);

hudControllers.controller('PropertyDetailsCtrl', 
  ['$scope','$window','$http', function ($scope,$window,$http) {

   //I want to reload this once the newCommentForm below has been submitted
$scope.initFirst=function()
{


   $http.get('/api/comments')
    .success(function(data) {...})
    .error(function(data) {...);

        //You need to define your required $scope.....

     $scope.myVariable=data;

 };

现在在适当的时候(你知道什么时候)调用你的下面的方法。

   $scope.newCommentForm = function(){

      newComment=$scope.newComment;
      requestUrl='/api/comments';
      var request = $http({method: "post",url: requestUrl,data: {...}});
      request.success(function(data){
        //How do I refresh/reload the comments?
             //without calling anything else, you can update your $scope.myVariable here directly like this


       $scope.myVariable=data


      });

      //or else you can call 'initFirst()' method whenever and wherever needed like this,

    $scope.initFirst();


  };

}]);

我希望这会有所帮助。

答案 1 :(得分:5)

不确定是否有一种正确的方法,但您可以在成功时调用$ location.path()。

request.success(function(){
    $location.path('your path');
});

要查看添加的评论(显然是您想要的评论),您可以使用:

request.success(function(response){
    $scope.comments.push(response.data);
});

如果您使用角度表达式和ng-repeat,您的内容会在页面上自动刷新。