您好我正在尝试在Angular中本地化字符串以进行复数化。我正在使用ng-pluralize指令来处理复数化和本地化我在运行时根据用户区域设置将字符串传递给指令。但是我收到错误“TypeError:Object#没有方法'one'”即使$ scope加载了翻译的字符串。以下是我的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时,我输出为, 对于我们:
$scope.translateStrings
{'0': '0 candy for sale','one': '1 candy for sale.','other': '{} candies for sale.'}
是因为指令没有使用最新的字符串更新,或者我在某处出错。
答案 0 :(得分:2)
如果您想要翻译字符串的异步加载,则需要重新编译ng-pluralize。
答案 1 :(得分: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>