It\'s really easy to have select options translated with angular-translate:
I had the same problem and I recommend using an own filter, because you don't want to mess up your controller! This is my current solution:
/**
* orderByTranslated Filter
* Sort ng-options or ng-repeat by translated values
* @example
* ng-options="country as ('countries.'+country | translate) for country in countries | orderByTranslated:'countries.'"
* @param {Array} array
* @param {String} i18nKeyPrefix
* @param {String} objKey
* @return {Array}
*/
app.filter('orderByTranslated', ['$translate', '$filter', function($translate, $filter) {
return function(array, i18nKeyPrefix, objKey) {
var result = [];
var translated = [];
angular.forEach(array, function(value) {
var i18nKeySuffix = objKey ? value[objKey] : value;
translated.push({
key: value,
label: $translate.instant(i18nKeyPrefix + i18nKeySuffix)
});
});
angular.forEach($filter('orderBy')(translated, 'label'), function(sortedObject) {
result.push(sortedObject.key);
});
return result;
};
}]);
Notice you need to pass your i18n prefix 'LANGUAGE.' and I saw your using an object instead of a simple string array so you can use it like this:
<select name="languageId"
ng-options="p.id as ('LANGUAGE.'+p.id)|translate for p in Const.languages | orderByTranslated:'LANGUAGE.':'id'">
I know it's an old question, but stumbled upon this today and here's how in this case you could solve it (only works for Array
though):
<select name="languageId"
ng-options="p.id as name=('LANGUAGE.'+p.id)|translate for p in Const.languages | orderBy:'name'">
The trick is to assign the translation and use this assignment to sort on.
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.
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