문제

I'm new to Angular and I'm trying to setup a basic "submit comment" & "show list of comments" page. I would like to have the list of comments be updated after submitting a comment. Currently I can submit, but must manually refresh the page to see it.

Controllers:

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;
    });
});

Service:

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?
});

The HTML form/list is super generic, I just use "ng-repeat" to display comments. Am I on the right track here? Is there something simple I can do so when a comment is submitted via form, the list of comments will be updated?

Thanks in advance!

도움이 되었습니까?

해결책

Something along these lines would probably do it, just edit the semantics to match your program.

In your controller:

var getList = function() {
    $scope.comments = CommentService.list();
};

CommentService.registerObserverCallback(getList);

And in your service:

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();
    })
 };

So basically your controller tells your service, "hey, I'm observing you.. If you do anything, call this call back function", and passes it getList. The service registers the observer, and calls the callback after the post() returns successful.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top