I am making a multilingual web ap...">

Angular lang attribute for html

I need help to dynamically change the HTML lang attribute:

 <html lang="en"> 

I am making a multilingual web application using AngularJS and the rest. Initially, I can specify the default lang attribute, but I want to change it depending on the user's browser, or change it if the user selects a language inside the web application.

Is there any way to do this?

+6
source share
4 answers

If you do not want to add a controller to your <html> , and if you use angular-translate , you can use a simple directive to achieve the same.

Angular translators give the $translateChangeSuccess event when your translation is loaded successfully or when you change the language (I assume that you will use $translate.use to change the current language). We can create a custom directive using this 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 add the same directive to your html attribute.

 <html update-language> 
+4
source

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

Try the following:

 <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 }]) 
+2
source

If you are creating a one-page web application, why does it matter? But, of course, you can change it like any attribute using, for example, <html lang="{{ lang }}"> . If you want to have localized content, you can use angular-translate .

+1
source

To improve Debagit's answer, I changed its directive to make sure that it also works when creating new elements and when the preferred language is set:

 function updateLanguage( $rootScope, $translate ) { return { link: function( scope, element ) { var defaultLang = "en"; element.attr("lang", $translate.use() || defaultLang ); var listener = function( event, translationResp ) { var currentlang = translationResp.language; element.attr("lang", currentlang || $translate.use() || defaultLang ); }; $rootScope.$on('$translateChangeSuccess', listener); } }; } angular.module('app').directive( 'updateLanguage', updateLanguage ); 

Just add the attribute 'update-language' to any element, for example. <html update-language>

0
source

Source: https://habr.com/ru/post/976965/


All Articles