我是 Angular 的新手,我正在尝试设置一个基本的“提交评论”和“显示评论列表”页面。我想在提交评论后更新评论列表。目前可以提交,但必须手动刷新页面才能看到。
Controller :
app.controller('FormController', function($scope, CommentService) {
$scope.comment = {}; //will be populated by basic form
$scope.submit = function() {
return CommentService.post($scope.comment).then(function(){
$scope.comment = ""; //blanks out form on POST
});
}
});
app.controller('CommentsController' function($scope, CommentService) {
CommentService.list().then(function(comments){
$scope.comments = comments.data;
});
});
服务:
app.service('CommentService', function($http) {
this.post = function(comment) {
return $http.post('/api/v1/comments/', comment);
};
this.list = function() {
return $http.get('/api/v1/comments/').
success(function(data) {
return data;
});
};
//How do I connect the two controllers?
});
HTML 表单/列表非常通用,我只是使用“ng-repeat”来显示评论。我走在正确的轨道上吗?当通过表单提交评论时,有什么简单的方法可以更新评论列表吗?
提前致谢!
最佳答案
按照这些思路可能会做到这一点,只需编辑语义以匹配您的程序。
在你的 Controller 中:
var getList = function() {
$scope.comments = CommentService.list();
};
CommentService.registerObserverCallback(getList);
在您的服务中:
var observerCallbacks = [];
// register the observer's callback in our callback list.
this.registerObserverCallback = function(callback){
observerCallbacks.push(callback);
};
// function to notify our observers and call the callback they registered with
var notifyObservers = function(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
this.post = function(comment) {
return $http.post('/api/v1/comments/', comment).success(function(data, status, headers, config) {
notifyObservers();
})
};
基本上,您的 Controller 会告诉您的服务,“嘿,我在观察您……如果您做了任何事情,请调用此回调函数”,然后将其传递给 getList
。服务注册观察者,并在post()
返回成功后调用回调。
关于javascript - 使用服务在 Angular 中提交表单后如何更新列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23143754/