Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort ng-options by translated values

Tags:

angularjs

It's really easy to have select options translated with angular-translate:

<select name="languageId"
  ng-options="p.id as ('LANGUAGE.'+p.id)|translate for p in Const.languages | orderBy:'name'">

But that way the options are sorted by their original key not their translated one. Is there a way I can have that list ordered by their translated value without preparing that list ahead in the controller?

like image 988
hoeni Avatar asked Jul 23 '14 11:07

hoeni


2 Answers

The easiest way that worked for me (angular 1.2.24 and angular-translate 2.14.0):

<select name="nationality" ng-model="person.nationality" ng-options="c.id as c.name | translate for c in Const.countries | orderBy:'name | translate' ">

The credit for this goes to the writer of this comment: https://github.com/angular-translate/angular-translate/issues/1064#issuecomment-267357441

like image 192
stefitz Avatar answered Oct 19 '22 01:10

stefitz


You could supply a predicate function to orderBy and have that function return the translated value. It means you also have to pass in the $filter service to your controller because you'd need to invoke translate inside your JS code.

So, to offer some code as guidance:

// CONTROLLER
// * Don't forget to inject the $filter service

$scope.translated = function(p) {
    return $filter('translate')('LANGUAGE.' + p.id);
}

And then you'd modify your orderBy expression:

... | orderBy:translated

I realise the suggestion seems somewhat convoluted because one translation attempt occurs within ng-options and then another in orderBy, but it should sort the select options as you'd expect.

like image 29
miqh Avatar answered Oct 19 '22 02:10

miqh