AngularJS-双向绑定
我有以下几点 我希望为这些滑块提供双向绑定,最终在服务中设置值AngularJS-双向绑定,angularjs,data-binding,view,uislider,watch,Angularjs,Data Binding,View,Uislider,Watch,我有以下几点 我希望为这些滑块提供双向绑定,最终在服务中设置值 也就是说,第二次更改on,服务中的值也更改 HTML: <div> <div ng-controller="FirstCtrl"> <input type="range" ng-model="speakerVolume" /> {{speakerVolume}} </div> <div ng-controller
也就是说,第二次更改on,服务中的值也更改 HTML:
<div>
<div ng-controller="FirstCtrl">
<input type="range" ng-model="speakerVolume" />
{{speakerVolume}}
</div>
<div ng-controller="SecondCtrl">
<input type="range" ng-model="speakerVolume" />
{{speakerVolume}}
</div>
</div>
小提琴的最终答案:一种方法是观察服务价值,而不仅仅是范围变量
var myApp = angular.module('myApp', []);
myApp.controller('FirstCtrl', function($scope, voipService) {
$scope.speakerVolume = voipService.speakerVolume;
$scope.$watch("speakerVolume", function (newValue) {
voipService.speakerVolume = newValue;
});
$scope.$watch(function() {
return voipService.speakerVolume;
}, function (newValue) {
$scope.speakerVolume = newValue;
});
});
myApp.controller('SecondCtrl', function($scope, voipService) {
$scope.speakerVolume = voipService.speakerVolume;
$scope.$watch("speakerVolume", function (newValue) {
voipService.setVolume(newValue);
});
$scope.$watch(function(){
return voipService.speakerVolume;
}, function (newValue) {
$scope.speakerVolume = newValue;
});
});
myApp.service('voipService', function() {
var self = this;
this.speakerVolume = 50;
this.setVolume = function(newVal){
self.speakerVolume = newVal;
}
});
第二种方法是在服务中使用
$broadcast
(当值更改时),并在触发此自定义事件时更新所有控制器中的值。但这不是双向的。当使用第二个滑块滑动时,它不会移动第一个滑块。这是因为您没有在voipService中定义自变量,我忽略了它。。。现在就试试看,你是对的!我已经在问题中添加了最后编辑的答案。非常感谢。
var myApp = angular.module('myApp', []);
myApp.controller('FirstCtrl', function($scope, voipService) {
$scope.speakerVolume = voipService.speakerVolume;
$scope.$watch("speakerVolume", function (newValue) {
voipService.speakerVolume = newValue;
});
$scope.$watch(function() {
return voipService.speakerVolume;
}, function (newValue) {
$scope.speakerVolume = newValue;
});
});
myApp.controller('SecondCtrl', function($scope, voipService) {
$scope.speakerVolume = voipService.speakerVolume;
$scope.$watch("speakerVolume", function (newValue) {
voipService.setVolume(newValue);
});
$scope.$watch(function(){
return voipService.speakerVolume;
}, function (newValue) {
$scope.speakerVolume = newValue;
});
});
myApp.service('voipService', function() {
var self = this;
this.speakerVolume = 50;
this.setVolume = function(newVal){
self.speakerVolume = newVal;
}
});