Angularjs在两个模块之间共享数据

时间:2015-07-19 04:26:03

标签: javascript angularjs

我试图在两个不同模块中的两个控制器之间共享服务。我发过帖子让我相信自己走在正确的轨道上herehere。但我显然遗漏了一些东西。这是我的代码和codepen

索引设置正常,但是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 个答案:

答案 0 :(得分:0)

试试这个:

<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>

您必须在shell.isSidebarActive()ng-show中调用ng-hide函数 http://codepen.io/anon/pen/EjpeoR