通过翻译值排序NG-选项 [英] Sort ng-options by translated values
问题描述
这真的很容易有翻译与选择选项角翻译:
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'">
但这样的选项是原来的按键排序不是他们的翻译之一。
有没有一种方法可以让我有一个列表,而$ P $通过的翻译价值下令提前pparing在控制器列表?
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?
推荐答案
我有同样的问题,我建议使用自己的过滤器,因为你不想弄乱你的控制器!这是我目前的解决方案:
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;
};
}]);
的通知您需要通过你的i18n preFIXLANGUAGE。我看到使用的对象,而不是一个简单的字符串数组,所以你可以使用它是这样的:
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'">
这篇关于通过翻译值排序NG-选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!