2014-02-19 14 views
1

我有兩種不同的視圖,它們具有音量滑塊。
我有$觀看每個音量滑塊模型,當它改變時,我調用setVolume方法。

$scope.$watch("speakerVolume", function() { 
    voipService.SpeakerVolumeChange($scope.speakerVolume * 655); 
});  

我想以某種方式觀看更改的音量,只要我在一個滑塊中更改音量,它也會在第二個中更改。
我聽說我可以把模型放在$ rootScope中,然後觀察它。
有沒有另一種解決方案呢?
感謝

回答

0

你可以像一個功能設置的第一個參數watchExpression:

app.controller('MainCtrl', function($scope, voipService) { 
    $scope.speakerVolume = voipService.speakerVolume; 
    $scope.$watch("speakerVolume", function (newValue) { 
    voipService.speakerVolume = newValue; 
    }); 
}); 

app.controller('SecondCtrl', function($scope, voipService) { 
    $scope.$watch(function() { return voipService.speakerVolume }, function (newValue) { 
    $scope.speakerVolume = newValue; 
    }); 
}); 

app.service('voipService', function() { 
    this.speakerVolume = 2; 
}); 

有兩個數據綁定:

<p ng-controller="MainCtrl"> 
    <input ng-model="speakerVolume" /> 
    {{speakerVolume}} 
</p> 
<p ng-controller="SecondCtrl">{{speakerVolume}}</p> 

Plunker

+0

謝謝。這是一個很好的解決方案,但它不適合我的問題,因爲我需要它雙向綁定,這裏是一種方法。如果我做兩個手錶,我最終會得到循環。 – liorafar

0

使用觀察家是那種總是醜陋。

也許這個https://egghead.io/lessons/angularjs-sharing-data-between-controllers會幫助你。

服務是單身人士,角度只有1個實例。 如果您在服務上設置了屬性,請將該服務傳遞給控制器​​並將此屬性綁定到範圍,但不會失去雙向綁定。

我建議你在服務中使用觀察器,並有2個變量:1觀察者正在觀察,1觀察者正在觀察值。

相關問題