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

AngularJS bind variable from service to controller

我可以只将变量(不是对象)从服务绑定到控制器吗?

对于绑定对象,它有效(来自):

<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 的对象)?

你必须像这样使用一个对象: Demo

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

它将范围变量设置为 dataService 对象 reference 并将 ng-model 属性设置为 reference 属性.

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 的经验法则是始终包含 "dot"。

DEMO on PLNKR.