2016-02-27 59 views
3

我在使用其他控制器對其進行某些更改時觀察服務中的多個變量時遇到問題。 我有以下幾點:Angularjs watchGroup()不能使用服務更改

angular.module('carApp').controller('CarListCtrl', function ($scope, CarService) { 
    $scope.carList = CarService.carList 
    $scope.initalAmount = CarService.initialAmount 
    $scope.startDate = CarService.startDate 

    $scope.$watchGroup(['carList', 'initialAmount', 'startDate'], 
     function (newValues, oldValues, $scope) { 
      console.log(newValues); 
     }); 
}); 

其他控制器更新值在服務所有的時間,但watchGroup永遠不會觸發了......

我已經創建一個簡單的手錶直接針對服務檢查是否工作,它的工作......所以我想象,watchGroup應該直接針對服務變量,但我無法找到如何做到這一點....

這裏是工作的簡單手錶:

$scope.$watch(function() { 
    return CarService.carList 
}, function (newVal, oldVal) { 
    console.log(newVal); 
}); 

我該怎麼做才能使它適用於多個服務變量?

更新1:

只是一個更新...如果我嘗試只用一個元素watchgroup,例如$範圍$ watchGroup([ '卡洛斯'],...它的作品,所以我嘗試。每一個和它的作品每一次,但只要我添加更多的元素,它停止工作...很討厭......

韓國社交協會再次傢伙!

回答

2

就關閉這個,人們angularjs github上幫助我:這裏是誰需要誰anwser:

watchGroup數組內的每個值都可以是表達式或函數,因此您可以在WatchGroup中使用三種不同的函數。 http://plnkr.co/edit/nMmPt808xAFXqjJ6yEoc?p=preview

$scope.$watchGroup([ 
    function() { 
     return myService.valueOne() 
    }, 
    function() { 
     return myService.valueTwo() 
    }  
    ], function(newValues, oldValues) { 
    $scope.valueOne = newValues[0] 
    $scope.valueTwo = newValues[1] 
    }) 

你的第一個例子可能不工作,因爲你的其他控制器在你的服務,這意味着你必須在你的控制器和你的startDate不同的價值觀不同的對象分配到initialAmount且StartDate新值。它可能適用於carList,因爲你只是添加/刪除項目,這意味着它在你的控制器和你的服務中仍然是同一個對象。