48

如何应用 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!

这似乎是一个简单的任务,但它已经花了我半天的时间,我做错了什么:(

4

2 回答 2

98

您需要将过滤器应用于数组gender.name而不是genders数组:

<select ng-model="me.gender" ng-options="gender.name | translate for gender in genders"></select>

这是一个演示

于 2014-05-09T16:04:43.623 回答
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>
于 2018-04-24T09:36:32.940 回答