2

I have 2 controllers using the same service, the first controller change the value of a property on the service, I need the second controller to know the property has changed to set the new value in his current $scope. I dont want to use broadcast, is there an elegant way to do this ?

Thank you.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
user3288840
  • 69
  • 2
  • 7
  • possible duplicate of [How to watch service variables?](http://stackoverflow.com/questions/12576798/how-to-watch-service-variables) – taxicala Sep 10 '15 at 19:57

2 Answers2

4

You could create an object in angular service,that will have various shareable properties in it. You could directly assign that variable with your controller scope variable. So that the reference of variable use by both controller are the same, like we gave to myCtrl1 and myCtrl2 will have only one copy in there scope variable. So changes in one variable updates the other one.

Markup

<body>
  <div ng-controller="myCtrl1">
    1st Controller
    <input type="text" ng-model="model1.prop1" />
    <input type="text" ng-model="model1.prop2" />
  </div>

  <div ng-controller="myCtrl2">
    2nd Controller
    <input type="text" ng-model="model2.prop1" />
    <input type="text" ng-model="model2.prop2" />
  </div>

</body>


app.service('dataService', function(){
  var dataService = this;
  dataService.model = {
     'prop1': '',
     'prop2': '',
  }
})

Controller1

app.controller('myCtrl1', function($scope, dataService){
     $scope.model1 = dataService.model;
});

Controller2

app.controller('myCtrl2', function($scope, dataService){
     $scope.model2 = dataService.model;
});

Demo Plunkr

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • perfect!, it didnt work because I registered as a factory instead of service. – user3288840 Sep 10 '15 at 20:29
  • @user3288840 no..same thing is possible with factory.. you got confused with factory and service. do read up on this http://stackoverflow.com/a/28262966/2435473 . – Pankaj Parkar Sep 10 '15 at 20:33
0

This will be fired once your value change and you can propagate it to new controller

$scope.$watch('passValueHere', function(event, passValueHere){
     $scope.controller2Value =   passValueHere;
});
Akshay Anand
  • 434
  • 5
  • 12