Angular 将服务属性绑定到控制器范围 [英] Angular bind service property to a controller scope

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

问题描述

我有 2 个控制器使用相同的服务,第一个控制器更改服务上的属性值,我需要第二个控制器知道属性已更改以在其当前 $scope 中设置新值.我不想使用广播,有没有一种优雅的方法来做到这一点?

谢谢.

解决方案

您可以在 angular 服务中创建一个 object,其中将具有各种可共享的属性.您可以使用控制器范围变量直接分配该变量.这样两个控制器使用的变量引用是相同的,就像我们给 myCtrl1myCtrl2 一样,在那里的作用域变量中只有一个副本.因此,一个变量的变化会更新另一个变量.

标记

<div ng-controller="myCtrl1">第一控制器<input type="text" ng-model="model1.prop1"/><input type="text" ng-model="model1.prop2"/>

<div ng-controller="myCtrl2">第二控制器<input type="text" ng-model="model2.prop1"/><input type="text" ng-model="model2.prop2"/>

app.service('dataService', function(){var dataService = this;数据服务.模型 = {'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

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.

解决方案

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

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

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆