How to ng-translate inside select box option in angularjs

╄→尐↘猪︶ㄣ 提交于 2019-11-27 10:07:25

问题


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 :(


回答1:


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>

Here is a demo




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!