html 的 AngularJS 动态 lang 属性 [英] AngularJS dynamic lang attribute of html

查看:23
本文介绍了html 的 AngularJS 动态 lang 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助来动态更改 HTML 的 lang 属性:

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

<html lang="en">

我正在使用 AngularJS 和 rest 后端制作多语言 Web 应用程序.最初我可以指定默认的 lang 属性,但我想根据用户浏览器更改它,或者如果用户在 Web 应用程序中选择了某种语言选项,则更改它.

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?

推荐答案

如果您不想将控制器添加到您的 <html> 标签,并且您正在使用 angular-translate 然后您可以使用简单指令来实现相同的目的.

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 会在您的翻译成功加载或更改语言时提供一个事件 $translateChangeSuccess(我假设您将使用 $translate.use 来更改当前语).我们可以使用该事件创建自定义指令.

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.

指令代码片段:

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 );

并且您在 html 属性中添加了相同的指令.

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

<html update-language>

这篇关于html 的 AngularJS 动态 lang 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆