2016-05-08 27 views
0

変数(オブジェクトではない)のみをサービスからコントローラにバインドできますか?サービスからコントローラへの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; 
}); 

Demo plnkr

しかし、変数は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; 
}); 

Demo plnkr

動作しません。どうして?

これには良い方法がありますか(プロパティが1つだけのオブジェクトなし、または$watchなし)ですか?

答えて

1

JS

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

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

ng-modelと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> 

親指のルールは常に "ドット" が含まれます。

DEMO on PLNKR

1

あなたはそうのようなオブジェクトを使用する必要があります。それはdataServiceオブジェクト参照参照財産へng-model属性にスコープ変数を設定することで動作します Demo

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

これは1つのプロパティを持つオブジェクトです(変数が1つだけ必要な場合は醜い解決策ですが、おそらく他に選択肢はありません)。 – mkczyk

関連する問題