我是Angular的新手,我正在尝试设置一个基本的“提交评论”& “显示评论列表”页面。我想在提交评论后更新评论列表。目前我可以提交,但必须手动刷新页面才能看到它。
控制器:
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”来显示注释。我在这里走在正确的轨道上吗?当通过表单提交评论时,我可以做些简单的事情,评论列表会更新吗?
提前致谢!
答案 0 :(得分:1)
这些方面的某些内容可能会这样做,只需编辑语义以匹配您的程序。
在您的控制器中:
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();
})
};
所以基本上你的控制器告诉你的服务,"嘿,我正在观察你..如果你做了什么,请调用这个回叫功能",然后传递它getList
。该服务注册观察者,并在post()
返回成功后调用回调。