[英]Angular.js: Two-Way data binding across multiple controllers
我在Angular中有這個代碼結構:
app.controller(AlphaCtrl, function(interstellarService){
$scope.interstellarService = {
routeToEarth: interstellarService.get('routeToEarth'),
}
})
app.controller(CentauriCtrl, function(interstellarService){
$scope.interstellarService = {
routeToEarth: interstellarService.get('routeToEarth'),
}
})
星際服務存儲在瀏覽器存儲中:
appServices.factory('interstellarService', function ($rootScope, $localStorage){
return {
set: function(entidy, value) {
$localStorage[entidy] = value;
},
get: function(entidy) {
if ($localStorage[entidy] !== undefined) {
return $localStorage[entidy];
} else return false;
}
}
});
現在,當我通過setter方法更改了AlphaCtrl
的routeToEarth
屬性時,我希望CentauriCtrl能夠相應地更新,因為數據在每個控制器上綁定到服務,如:
AlphaCtrl < - data - > interstellarService < - data - > CentauriCtrl
這是行不通的:我想在Centauri-HTML中使用和共享存儲在routeToEarth
中的值,例如
<li>
<a>
{{interstellarService.routeToearth}} && 'Timetravel' || 'Wormhole' }}
</a>
</li>
我在這里錯過了什么?
您需要進行某些更改才能使其運行。
AlphaCtrl
和CentauriCtrl
的報價 AlphaCtrl
和CentauriCtrl
控制器注入$ scope appServices
for service和app
for controller 腳本
var appServices = angular.module('app', ['ngStorage']);
appServices.factory('interstellarService', function ($rootScope, $localStorage) {
return {
set: function (entidy, value) {
$localStorage[entidy] = value;
},
get: function (entidy) {
if ($localStorage[entidy] !== undefined) {
return $localStorage[entidy];
} else return false;
}
}
});
appServices.controller('AlphaCtrl', function (interstellarService, $scope) {
interstellarService.set('routeToEarth', 'Alpha');
$scope.interstellarService = {
routeToEarth: interstellarService.get('routeToEarth'),
}
console.log('AlphaCtrl value::', $scope.interstellarService);
})
appServices.controller('CentauriCtrl', function (interstellarService, $scope) {
interstellarService.set('routeToEarth', 'Centauri');
$scope.interstellarService = {
routeToEarth: interstellarService.get('routeToEarth'),
}
console.log('CentauriCtrl value::', $scope.interstellarService);
})
HTML
<div ng-controller="AlphaCtrl">
{{interstellarService.routeToEarth}}
</div>
<div ng-controller="CentauriCtrl">
{{interstellarService.routeToEarth}}
</div>
當我在AlphaCtrl
更改它時,將它放入我的CentauriCtrl
終於顯示了通往地球的路線。
$rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
$scope.interstellarService = {
routeToEarth: interstellarService.get('routeToEarth'),
}
});
向此SO問題致敬: AngularJS Bootstraps Navbar
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.