I was working on migration of my Angularjs code from ng-router to UI-Router. In my ng-router I have optional parameters however I realized that same easy way to support optional parameter is not supported in ui-router. Following is my routes from my existing ng-router module.
//Define routes for view using ng-router
$routeProvider.
when('/my-app/home/:userid?', {
templateUrl: '/templates/partials/home/HomeView.html',
controller: 'HomeViewController'
})
.when('/my-app/:productKey/:userid?', {
templateUrl: '/templates/partials/productpage/ProductPageView.html',
controller: 'ProductViewController'
})
.otherwise({redirectTo: '/my-app/home'});
Note: If you see ":userid" parameter is very smoothly implemented here as optional.
I tried following in ui-router however same is not working. I have gone through many post and it was suggested to duplicate the routes. I really don't want to duplicate as it will make code dirty.
//Set the default route
$urlRouterProvider.otherwise('/my-app/home');
//Define routes for view (Please make sure the most matched pattern is define at top)
$stateProvider
.state('viewallcards', {
url: '/my-app/home/:userid',
templateUrl: '/templates/partials/home/HomeView.html',
controller: 'HomeViewController'
})
.state('productpage', {
url: '/my-app/:productKey/:userid',
templateUrl: '/templates/partials/productpage/ProductPageView.html',
controller: 'ProductViewController'
});
Here /my-app/home/ works however /my-app/home doesn't work. How to make it without trailing slash as well?
Also following post on same issue has surprised to me to know that this is not supported in ui-router. Is it still valid? Please help.
There is a working example
We can use
params : {}
object to define theuserid
exactly as we need (i.e. ready to be omitted).Check more details about
params
here:Angular ui router passing data between states without URL
Check it in action here