我有一个指令,显示从使用工厂的服务中检索的列表。主控制器更新服务使用的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