Angular js - route-ui add default parmeter
Solution 1:
There is a working plunker
As always, that is feasible with UI-Router
- built in features. Firstly, we'd introduce the super parent state called for example 'root'. It would have defined parameter lang
.state('root', {
url: '/{lang:(?:en|he|cs)}',
abstract: true,
template: '<div ui-view=""></div>',
params: {lang : { squash : true, value: 'en' }}
})
Interesting things to mention: The url
uses regexp to reduce amount of matching lang words (in our case, English, Hebrew and Czech) :
url: '/{lang:(?:en|he|cs)}',
Read more e.g. here.
Also, we do profit from a setting called params : {}
. It says, that the default value is 'en'
and what is more important - it should be squashed, skipped if there is a match with 'en' param value:
params: {lang : { squash : true, value: 'en' }}
Read more e.g. here or here
So, this is our parent, root state, which we just would apply to all states with a state definition setting parent : 'root'
:
.state('home', {
parent: 'root', // parent will do the magic
url: "/",
templateUrl: "Assets/app/templates/home.html",
controller: 'homeController'
})
.state('activity', {
parent: 'root', // parent magic
url: "/activity",
templateUrl: "Assets/app/templates/gallery.html",
controller: 'galleryController'
})
.state('page', {
parent: 'root', // magic
url: '/page/:pagename',
templateUrl: "Assets/app/templates/page.html",
controller: 'pageController'
});
And now these links would work:
ui-sref English:
<a ui-sref="home({lang: 'en'})">home({lang: 'en'})</a>
<a ui-sref="activity({lang: 'en'})">activity({lang: 'en'})</a>
<a ui-sref="page({pagename:'one', lang: 'en'})">page({pagename:'one', lang: 'en'})</a>
ui-sref Hebrew:
<a ui-sref="home({lang: 'he'})">home({lang: 'he'})</a>
<a ui-sref="activity({lang: 'he'})">activity({lang: 'he'})</a>
<a ui-sref="page({pagename:'two', lang: 'he'})">page({pagename:'two'})</a>
href English:
<a href="#/">#/</a>
<a href="#/activity">#/activity</a>
<a href="#/page/three">#/page/three</a>
href Hebrew:
<a href="#/he/">#/he/</a>
<a href="#/he/activity">#/he/activity</a>
<a href="#/he/page/three">#/he/page/three</a>
Check it in action here