Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS dynamic lang attribute of html

I need some help for change dynamically the lang attribute of HTML:

<html lang="en">

I'm making a multilanguage web application with AngularJS and rest backend. Initially I can specify a default lang attribute, but I want to change it depending on the user browser or change it if the user selects inside the web application some language option.

There is some way to do it?

like image 352
Jorge Guerola Avatar asked Oct 20 '14 08:10

Jorge Guerola


3 Answers

If you don't want to add controller to your <html> tag and if you are using angular-translate then you can use a simple directive to achieve the same.

Angular-translates gives an event $translateChangeSuccess when your translation loaded successfully or when you change the language (I assume you will use $translate.use to change the current language). We can create a custom directive using that event.

Directive Code Snippet:

function updateLanguage( $rootScope ) {
    return {
      link: function( scope, element ) {
        var listener = function( event, translationResp ) {
          var defaultLang = "en",
              currentlang = translationResp.language;

          element.attr("lang", currentlang || defaultLang );
        };

        $rootScope.$on('$translateChangeSuccess', listener);
      }
   };
}
angular.module('app').directive( 'updateLanguage', updateLanguage );

And you have add the same directive in you html attribute.

<html update-language>
like image 68
Debajit Majumder Avatar answered Oct 23 '22 12:10

Debajit Majumder


If you want to change the language dynamically. simply you can add one controller to html tag and then change the language.

Try this:

<html ng-app="langChange" ng-controller="langCtrl" lang={{lang}}>

</html>

js code:

var app = angular.module(langChange,[]);
app.controller("langCtrl",[$scope,function($scope){
            $scope.lang = "en";//here you can change the language dynamically
}])
like image 22
chandu Avatar answered Oct 23 '22 12:10

chandu


If you are making a single page web application, why would that even matter? But sure, you can change it as any attribute, using e.g. <html lang="{{ lang }}">. If you want to have localized content, then you could use angular-translate .

like image 22
Mikko Viitala Avatar answered Oct 23 '22 12:10

Mikko Viitala