Javascript 从工厂更新指令

Javascript 从工厂更新指令,javascript,angularjs,Javascript,Angularjs,我有一个指令,显示从使用工厂的服务检索到的列表。主控制器更新服务用于获取所需列表的id。发生这种情况时,我需要更新指令,但它似乎无法正常工作,可能我使用了错误的方法。这是我的密码: Chat.service('SubscriberService', ['User', function(User){ this.subscribers = []; this.id = -1; this.updateSubscriberList = function(id){

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


谢谢。

正如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;
}]);

this.subscribers=User.fetch({id:this.id})
在我看来很可疑,User.fetch是否应该返回一个承诺?是的,但当承诺解决时,您得到了数组@调用KevinB
SubscriberService.updateSubscriberList
时,不会更改在中分配的引用:
$scope.subscribers=SubscriberService.getSubscribers()。这里有几个选项。最简单的(但我认为最不优雅的)是使用中间对象,例如
数据。订阅者
@arturgrzesiak您能详细说明一下吗?这不会触发$watch函数,有什么想法吗?尝试使用$watchCollection而不是$watch。