2014-09-30 71 views
0

我有一个指令,显示从使用工厂的服务中检索的列表。主控制器更新服务使用的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,并且当服务获取新信息时,该指令更新视图。

谢谢。

+0

'this.subscribers = User.fetch({ID:this.id});'看起来很可疑对我来说,不应该被User.fetch返回一个承诺? – 2014-09-30 18:08:35

+0

是的,但是当承诺解决你获得数组? @KevinB – scanales 2014-09-30 18:23:37

+0

'SubscriberService.updateSubscriberList'被调用时不会**改变在'$ scope.subscribers = SubscriberService.getSubscribers();'中分配的引用。这里有几个选项。最简单的(但最不优雅的)将是使用中间对象,例如'data.subscribers'。 – 2014-09-30 18:48:45

回答

0

正如artur grzesiak在评论中指出的那样,$scope.subscribers的价值永远不会更新。而是将变量this.subscribers设置为服务中的新值,这意味着它们包含不同的对象。

相反,你可以使用这个服务:

Chat.service('SubscriberService', ['User', function(User){ 
    this.subscribers = []; 
    this.id = -1; 
    var self = this; 

    this.updateSubscriberList = function(id){ 
     console.log("fetching data"); 
     this.id = id 
     User.fetch({ id: id }, function(result) { 
      // Removed the original data and replaces it with the result. 
      // This keeps the reference to the original object the same. 
      // Use self, because I'm not sure where `this` refers to in this context. 
      angular.copy(result, self.subscribers); 
     }); 
    }; 

    this.getSubscribers = function(){ 
     return this.subscribers; 
    }; 
    return this; 
}]); 
+0

这不会触发$ watch功能,有什么想法吗? – scanales 2014-09-30 20:47:46

+0

尝试使用$ watchCollection而不是$ watch。 – 2014-10-01 06:53:59