0

I'm trying to share a service between two controllers in two different modules. I've seen posts that lead me to believe I'm on the right track, here and here. But I'm obviously missing something. Here is my code and a codepen.

The index is being set okay, but isSidebarActive isn't being fired automatically like one would expect. Any help would be much appreciated. Thank you!

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>
Community
  • 1
  • 1
user3009902
  • 97
  • 1
  • 5

1 Answers1

0

Try this:

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

You must call the function shell.isSidebarActive() in ng-show and ng-hide http://codepen.io/anon/pen/EjpeoR

monkey
  • 1,279
  • 14
  • 15