2014-09-30 72 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