我閱讀以下問題和答案: Share data between AngularJS controllers, Update scope value when service data is changed, 和Angular: Update service and share data between controllers。在Angular中的控制器之間共享數據,觀看還是不觀看?
我的問題是關於提供的答案。答案通常建議$watch
,我不明白爲什麼。
我想控制器之間共享一些價值,所以我只是這樣做(這是代碼的簡化):
angular.module('app', [])
.factory('SomeSharedData', function()
{
return { 'pointer' : { 'someKey' : 'someValue' }};
})
.controller('Controller1', ['$scope', 'SomeSharedData', function($scope, SomeSharedData) {
$scope.pointer = SomeSharedData.pointer;
}])
.controller('Controller2', ['$scope', 'SomeSharedData', function($scope, SomeSharedData)
{
$scope.pointer = SomeSharedData.pointer;
}]);
是由於某種原因,這個inheritly邪?
爲什麼使用這樣的:
$scope.$watch(function() { return SomeSharedData.someKey(); }, function (newValue) {
if (newValue) $scope.someKey = newValue;
});
取決於你想要達到的目標。在你的第一個例子中,當控制器第一次運行時,'pointer'的值將被設置,並且如果'SomeSharedData.pointer'在別處改變,將不會更新。如果這就是你所需要的,那麼$ watch是不必要的。如果你想要引用'SomeSharedData.pointer'的所有實例之間的數據綁定,你需要使用類似代碼的第二部分。 – 2014-09-21 15:45:17