How to ng-translate inside select box option in angularjs

Rahul Prasad picture Rahul Prasad · May 9, 2014 · Viewed 27.1k times · Source

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

Answer

Sebastian picture Sebastian · May 9, 2014

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