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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With