【发布时间】: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;
});
但我只需要一个变量(不是具有属性的对象)。
<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;
});
它不起作用。为什么?
有没有好的方法(没有只有一个属性的对象或没有$watch)?
【问题讨论】:
标签: angularjs angularjs-scope angularjs-service