2014-04-17 9 views
3

我是Angular的新手,我正在嘗試設置基本的「提交評論」&「顯示評論列表」頁面。我希望在提交評論後更新評論列表。目前我可以提交,但必須手動刷新頁面才能看到它。如何在使用服務提交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重複」 來顯示評論。我在正確的軌道上嗎?有沒有簡單的我可以這樣做,當通過表單提交評論時,評論列表將被更新?

在此先感謝!

+0

看看這個:http://stackoverflow.com/questions/9293423/can-one-controller-call-another-in-angularjs – welbornio

回答

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()返回成功後調用回調。

+0

謝謝!我能夠得到這個工作。我看着你的另一個鏈接,它看起來像使用$ rootScope進行廣播的「最乾淨」的方式(但也許是危險的)?傳遞迴調似乎很奇怪。 – WBC

+0

很高興工作!我發現觀察者方法通常是首選方式,但這絕對是一個可以考慮的選項。好狩獵! – welbornio

相關問題