Question

I have the following 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

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:

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

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top