【问题标题】:AngularJS bind variable from service to controllerAngularJS 将变量从服务绑定到控制器
【发布时间】:2016-09-02 21:06:12
【问题描述】:

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

对于绑定对象,它可以工作(来自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)?

【问题讨论】:

    标签: angularjs angularjs-scope angularjs-service


    【解决方案1】:

    它将作用域变量设置为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 的经验法则总是包含一个“点”。

    DEMO on PLNKR

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 它是具有一个属性的对象(如果我只需要一个变量,这有点难看,但我可能别无选择)。
      猜你喜欢
      • 2014-09-05
      • 1970-01-01
      • 2014-01-24
      • 2019-03-05
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 2014-05-09
      相关资源
      最近更新 更多