0

Okay this question is abit long but i feel like ive tried everything so i hope you will help me out if you can :)

So basicly my system has two user types: Admin & Client these types are bound to a template tpl/app.html & tpl/client/client.html

Now instead of defining states twice (1 for Admin & 1 for client) i wish to make a logic that serves the correct template no matter what

For this purpose i read the Documentation for $stateProvider and found that i am able to set the templateUrl to a function:

  templateProvider: function ($sessionStorage) {
                        return template;
                    },

Using this syntax i was able to do something like this:

templateProvider: function ($sessionStorage) {
    var templateLocation = $sessionStorage.user.type == 'Admin' ? 'tpl/app.html' : 'tpl/client/client.html';
   return '<div ng-include="'+templateLocation+'"> </div>' 
},

Now there are two things wrong with this

  1. First of all for some reason this doesnt work. it does set the url to the correct template however it is never injected into the html instead i get this:

    <div>   <!-- ngInclude: tpl/client/client.html -->    </div>
    
  2. The idea is fine however making the above code for each abstract state seems tedious and very redundant.

Because of #2 i decided to create a decorator. however the decorator has a problem aswell. It simply cannot use the service $sessionStorage where my user data is in meaning that i am unable to know which user is attempting to reach the content.

So now i feel like im out of options.

I hope that some of you might be able to help me!

Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364

1 Answers1

1

It isn't necessary to write WET anonymous function for each abstract state.

function userTemplateProvider($sessionStorage, $templateRequest) {
    var templateLocation = $sessionStorage.user.type == 'Admin' ? 'tpl/app.html' : 'tpl/client/client.html';
   return $templateRequest(templateLocation); 
},

...
templateProvider: userTemplateProvider

Angular decorator won't help with UI Router states because it would affect $state instance and not $stateProvider provider. $stateProvider.state method can be patched directly to modify state object, though it is hardly can be considered a justified solution in this case.

Community
  • 1
  • 1
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • The above code works but i can figure out if your saying its recommended or not? – Marc Rasmussen Apr 04 '16 at 14:52
  • @MarcRasmussen The supplied code is the recommended DRY solution. It can be made even DRYer by patching $stateProvider.state, but I wouldn't recommend that. – Estus Flask Apr 04 '16 at 15:00