Alan2
Alan2

Reputation: 24602

How can I switch languages dynamically with angular-translate and angular-ui-router?

My application is using angular-translate, angular-ui-router and templates. The application html pages with the exception of the index.html are packed into templates and served from Amazon CloudFront backed by S3. What I would like to do is to find a way to switch the language dynamically depending on a two letter code after the domain name and also if possible pick up on the user locale and use that for default switching.

The reason I would like to do this is for SEO purposes as I have read that Google recommends putting in a country code into the address as below.

Here's what I have so far:

The router file

    var home = {
        name: 'home',
        url: '/home/'
    };

    var homeAccess = {
        name: 'home.access',
        url: 'access',
        views: {
            'home@': {
                templateProvider: ['$templateCache', ($templateCache) => {
                    return $templateCache.get('webapi.html');
                }],
            }
        }
    };

Somehow I would like to make it so that when a search engine chooses:

www.example.com/de/home/webapi  or
www.example.com/en/home/webapi  or
www.example.com/fr/home/webapi

That angular router switches to the appropriate language file before serving the webapi.html file.

Any suggestions on how I could do this would be much appreciated. Ideally I'd like to see a simple example with a language file switcher that would help me and also others in the community to do what's needed.

Please note there's another similar question out there:

Localize URL's with ui-router and angular-translate

The answers there are good but I'm also hoping that by opening up this question I can get an even better and more updated answer, perhaps with some internationalization SEO tips thrown in. I just think this is such an important thing that the more answers to help people on this forum the better.

Upvotes: 22

Views: 6101

Answers (1)

Stepan Suvorov
Stepan Suvorov

Reputation: 26236

You need to create common abstract ui-router state and setup your language settings there:

$stateProvider.state('common', {
  abstract: true,
  url: '/{lang:(?:es|en)}'
});

and after your home state would be child from common:

$stateProvider.state('common.home', {
  url: '/home',
  templateUrl: 'views/home.html',
});

now you can setup language switch on state change event:

app.run(($rootScope) => {
  $rootScope.$on('$stateChangeSuccess', (event, toState, toParams) => {
    if(toParams.lang && $translate.use() !== toParams.lang){
      $translate.use(toParams.lang);
    }
  });
});

[19.04.2016] I declare that Google is still not able to parse your web application in clever way. Related question - SEO: How does Google index Angular applications 2016

So I as well as @shershen I recommend to use prerender.io service for better SEO.

Upvotes: 10

Related Questions