问题描述
我正在尝试在两个不同模块中的两个控制器之间共享服务。 我看到过一些帖子,使我相信自己在和正确的轨道上。 但是我显然缺少了一些东西。 这是我的代码和一个 。
索引设置正确,但是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>
1楼
尝试这个:
<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>
您必须在ng-show
和ng-hide
调用函数shell.isSidebarActive()