Search code examples
angularjsangularjs-service

AngularJS - Changing a template depending to a service


I am fairly new to Angular and I find it quite difficult to think the Angular way.

I have registered a SessionService which loads a user object at login. Each controller can depend on the SessionService so I can have some sort of access control.

app.factory('SessionService',['$resource', function($resource){

    var service = $resource('/session/:param',{},{
      'login': {
        method: 'POST'
      }
    });

    var _user = { authorized: false };

    function getUser() {
      return _user;
    }

    function authorized(){
      return _user.authorized === true;
    }

    function unauthorized(){
      return _user.authorized === false;
    }

    function login(newUser,resultHandler) {
      service.login(
        newUser,
        function(res){
          _user = (res.user || {});
          _user.authorized = res.authorized;
          if(angular.isFunction(resultHandler)) {
            resultHandler(res);
          }
        }
      );
    }
    return {
      login: login,
      authorized: authorized,
      getUser: getUser
    };
  }]);

...this is how I access the SessionService from a controller:

app.controller('SidebarCtrl', ['$scope', 'SessionService', function($scope, SessionService) {
  $scope.template = '/templates/sidebar/public.html';
  if(SessionService.authorized()){
      $scope.template = '/templates/sidebar/menu.html';  // <-- ???
  }
}]);

...and here the html file:

<div ng-controller="SidebarCtrl">
  <div ng-include src="template"></div>
</div>

Here is my question: How do I make the SidebarCtrl's template dependent on SessionService.authorize? So the sidebar shows the right content according to a user being logged in or not.

I hope this makes sense to you.


Solution

  • You need to $watch the SessionService.authorized(). So change the controller as:

    app.controller('SidebarCtrl', ['$scope', 'SessionService', function($scope, SessionService) {
        $scope.template = null;
        $scope.$watch(
            function() {
                return SessionService.authorized();
            },
            function(authorized) {
                if( authorized ) $scope.template = '/templates/sidebar/menu.html';
                else $scope.template = '/templates/sidebar/public.html';
            }
        );
    }]);