javascript - 使用服务在 Angular 中提交表单后如何更新列表?

标签 javascript forms angularjs frontend

我是 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/

相关文章:

javascript - 从 js 文件生成 .d.ts 的过程

android - 单击视觉状态更改的按钮

jquery - Angularjs:jquery可选择子元素点击问题

javascript - 让 chrome、IE 8 和 Firefox 提交相同表单的奇怪方法

angularjs - 在 Mocha 测试套件中触发 AngularJS 指令上的点击事件

javascript - 带有可选范围值的指令和使用 html 中的文字设置的困难

javascript - 语法帮助 - JavaScript 中的 HTML

javascript - 如何在同一页面上显示用户提交的数据

javascript - 按下回车键时表单未提交

javascript - 输入数字类型美元符号