i18next - 当语言改变时,字符串不会更新

时间:2017-06-09 20:54:56

标签: angularjs localization i18next

我正在将i18next库与我的Angular 1.5.3项目集成。

https://github.com/i18next/ng-i18next

当我使用changeLanguage功能时,我页面上的字符串不会更新为正确的语言。

这是我的HTML:

<!DOCTYPE html>
<html lang="en">

  <head>
    <script data-require="angular.js@1.5.3" data-semver="1.5.3" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular-sanitize.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/i18next/8.4.1/i18next.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ng-i18next/1.0.4/ng-i18next.min.js"></script>
    <script src="app.js"></script>
    <meta charset="utf-8" />
  </head>

  <body ng-app="myApp">
    <div ng-controller="MyCtrl">
      Hello, {{name}}!
      <div ng-i18next="HELLO"></div>
      <button ng-click="change()">change lng</button>
    </div>
  </body>

</html>

这是我的app.js

if (window.i18next) {
  window.i18next.init({
    debug: true,
    lng: 'en', // If not given, i18n will detect the browser language.
    fallbackLng: 'en', // Default is dev
    resources: {},
    useCookie: false,
    useLocalStorage: false,
    joinArrays: '<br />'
  });
}

var myApp = angular.module('myApp', ['ngSanitize', 'jm.i18next']);
myApp.controller('MyCtrl', MyCtrl);

function MyCtrl($scope, $i18next) {
  $scope.name = 'Superhero';

  $scope.change = function() {
    $i18next.i18n.changeLanguage('fr', function(err, t) {
      console.log(t('HELLO')); //prints out bonjour
    });
    console.log($i18next.t('HELLO')); //prints out hiya
  };

  $i18next.i18n.addResourceBundle('en', 'translation', {
    'HELLO': 'hiya'
  });

  $i18next.i18n.addResourceBundle('fr', 'translation', {
    'HELLO': 'bonjour'
  });

  console.log($i18next.t('HELLO')); //prints out hiya
}

Plunkr:https://plnkr.co/edit/7oI13bNJVqVgTEFOT6bk

我不知道如何刷新&#39;我的页面以获得正确的翻译。

1 个答案:

答案 0 :(得分:2)

<强> Working plunker

使用此选项更改语言$i18next.changeLanguage('fr');

替换:

$i18next.i18n.changeLanguage('fr', function(err, t) {
  console.log(t('HELLO')); //prints out bonjour
});

用这个:

$i18next.changeLanguage('fr');

控制器中的翻译
要在语言更改发生后在控制器中执行翻译,请听取i18nextLanguageChange事件,然后执行如下翻译。

  // Listen for the language change event and perform $scope bindings
  $scope.$on('i18nextLanguageChange', function () {
    // Inside a timeout to allow the language change to complete
    $timeout(function () {
      console.log($i18next.t('HELLO'));}
      );
  });
相关问题