问题
Hi I am trying to localize the strings for pluralization in Angular. I am using ng-pluralize directive to handle pluralization and for localizations I am passing the strings to the directive at runtime based on user locale. But I am getting error "TypeError: Object # has no method 'one'" even if the $scope is loaded with translated strings.Following is my html code,
<input class="input-text" type="number" ng-model="candyCount" ng-keypress="loadStrings()"/>
<ng-pluralize count = "candyCount" when = "translateStrings" ></ng-pluralize>
Javascript code
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;
}
}
});
I have added debugger to every condition block, so when I check for $scope.translateStrings in the console, I get output as, For en-us:
$scope.translateStrings
{'0': '0 candy for sale','one': '1 candy for sale.','other': '{} candies for sale.'}
Is it because the directive is not getting updated with the latest strings, or am I going wrong somewhere.
回答1:
If you want async loading of translation string you need to recompile ng-pluralize.
Here is a demo: http://plnkr.co/edit/0pFdk4Ac1QC5SE7JSXeJ?p=preview
回答2:
When the <ng-pluralize>
element is first linked, translateStrings
is unset. Try putting it into the $scope
in a controller's constructor instead of on keypress.
Update:
Here's an example with a controller:
<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>
And the HTML:
<div ng-controller="TranslationController">
<input class="input-text" type="number" ng-model="candyCount" />
<ng-pluralize count = "candyCount" when = "translateStrings" ></ng-pluralize>
</div>
来源:https://stackoverflow.com/questions/21489657/ng-pluralize-with-translations-errortypeerror