Mat*_*att 9 javascript http-post angularjs
在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>
Run Code Online (Sandbox Code Playgroud)
谢谢.
有很多方法可以做到.我还想告诉你最简单的方法(根据你的需要).
假设您有'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()'.
Run Code Online (Sandbox Code Playgroud)
在你的.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;
};
Run Code Online (Sandbox Code Playgroud)
现在在适当的时候(你知道什么时候)你的下面的方法被调用.
$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();
};
}]);
Run Code Online (Sandbox Code Playgroud)
我希望这将有所帮助.
不确定是否有一种正确的方法,但你可以成功调用$ location.path().
request.success(function(){
$location.path('your path');
});
Run Code Online (Sandbox Code Playgroud)
要查看添加的评论(显然是您想要的),您可以使用:
request.success(function(response){
$scope.comments.push(response.data);
});
Run Code Online (Sandbox Code Playgroud)
如果您使用角度表达式和ng-repeat,您的内容将在页面上自动刷新.