How do I apply ng-translate to translate options inside a select box.
For example:
Template:
<select class="form-control" ng-model="me.gender" ng-options="gender.name for gender in genders">
</select>
Controller:
$scope.genders = [{code: "M", name:"TXT_MALE"}, {code: "F", name:"TXT_FEMALE"}]
enUS.json:
{
"TXT_MALE": "Male",
"TXT_FEMALE": "Female",
}
I tried adding filter like ng-options="gender.name for gender in genders | translate"
but obviously it was adding filter to $scope.genders
array instead of single element
I tried writing own filter (I am new to this)
filter('translateArrayObj', ['$translate', '_', function($translate, _) {
return function(arr) {
var arr2 = [];
angular.forEach(arr, function (value, key) {
$translate(value.name).then(function(translation) {
var obj2 = angular.copy(value);
obj2.name = translation;
obj2.code = value.code;
arr2.push(obj2);
});
});
return arr2;
}
}])
But I got following error
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
It seems like a simple task but it has already taken half of my day, what am I doing wrong :(
You need to apply the filter to gender.name
and not to the genders
array:
<select ng-model="me.gender" ng-options="gender.name | translate for gender in genders"></select>
Another simpler method by using md-select, here placeholder is also used
JSON:
"placeholder":{
"gender": "Gender"
},
"gender":
{
"TXT_MALE": "Male",
"TXT_FEMALE": "Female"
}
HTML Code:
<md-select ng-model="gender" placeholder="{{'placeholder.gender' | translate}}" ng-required="true" style="width: 160px;" >
<md-option ng-value="gender .code" ng-repeat="gender in genders" translate="gender.{{gender.name}}"></md-option>
</md-select>
来源:https://stackoverflow.com/questions/23568180/how-to-ng-translate-inside-select-box-option-in-angularjs