Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-orderby

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


my object looks like this:

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

      }]

    }]

I want to sort this according to the field "description" in side the "descriptions",

I'm able to sort this by other fields such as name, phone and age, but not by 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>

Please suggest me a way to sort the data by "description".


Solution

  • You can use ngInit to prefilter description in given language and then use it for sorting and displaying:

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

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