変数(オブジェクトではない)のみをサービスからコントローラにバインドできますか?サービスからコントローラへのAngularJSバインド変数
は、バインドオブジェクトの場合、それは(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;
});
しかし、変数は1つだけ必要です(プロパティを持つオブジェクトではありません)。
<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;
});
動作しません。どうして?
これには良い方法がありますか(プロパティが1つだけのオブジェクトなし、または$watch
なし)ですか?
これは1つのプロパティを持つオブジェクトです(変数が1つだけ必要な場合は醜い解決策ですが、おそらく他に選択肢はありません)。 – mkczyk