Search code examples
javascriptangularjssidebarmobile-angular-ui

Implement a dynamic sidebar, which refresh on particular actions


I am trying to build a dynamic sidebar, which displays elements depending on the current user state. So only some elements should be displayed, if the user is logged in and some others, if the the user isn´t.

The current state is saved in the userService. There also is a method, which return the current state:

angular.module('app').service('userService', ['$http', 'base64', function ($http, base64) {

var user = {
    auth: "",
    ask: "",
    mandant: ""
};

...
this.isloggedIn = function(){
        if(user.auth != "" && user.ask != "" && user.mandant != "")
        {
            return true;
        }
        else
        {
            return false;
        }
...

}]);

Now I created a small controller:

angular.module('app')
.controller('sidebarController',['$scope', 'userService',  function($scope, userService) {

$scope.loggedIn = userService.isloggedIn();

}]);

My sidebar looks like this:

<div class="scrollable" ng-controller="sidebarController">
  <h1 class="scrollable-header app-name">Navigation</h1>  
  <div class="scrollable-content">
    <div class="list-group" ui-turn-off='uiSidebarLeft'>


      <a class="list-group-item green" href="#/login" ng-hide="loggedIn">Login</a>
      <a class="list-group-item red" href="#/logout" ng-show="loggedIn">Logout</a>


    </div>
  </div>
</div>

The Goal : The sidebar should only display the login element, if the user is logged out and only the logout element, if the user is logged in.

After runing this, the sidebar only displays the login element, but after login the sidebar do not change. How can i force the sidebar to refresh?


Solution

  • Your problem is that

    $scope.loggedIn = userService.isloggedIn();
    

    is only being called once: on initiating the controller. What you want is to create a function which is being called whenever the state changes (e.g. after login):

    angular.module('app').controller('sidebarController', ['$scope', 'userService',  function($scope, userService) {
    
        function refreshState() {
            $scope.loggedIn = userService.isloggedIn();
        }
    
        refreshState();
    
        $scope.login = function() {
            // do login
            // call refreshState() afterwards
            refreshState();
        }
    }]);