【问题标题】:How to update list after submitting form in Angular with a service?使用服务在 Angular 中提交表单后如何更新列表?
【发布时间】:2014-04-17 21:26:27
【问题描述】:

我是 Angular 的新手,我正在尝试设置一个基本的“提交评论”和“显示 cmets 列表”页面。我希望在提交评论后更新 cmets 列表。目前可以提交,但必须手动刷新页面才能看到。

控制器:

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”来显示 cmets。我在正确的轨道上吗?当通过表单提交评论时,我可以做一些简单的事情吗? cmets 列表将被更新?

提前致谢!

【问题讨论】:

标签: javascript forms angularjs frontend


【解决方案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()返回成功后调用回调。

【讨论】:

  • 谢谢!我能够让它工作。我查看了您的其他链接,这似乎是使用 $rootScope 进行广播的“最干净”的方式(但可能很危险)?传递回调似乎很奇怪。
  • 很高兴它成功了!我发现观察者方法通常是首选方法,但这绝对是一个值得考虑的选择。很好的狩猎!
猜你喜欢
  • 2016-10-02
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 2020-07-04
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 2019-12-18
相关资源
最近更新 更多