简体   繁体   English

AngularJS-双向绑定

[英]AngularJS - two way binding

I have the following JSFiddle 我有以下JSFiddle

I want two way binding for these sliders that will eventually set the value in the service 我想为这些滑块进行两种方式的绑定,这些绑定最终将在服务中设置值
Meaning that the on is changed also the second and the value in the service also 意味着on也被更改为第二,服务中的值也被更改

HTML: 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>

JS: JS:

var myApp = angular.module('myApp', []);

myApp.controller('FirstCtrl', function($scope, voipService) {
  $scope.speakerVolume = voipService.speakerVolume;
  $scope.$watch("speakerVolume", function (newValue) {
      voipService.speakerVolume = newValue;
      voipService.setVolume(newValue);
  });
});

myApp.controller('SecondCtrl', function($scope, voipService) {
  $scope.speakerVolume = voipService.speakerVolume;
  $scope.$watch("speakerVolume", function (newValue) {
      $scope.speakerVolume = newValue;
      voipService.setVolume(newValue);
  });
});

myApp.service('voipService', function() {
    this.speakerVolume = 50;

    this.setVolume = function(newVal){
        self.speakerVolume = newVal;
    }
});  

Final Answer in Fiddle: 小提琴的最终答案:
Fiddle - Final Answer 小提琴-最终答案

one way is to watch also service value, not just scope variable 一种方法是观察服务价值,而不仅仅是范围变量

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;
    }
});

second way is to use $broadcast in the service (when the value is changed) and update values in all controllers when this custom event is fired 第二种方法是在服务中使用$broadcast (更改值时),并在触发此自定义事件时更新所有控制器中的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM