从工厂更新指令

时间:2014-09-30 18:03:02

标签: javascript angularjs

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

感谢。

1 个答案:

答案 0 :(得分: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;
}]);