0
votes

I am using $stateProvider for routing and angular-translate for translations. What i would like to achieve is having the selected language bind to the URL and make Language optional with [default=en]. like so:

www.mydomain.com/home
www.mydomain.com/en/home
www.mydomain.com/ar/home

and make it respond accordingly.

I used this code

$urlRouterProvider.otherwise("/home");
$stateProvider
        // Homepage:
        .state("app", {
            url: "/:lang?",
            abstract: true,
            template: '<ui-view/>'
        })


        .state("app.home", {
            url: "/home",
            templateUrl: "common/views/main.html"
        });

i want to go to home page with language parameter like

www.mydomain.com/en/home

or without it like

www.mydomain.com/home

Thanks

2

2 Answers

0
votes

You can specify the url

$urlRouterProvider.otherwise("/home");
$stateProvider
    // Homepage:
    .state("app", {
        url: "/:lang",
        abstract: true,
        template: '<ui-view/>'
    })
    .state("app.home", {
        url: "/home",
        templateUrl: "common/views/main.html"
    });

in your controller

$state.go("app",{lang:"en"});

Attention: the name of the url variable should be the same as put in the $ state

0
votes

You can specify the squash: true option for optional parameters in the params property of the configuration. When the parameter value is the default one, this will remove any slashes around it too.

$urlRouterProvider.otherwise("/home");
$stateProvider
    // Homepage:
    .state("app", {
        url: "/:lang",
        params: {squash: true, value: 'en'}
        abstract: true,
        template: '<ui-view/>'
    })


    .state("app.home", {
        url: "/home",
        templateUrl: "common/views/main.html"
    });

Note that this will not include the default value in generated routes, so even though /en/home works, a link with ui-sref='app.home({lang:"en"})' will yield /home, not /en/home. You can set up value: null and use the "en" as default in your language selection logic later when $stateParams.lang is null.