AngularJS - angular-translate 国际化插件

太叔涵亮
2023-12-01

配置

1.安装依赖

  • npm install angular-translate -s
  • npm install angular-translate-loader-static-files -s

2.在html中加载JS

  • ‘node_modules/angular-translate/dist/angular-translate.min.js’,
  • ‘node_modules/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js’

3.注入依赖

  • ‘pascalprecht.translate’
    angular
        .module('core')
        .config(translateProvider);

    translateProvider.$inject = ['$translateProvider'];
    function translateProvider($translateProvider) {
        $translateProvider.useStaticFilesLoader({
            prefix: '/api/base/web/language/',
            suffix: ''
        });
        var preferLanguage = 'en';
        $translateProvider.preferredLanguage(preferLanguage);
        $translateProvider.useStorage('translateStorage');
    }

4.定义translateStorage

    angular
        .module('core')
        .factory('translateStorage', translateStorage);
    translateStorage.$inject = ['$window'];
    var langKey;

    function translateStorage($window) {
        return {
            put: function (name, value) {
                // store `value` under `name` somehow
                langKey = value;
                $window.localStorage.setItem(name, value);
            },
            get: function (name) {
                // request value of `name` somehow
                if (!langKey) {
                    langKey = $window.localStorage.getItem(name);
                }
                return langKey;
            }
        };
    }

使用

两种使用方式:

  • 是当成过滤器使用(指使用的格式和使用过滤器一样,{{ 'dashboard_personality_chart_title' | translate }});
  • 当成指令使用(使用格式和使用指令一样,<h2 translate="dashboard_personality_chart_title"></h2>)
 类似资料: