AngularJS - 支持基于翻译文件(语言环境)的其他语言

时间:2017-05-16 06:28:32

标签: javascript angularjs json locale translation

语言文件的目录结构

app/common/JsonLang/
language-FR.json
language-EN.json

app.route.js

myApp.config(['$routeProvider', '$translateProvider',
function ($routeProvider, $translateProvider) {


        //Language Selection for Multi Language Options
        $translateProvider.useStaticFilesLoader({
            prefix: 'common/JsonLang/language-',
            suffix: '.json'
        });

        $translateProvider.preferredLanguage('EN');
        $.getScript("assets/js/lib/Angular/angular-i18n/angular-locale_EN.js");
        $translateProvider.useSanitizeValueStrategy('escape');
        $translateProvider.useLocalStorage(); // saves selected language to localStorage
        //End Language Selection - Configure Portion for Multi Language Options

}]);

控制器

myApp.controller('LangCtrl', function ($translate, languageConstant, $rootScope, $state, $cookieStore, $timeout, $interval, $scope, $filter, $uibModal, $location, $window) {

    //define array for number of language available
    $scope.languages = {
        "EN": $translate.instant('BUTTON_LANG_EN'),
        "FR": $translate.instant('BUTTON_LANG_FR')
    };

    //"BUTTON_LANG_EN": "English",
    //"BUTTON_LANG_FR": "French"

    //Model Name that define currently selected language
    $scope.selectedlanguage = "";
    $scope.selectedlanguage = $cookieStore.get('lang');

    //check condition if no language is selected
    if ($scope.selectedlanguage == null)
        //if no language is selected than default language will be English
        $scope.selectedlanguage = 'EN';

    //when language is change this function is called
    $scope.changeLanguage = function (langKey) {

        if (langKey == null)
            langKey = 'EN';
        else if (angular.equals(langKey, 'FR')) {
            $scope.selectedLang = "FR";
            angular.element.getScript(languageConstant.languagePath + "angular-locale_FR.js"); //load french script
        } else {
            $scope.selectedLang = "EN"
            angular.element.getScript(languageConstant.languagePath + "angular-locale_EN.js"); //load english script
        }
        $cookieStore.put('lang', langKey); //store the language in cookie
        $translate.use(langKey); //translate  language
    };
});

language.html

<div ng-controller="LangCtrl">      
    <select ng-model="selectedlanguage" ng-options="k as v | translate for (k,v) in languages" 
            ng-change="changeLanguage(this.selectedlanguage)" ng-selected="true" selected="selected">
    </select>
</div>

使用案例

如果系统必须支持其他语言'DE',则必须为其编写代码并添加JSON转换文件。 如何才能在app/common/JsonLang/下添加JSON语言翻译文件,并使用上面的代码动态加载其他语言作为选项?

0 个答案:

没有答案