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

时间:2015-08-20 06:21:38

标签: javascript angularjs angularjs-ng-repeat angularjs-orderby

我的对象看起来像这样:

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

      }]

    }]

我想根据“描述”一侧的“描述”字段对其进行排序,

我可以通过其他字段对此进行排序,例如姓名,电话和年龄,但不是 描述

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

请建议我按“说明”对数据进行排序。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

你可以编写一个可以解决问题的自定义排序,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]有一个空白的空间是弄乱的,花了很长时间才弄明白为什么...... "description": " d Some description",空白将首先被处理**排序规则: )

答案 2 :(得分:0)

不会与外部ng-repeat相同

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