如何在 ng-repeat Angularjs 中对对象的内部字段使用 orderBy

How to use orderBy for inner fields of object in ng-repeat Angularjs

我的对象看起来像这样:

$scope.options = [{
      name: 'John',
      phone: '555-1212',
      age: 10,
      descriptions: [{
        "languageId": "EN",
        "description": "b Some description",

      }, {
        "languageId": "DE",
        "description": "b Some description in dutch",

      }]

    },
    {
      name: 'Jimmy',
      phone: '555-1212',
      age: 10,
      descriptions: [{
        "languageId": "EN",
        "description": " d Some description",

      }, {
        "languageId": "DE",
        "description": "d Some description in dutch",

      }]

    },
    {
      name: 'Cris',
      phone: '555-1212',
      age: 10,
      descriptions: [{
        "languageId": "EN",
        "description": "a Some description",

      }, {
        "languageId": "DE",
        "description": "a Some description in dutch",

      }]

    }]

我想根据 "descriptions"、

中的字段 "description" 对其进行排序

我可以按姓名、phone 和年龄等其他字段对其进行排序,但不能按 说明。

 <tr ng-repeat="option in options | orderBy:'name':true">
     <td> {{option.name}}</td>
      <td ng-repeat="desc in option.descriptions |filter:{languageId:'EN'} ">{{desc.description}}</td> 


    </tr>

请建议我一种按 "description" 排序数据的方法。

会不会和外面的ng-repeat一样

<td ng-repeat="desc in option.descriptions | orderBy:'description':true |filter:{languageId:'EN'} ">

您可以使用ngInit预过滤给定语言的描述,然后用它来排序和显示:

<tr ng-repeat="option in options | orderBy:'description'" 
    ng-init="option.description = (option.descriptions | filter:{languageId:'EN'})[0].description">
    <td>{{option.name}}</td>
    <td>{{option.description}}</td>
</tr>

演示: http://plnkr.co/edit/eyRYqfeJ6ewaJnGReGTB?p=preview

您可以编写自定义排序来实现这一点,orderby 中的第二个参数可以是字符串、函数或数组,请参考 Angular order By

<tr ng-repeat="option in options | orderBy:myCustomSort :true">
     <td> {{option.name}}</td>
     <td ng-repeat="desc in option.descriptions |filter:{languageId:'EN'} ">
          {{desc.description}}
     </td> 
</tr>

还有你的 JS,我猜你可以设置一个当前使用的语言的变量,这应该可以解决问题

//inside your controller
$scope.lang = 'EN'; //you can edit this the way you added a filter:'EN'
$scope.myCustomSort = function(opt){
    for(var i=0; i<opt.descriptions.length; i++){
        //written assuming you have one description that is for 'EN'
        //you can sort out the description array first and then return
        if(opt.descriptions[i].languageId === $scope.lang){
            return opt.descriptions[i].description.toUpperCase();
        }
    }
    return '';
}

哦还有一件事你的描述 [2] 有一个空白 space 是乱七八糟的,花了很长时间才弄清楚为什么...... "description": " d Some description", 将首先处理空白**排序规则:)