Saturday 31 December 2016

javascript - How to define optional parameter using UI-Router without trailing slash as well?



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.


Answer



There is a working example




We can use params : {} object to define the userid 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



  $stateProvider
.state('viewallcards', {
url: '/my-app/home/:userid',

params: {
userid: {squash: true, value: null }, // this will make both links below working:
// #/my-app/home
// #/my-app/home/
},
...
})
.state('productpage', {
url: '/my-app/:productKey/:userid',
...

})


Check it in action here


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...