How to ng-translate inside select box option in angularjs
Asked Answered
T

2

48

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

Tasker answered 9/5, 2014 at 15:15 Comment(0)
P
100

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

Pontiff answered 9/5, 2014 at 16:4 Comment(0)
V
0

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>
Ventilation answered 24/4, 2018 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.