Angular bind service property to a controller scope

不想你离开。 提交于 2019-12-12 09:12:40

问题


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


来源:https://stackoverflow.com/questions/32510495/angular-bind-service-property-to-a-controller-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!