javascriptangularjsangularjs-serviceangularjs-routingangularjs-provider

different template url on basis of role angular


I have route configuration like :

.config(['$routeProvider',
            function ($routeProvider) {
                $routeProvider
                        .when('/home', {
                            templateUrl: 'partials/home.html',
                            controller: 'HomeCtrl'
                        })
}]);

Now I want to determine the login template to be different according to the authorization of user. I have authorized defined in session in services. I want to be able to do something like this:

 .config(['$routeProvider', 'Session'
                function ($routeProvider, Session) {
                    $routeProvider
                            .when('/home', {
                                templateUrl: Session.getState().authorized?'partials/authHome.html':'partials/home.html',
                                controller: 'HomeCtrl'
                            })
    }]);

But I cannot use Session in config this way. So what can be the possible way to this?


Solution

  • Basically the problem is you can't inject service/factory to angular config phase. You need to create a provider instead of service/factory. Because provider has access in the configuration phase of an Angular.

    Session.js

    app.provider('Session', function() {
        this.getState = function(){
            var object;
            //fill up object value.
            return object; //object will have your desired format with authorised prop
        }
    
        this.$get = function() {
            return {
                myMethod: function() {
                    return "Something";
                }
            }
        };
    });