angular-translate

常雅达
2023-12-01
//index.config.js

  angular
    .module('app')
    .config(config);

  /** @ngInject */
  function config($logProvider, $translateProvider, $translatePartialLoaderProvider) {
    // Enable log
    $logProvider.debugEnabled(true);

    $translatePartialLoaderProvider.addPart('home');
    $translateProvider.useLoader('$translatePartialLoader', {
      urlTemplate: "app/i18n/{part}/{lang}.json"
    });
    $translateProvider.preferredLanguage('zh_cn').fallbackLanguage('en');

    $translateProvider.useMissingTranslationHandlerLog();

    $translateProvider.registerAvailableLanguageKeys(['zh_cn', 'en', 'zh_hant'], {
      'en_*': 'en',
      'zh_tw': 'zh_hant',
      'zh_hk': 'zh_hant'
    });

    $translateProvider.useSanitizeValueStrategy('escaped');
    $translateProvider.useCookieStorage();
  }
  
  // i18n/home/en.json
  {
    "TITLE": "home",
    "DESCRIPTION": "This is home page",
    "ITEM1": {
      "TITLE": "item1",
      "INFO": "this is item1"
    },
    "ITEM2": {
      "TITLE": "item2",
      "INFO": "this is item2"
    }
  }
  // i18n/home/zh_cn.json
  {
    "TITLE": "首页",
    "DESCRIPTION": "这是首页",
    "ITEM1": {
      "TITLE": "项目一",
      "INFO": "这是项目一"
    },
    "ITEM2": {
      "TITLE": "项目二",
      "INFO": "这是项目二"
    }
  }
  // home.controller.js
  /** @ngInject */
  function HomeController(homeData) {
    var vm = this;
    vm.items= [
      {
        title: 'ITEM1.TITLE',
        info: 'ITEM1.INFO'
      },
      {
        title: 'ITEM2.TITLE',
        info: 'ITEM2.INFO'
      }
    ];
  }
  // home.html
  <html>
    <head>
      <title data-translate="TITLE"></title>
    </head>
    <body>
      <div data-translate="DESCRIPTION"></div>
      <div data-ng-repeat="item in ::vm.items">
        <h3 data-translate="{{item.title}}"></h3>
        <p data-translate="{{item.info}}"></p>
      </div>
    </body>
  </html>
 类似资料: