0
我試圖在兩個不同模塊中的兩個控制器之間共享一個服務。我見過的帖子讓我相信我在正確的軌道上,here和here。但我顯然錯過了一些東西。這是我的代碼和codepen。Angularjs在兩個模塊之間共享數據
該索引正在設置好,但是isSidebarActive不會像所期望的那樣被自動觸發。任何幫助將非常感激。謝謝!
index.js
angular
.module('app', ['app.layout', 'app.sidebar']);
angular
.module('app.layout', [])
.service('layoutService', function() {
var vm = this;
var sidebarStatus = null;
vm.isSidebarActive = function() {
console.log('isSidebarActive: ' + (sidebarStatus ? 'true' : 'false'));
return sidebarStatus;
};
vm.setSidebarStatus = function(status) {
console.log('setSidebarStatus: ' + (status ? 'true' : 'false'));
sidebarStatus = status;
};
})
.controller('ShellController', ['layoutService', function(layoutService) {
var vm = this;
vm.isSidebarActive = function() {
return layoutService.isSidebarActive();
}
}]);
angular
.module('app.sidebar', ['app.layout'])
.controller('SidebarController', ['layoutService', function(layoutService) {
var vm = this;
var index = null;
vm.setIndex = function(i) {
index = i;
layoutService.setSidebarStatus(i > 0);
console.log('setIndex: ' + index);
};
vm.isIndex = function (i) {
return index === i;
};
}]);
的index.html
<body ng-app="app">
<div ng-controller="ShellController as shell">
<div class="alert alert-info" ng-show="shell.isSidebarActive">active</div>
<div class="alert alert-warning" ng-hide="shell.isSidebarActive">non-active</div>
<div/>
<div ng-controller="SidebarController as sidebar">
<a class="btn" ng-click="sidebar.setIndex(1)">active</a>
<a class="btn" ng-click="sidebar.setIndex(0)">non-active</a>
<div/>
</body>
從第二個模塊中刪除數組。 – Ved
謝謝你,我花了很長時間才弄清楚。 – user3009902