Angular bind service property to a controller scop

2019-04-13 19:13发布

问题:

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.

回答1:

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



回答2:

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