简体   繁体   English

如何通过Angular.js中的翻译内容订购ng-repeat?

[英]How to order ng-repeat by translated content in Angular.js?

Does there exists an easy way to order repeated elements by translated strings? 是否存在一种通过翻译后的字符串对重复元素进行排序的简便方法? So far I am using the following template: 到目前为止,我正在使用以下模板:

        <h3 ng-repeat="scheme in data.schemes  | orderBy:'scheme.collectionName':true"> 
            <span class="{{scheme.iconCssClassName || 'glyphicon glyphicon-asterisk'}}"></span> 
            <a href="#/storage/{{scheme.collectionName}}" translate="storage__{{scheme.collectionName}}"></a>
        </h3>

I'd like to order by $translate("storage__" + scheme.collectionName) 我想按$translate("storage__" + scheme.collectionName)

I've created a custom filter just in case you are using angular-translate ;) 我已经创建了一个自定义过滤器,以防万一您使用angular-translate;)

I've updated the description, so you can see how you can use it for your object in the ng-repeat. 我已经更新了说明,因此您可以在ng-repeat中看到如何将其用于对象。 You can also use this with a simple array. 您也可以将其与简单数组一起使用。

/**
 * orderByTranslated Filter
 * Sort ng-options or ng-repeat by translated values
 * @example
 *   ng-repeat="scheme in data.schemes | orderByTranslated:'storage__':'collectionName'"
 * @param  {Array|Object} array or hash
 * @param  {String} i18nKeyPrefix
 * @param  {String} objKey (needed if hash)
 * @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;
  };
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM