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

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

本文关键字:内部 字段 order 对象 ng-repeat Angularjs      更新时间:2023-09-26

我的对象是这样的:

$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",
      }]
    }]

我想根据"description"旁边的字段"description"来排序,

我可以按其他字段排序,如姓名、电话和年龄,但不能按描述。

 <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>

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

您可以使用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

你可以编写一个自定义排序来完成这个任务,order中的第二个参数可以是字符串、函数或数组。

<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]有一个空格很乱,花了很长时间才弄清楚为什么…"description": " d Some description",空格将首先处理**排序规则:)

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

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