Sort ng-options by translated values

前端 未结 4 2107
梦毁少年i
梦毁少年i 2021-01-11 10:47

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


                        
    
提交评论

  • 2021-01-11 11:15

    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.

    0 讨论(0)
  • 2021-01-11 11:17

    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.

    0 讨论(0)
  • 2021-01-11 11:20

    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

    0 讨论(0)
  • 提交回复
    热议问题