如何应用ng-translate翻译选择框内的选项。
例如:
模板:
<select class="form-control" ng-model="me.gender" ng-options="gender.name for gender in genders">
</select>
控制器:
$scope.genders = [{code: "M", name:"TXT_MALE"}, {code: "F", name:"TXT_FEMALE"}]
enUS.json:
{
"TXT_MALE": "Male",
"TXT_FEMALE": "Female",
}
我尝试添加ng-options="gender.name for gender in genders | translate"
之类的过滤器
但显然它是在$scope.genders
数组中添加过滤器而不是单个元素
我尝试编写自己的过滤器(我是新手)
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;
}
}])
但我收到了以下错误
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
这似乎是一项简单的任务,但它已经占用了我一半的时间,我做错了什么:(
答案 0 :(得分:92)
您需要将过滤器应用于gender.name
而不是genders
数组:
<select ng-model="me.gender" ng-options="gender.name | translate for gender in genders"></select>
答案 1 :(得分:0)
使用md-select的另一种更简单的方法,这里也使用了占位符
JSON:
"placeholder":{
"gender": "Gender"
},
"gender":
{
"TXT_MALE": "Male",
"TXT_FEMALE": "Female"
}
HTML代码:
<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>