我在Angular中有这个代码结构:
app.controller(AlphaCtrl, function(interstellarService){
$scope.interstellarService = {
routeToEarth: interstellarService.get('routeToEarth'),
}
})
app.controller(CentauriCtrl, function(interstellarService){
$scope.interstellarService = {
routeToEarth: interstellarService.get('routeToEarth'),
}
})
Interstellar Service存储在浏览器存储中:
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 - >星际服务< - 数据 - > CentauriCtrl
这是行不通的:我想在Centauri-HTML中使用和共享存储在routeToEarth
中的值,例如
<li>
<a>
{{interstellarService.routeToearth}} && 'Timetravel' || 'Wormhole' }}
</a>
</li>
我在这里缺少什么?
答案 0 :(得分:3)
您需要进行某些更改才能让它运行。
AlphaCtrl
和CentauriCtrl
AlphaCtrl
和CentauriCtrl
控制器appServices
用于服务,app
用于控制器<强> Working Demo 强>
<强>脚本强>
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>
答案 1 :(得分:0)
当我在CentauriCtrl
更改它时,将它放入我的AlphaCtrl
终于显示了通往地球的路线。
$rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
$scope.interstellarService = {
routeToEarth: interstellarService.get('routeToEarth'),
}
});
向此SO问题致敬:AngularJS Bootstraps Navbar