javascript - Angular js - route-ui add default parmeter -


in app use angular ui-router.

i have locals (english , hebrew) base language english.

thats why want if language english not add parameter url

for example:

  • home english --> http://example.com/
  • home hebrew --> http://example.com/he/

  • about english --> http://example.com/about

  • about hebrew --> http://example.com/he/about

is possible ?

this current code

$stateprovider         .state('/', {             url: "/",             templateurl: "assets/app/templates/home.html",             controller: 'homecontroller'         })         .state('activity', {             url: "/activity",             templateurl: "assets/app/templates/gallery.html",             controller: 'gallerycontroller'         })         .state('page', {             url: '/:pagename',             templateurl: "assets/app/templates/page.html",             controller: 'pagecontroller'         }); 

there a working plunker

as always, feasible ui-router - built in features. firstly, we'd introduce super parent state called example 'root'. 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 mention: url uses regexp reduce amount of matching lang words (in our case, english, hebrew , czech) :

url: '/{lang:(?:en|he|cs)}', 

read more e.g. here.

also, profit setting called params : {}. says, default value 'en' , more important - should squashed, skipped if there match 'en' param value:

params: {lang : { squash : true, value: 'en' }} 

read more e.g. here or here

so, our parent, root state, apply states state definition setting parent : 'root':

.state('home', {     parent: 'root', // parent 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 these links 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 in action here


Comments