AngularJS - 在POST请求后刷新页面

9
在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个回答

7

有很多方法可以做到这一点,但我想向您展示最简单的方法(根据您的需求)。

假设您有一个名为“first.html”的页面,并且与之关联的是“PropertyDetailsCtrl”。 现在,在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
欢迎Matt。在接下来的学习中,你会遇到许多与Angularjs相关的问题。请随意提问。 - micronyks

5

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

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

要查看添加的评论(这显然是您想要的),您可以使用以下方法:
request.success(function(response){
    $scope.comments.push(response.data);
});

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


2
我认为OP并不是要求页面刷新,只是要求重新加载评论。 - runTarm
已编辑以反映这一点。 - Goodzilla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接