角绑定服务属性设置为一个控制器范围 [英] Angular bind service property to a controller scope

查看:167
本文介绍了角绑定服务属性设置为一个控制器范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用相同的服务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 ?

感谢您。

推荐答案

您可以创建一个对象的角度服务,将在它有各种各样的共享特性。你可以将该变量直接分配与控制器范围的变量。因此,通过两个控制器变量使用参考是相同的,就像我们给了 myCtrl1 myCtrl2 将只有在那里范围的变量一个副本。因此,在一个变量的变化更新的另一个。

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.

标记

<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': '',
  }
})

控制器1

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

控制器2

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

演示Plunkr

这篇关于角绑定服务属性设置为一个控制器范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆