Hey all I'm running into what I thought would be a common routing problem, but I'm unable to figure out a solution. Basically my page has two states, basic and advanced, and I want the URL patterns to be the same for both states but only load the template for the current state at the time (which is transitioned to from within a controller)
config(function ($stateProvider) {
$stateProvider.state('basic', {
url: '/:post',
templateUrl: function (stateParams) {
return 'post-' + stateParams.post + '-tmpl.html';
}
});
$stateProvider.state('advanced', {
url: '/:post',
templateUrl: function (stateParams) {
return 'post-' + stateParams.post + '-advanced-tmpl.html';
}
});
})
controller('myCtrl', function ($state) {
//
// In this case, I would expect only the template from
// the advanced state to load, but both templates are trying
// to load.
$state.transitionTo('advanced', {post: 2});
}
I assume that navigating to the matched pattern loads the given state which is why when it matches, both templates attempt to load. Is there some way to accomplish the same url pattern but with different templates based only on the current state?
You need to use nested states
Assuming that you cannot have two states with the same URL, why don't you go along and merge the two states into one? Ui-router already allows you to have a custom function to return the template. You just need to add another, hidden custom parameter (let's call it
advanced
) to the state declaration:And then you call it with:
For another possible solution with nested states and a common controller, see issues #217 and #1096 on ui-router's github page.
The solution presented there creates a third state whose controller does the dispatching work, whereas the two states you want to land in (
basic
andadvanced
) have empty URLs:This solution is better if your states differ in more aspects than the simple
templateUrl
(e.g. if they have completely separate controllers, etc.)Also see another question on StackOverflow about a similar issue.
This is very useful in AngularJS,
You Can Specify Dynamic Route for Multiple State with same url pattern
My Code is As follow that can be useful for you,
Module Intialization,
Further,
May be this is helpful for you... Enjoy...
Why would you want to have two different views mapped on the same url. Did you imagined the problem when the user would want to add a bookmark on one of the states? How would you then know which one was if they have exactly the same url?
I would suggest defining two different states like:
This can be done with defining /:post as abstract state and two different states for the simple and advanced view. For convenience simple view will act as default. If you like the idea I can provide you an example solution.
The other option would be to add url parameter for example:
I hope that this answer will help you. At least by seeing the things from different angle ;).