tomriddle_1234 tomriddle_1234 - 3 months ago 26
AngularJS Question

How to deal with specific route state url parameters on AngularJS or Ionic? How to do route state override on specific parameters?

My question is simple, but I couldn't find solution anywhere else.

For example I have a normal route state with parameter,

.state('page', {
url: '/page/:pageid',
templateUrl: 'templates/pages.html',
controller: 'pagesCtrl'
})


However for example, if I have 1000 pages, but for the Number 1 and Number 999 pages I have to use another template. How could I simply do this? Something like

.state('page', {
url: '/page/:pageid',
templateUrl: 'templates/pages.html',
controller: 'pagesCtrl'
})
.state('page', {
url: '/page/1',
templateUrl: 'templates/page1.html',
controller: 'pagesCtrl'
})
.state('page', {
url: '/page/999',
templateUrl: 'templates/page999.html',
controller: 'pagesCtrl'
})


Will this work?I tested, the later 2 options are not overriding the original state with parameter.

If I wish to use the same controller, how to load the 1 and the 999 as the pageid parameter in the controller?

Answer

Definitely you shouldn't have two more state for separate template. You should use single generic state which will take templateUrl with the help of passed state parameter.

Code

.state('page', {
    url: '/page/:id',
    templateUrl: function($stateParams){
      var template = $stateParams.id.indexOf([1, 1000]) > -1?'pages.html'
                                                            :'page'+$stateParams.id+'.html';
      return 'templates/'+template ,
    }
    controller: 'pagesCtrl'
})