AngularJS将变量从服务绑定到控制器

时间:2016-05-08 01:20:09

标签: angularjs angularjs-scope angularjs-service

我是否只能将变量(非对象)从服务绑定到控制器?

对于绑定对象,它起作用(来自this answer):

<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>

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

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


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

Demo plnkr

但我只需要一个变量(不是具有属性的对象)。

<div ng-controller="myCtrl1">
  1st Controller
  <input type="text" ng-model="variable1"/>
</div>
<div ng-controller="myCtrl2">
  2nd Controller
  <input type="text" ng-model="variable2"/>
</div>

app.service('dataService', function() {
  this.variable = '';
});

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


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

Demo plnkr

它不起作用。为什么呢?

有没有很好的方法(没有只有一个属性或没有$watch的对象)?

2 个答案:

答案 0 :(得分:1)

您必须使用如下对象: Demo

app.service('dataService', function() {
    this.variable = {a:''};
});

答案 1 :(得分:1)

通过将范围变量设置为dataService对象引用并将ng-model属性设置为引用属性,可以正常工作。

JS

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

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

HTML

<div ng-controller="myCtrl1">
  1st Controller
  <input type="text" ng-model="ds1.variable"/>
</div>

<div ng-controller="myCtrl2">
  2nd Controller
  <input type="text" ng-model="ds2.variable"/>
</div>

ng-model的经验法则始终包括&#34; dot&#34;。

The command returns "OK" ..., and "ERROR" otherwise