1

嗨,我正在尝试在 Angular 中本地化字符串以进行复数。我正在使用 ng-pluralize 指令来处理复数化和本地化,我在运行时根据用户区域设置将字符串传递给指令。但是即使 $scope 加载了翻译后的字符串,我也会收到错误“TypeError: Object # has no method 'one'”。以下是我的 html 代码,

 <input class="input-text" type="number" ng-model="candyCount" ng-keypress="loadStrings()"/>
 <ng-pluralize count = "candyCount" when = "translateStrings" ></ng-pluralize>

Javascript代码

   myApp.controller(‘MyCtrl’,function($scope){

   $scope.loadStrings = function(){ 

        $scope.translateStrings = null;

          if (userLocale == "en-us"){
                 $scope.translateStrings = 
                   {'0': '0 candy for sale','one': '1 candy for sale.','other': '{} candies for sale.'} ;
              debugger;
              }
             else if (userLocale == "de-de"){
                   $scope.translateStrings = {'0': '0 Süßigkeiten ausgewählt',
                   'one': '1 Süßigkeiten zum Verkauf',
                'other': '{} Süßigkeiten zum Verkauf.'
               };
             debugger;
           }

        }

    });

我已将调试器添加到每个条件块中,因此当我在控制台中检查 $scope.translateStrings 时,我得到的输出为,对于 en-us:

   $scope.translateStrings
   {'0': '0 candy for sale','one': '1 candy for sale.','other': '{} candies for sale.'}

是因为指令没有用最新的字符串更新,还是我在某个地方出错了。

4

2 回答 2

2

如果你想异步加载翻译字符串,你需要重新编译 ng-pluralize。

这是一个演示:http ://plnkr.co/edit/0pFdk4Ac1QC5SE7JSXeJ?p=preview

于 2014-02-10T13:30:03.953 回答
0

<ng-pluralize>元素第一次链接时,translateStrings未设置。尝试将其放入$scope控制器的构造函数中而不是按键上。

更新

这是一个带有控制器的示例:

<script>
  // The controller will be injected with a new scope for your element.
  var TranslationController = function($scope) {
    // This is your code from your example. This assumes there's a global
    // 'userLocale' variable.
    if (userLocale == "en-us"){
      $scope.translateStrings = 
      {'0': '0 candy for sale','one': '1 candy for sale.','other': '{} candies for sale.'} ;
      debugger;
    }
    else if (userLocale == "de-de"){
      $scope.translateStrings = {'0': '0 Süßigkeiten ausgewählt',
      'one': '1 Süßigkeiten zum Verkauf',
      'other': '{} Süßigkeiten zum Verkauf.'
      };
      debugger;
    }
  };
</script>

和 HTML:

<div ng-controller="TranslationController">
  <input class="input-text" type="number" ng-model="candyCount" />
  <ng-pluralize count = "candyCount" when = "translateStrings" ></ng-pluralize>
</div>
于 2014-01-31T21:03:45.477 回答