Adding language URLs to your Angular application using ngRoute

While building an Angular application, a customer requested the ability to have users share the URL to their Facebook wall. Easy enough, except that Angular has no way of adding the language to the URL and the user would thus always be redirected to the default language.

*This article assumes you’re using the Angular Translate module.

1. Adding the language to the URL

The first thing you’ll want to do is add the language to the URL. By using the power of .htaccess mod_rewrite we can add our language as subfolders, going from to[lang]. We’ll also force a redirect to our default language if it’s missing.

# Add language to URL - redirect to default if missing    

RewriteBase /

# empty url -> redirect to fr/
RewriteCond %{QUERY_STRING} !lang=(nl|fr)
RewriteRule ^$ fr/ [R=301,L]

# url is ONLY '/nl' or '/fr' -> redirect to /nl/ or /fr/ (adding slash)
RewriteRule ^(nl|fr)$ $1/ [R=301,L]

# now all urls have nl/ fr/ -> parse them
RewriteRule ^(nl|fr)/(.*)$ $2?lang=$1&%{query_STRING} [L]


2. Getting the language in AngularJS

Now all that remains is parsing the URL in AngularJS, so that we can update the content. Angular Translate is configured in the config block of your application, so we’ll start there.

Since the $window service is not available in the config block yet, we’ll have to get it via the $windowProvider. Then we can ask for the pathname and take of the slashes to get to our language, after which we pass it to our $translateProvider.

config.$inject = ['$translateProvider', '$windowProvider'];

function config($translateProvider, $windowProvider) {

var $window,

$window = $windowProvider.$get();
language = $window.location.pathname.replace(/\//g, '');


prefix: 'translations/',
suffix: '.json'
.preferredLanguage( language )

3. Getting the language in your templates

If you want to have access to your language, for example to set the lang-attribute or to be able to adjust styling, the simplest way is to add it to your $rootScope. That way it will be available throughout the entire application.

run.$inject = [‘$window’];
function run($window) {
$rootScope.language = $window.location.pathname.replace(/\//g, ‘’);

And in your HTML:

<!doctype html>
<html ng-app=”yourApp” lang=”be-{{language|uppercase}}”>

<body class=”{{page}} lang-{{language}}”>
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.