Popokoko
Popokoko

Reputation: 6543

Angularjs: Can i have one route with multiple views?

Consider a certain route let's say myapp\profile which has two modes (buyer/seller) What i would like to achieve is:

What i already considered:

  1. Thought about using ui-router's sub states, but I dont want to change the url.
  2. Thought about creating this 'profile' route and while navigating to it, figure the mode (buyer/seller), and then $state.go to a new state (but again, i would like to keep same route name at the end so it's not ok)
  3. Ideally thought i could navigate to my shared controller and then render the correct view and controller, but this idea kinda messed up me.

Could you share what is a clean way of doing this?

Upvotes: 1

Views: 134

Answers (1)

jusopi
jusopi

Reputation: 6813

most use cases

Normally, in order to dynamically select a template for a state, you can use a function:

state = {
    .....
    templateUrl: function($stateParams){
         if ($stateParams.isThis === true)
             return 'this.html'
         else
             return 'that.html'
    }
}

but...

Unfortunately you can't pass other injectables to the templateUrl function. UI.Router only passes $stateParams. You don't want to alter the URL in anyway so you can't use this.

when you need to inject more than $stateParams

But you can leverage templateProvider instead. With this feature, you can pass a service to your templateProvider function to determine if your user is a buyer or seller. You'll also want to use UI.Router's $templateFactory service to easily pull and cache your template.

state = {
    ....
    templateProvider: function($templateFactory, profileService){
        var url = profileService.isBuyer ? 'buyer.html' : 'seller.html';
        return $templateFactory.fromUrl(url);
    }
}

Here it is working in your plunkr - http://plnkr.co/edit/0gLBJlQrNPUNtkqWNrZm?p=preview

Docs:

Upvotes: 1

Related Questions