我有一個指令,顯示從使用工廠的服務中檢索的列表。主控制器更新服務使用的id以獲取所需的列表。我需要在發生這種情況時更新指令,並且似乎無法使其工作,也許我使用了錯誤的方法。這是我的代碼:從工廠更新指令
Chat.service('SubscriberService', ['User', function(User){
this.subscribers = [];
this.id = -1;
this.updateSubscriberList = function(id){
console.log("fetching data");
this.id = id
this.subscribers = User.fetch({ id: this.id });
}
this.getSubscribers = function(){
return this.subscribers;
}
return this;
}]);
Chat.directive('subscribersList', function(SubscriberService){
return {
restrict: 'E',
templateURL: 'angular/templates/subscribers_list.html',
controller: function($scope){
$scope.subscribers = SubscriberService.getSubscribers();
$scope.$watch('subscribers', function(value){
console.log("watch triggered");
$scope.subscribers = SubscriberService.getSubscribers();
});
}
}
});
Chat.controller('MainCtrl', function($scope, $stateParams, SubscriberService){
var id = $stateParams.id;
//update the current id when the URL changes
SubscriberService.updateSubscriberList(id);
});
任何想法?我需要MainCtrl來更新服務中的id,並且當服務獲取新信息時,該指令更新視圖。
謝謝。
'this.subscribers = User.fetch({ID:this.id});'看起來很可疑對我來說,不應該被User.fetch返回一個承諾? – 2014-09-30 18:08:35
是的,但是當承諾解決你獲得數組? @KevinB – scanales 2014-09-30 18:23:37
'SubscriberService.updateSubscriberList'被調用時不會**改變在'$ scope.subscribers = SubscriberService.getSubscribers();'中分配的引用。這裏有幾個選項。最簡單的(但最不優雅的)將是使用中間對象,例如'data.subscribers'。 – 2014-09-30 18:48:45