Zink February 2016

orderBy nested sorting with dropdown is grouping the data

Given the data model below, I am trying to sort the products by manufacturer name and / or by price. It's kind of working and is sorting ascending and descending but it is grouping the sorting by manufacturer so for example, when sorting by price I would expect the following:

Please see jsFiddle here

Expected output (by price)

  1. Apple Macbook - 1200.00

  2. Acer Laptop - 900.00

  3. Apple Ipad - 420.00

  4. Acer Mouse - 20.00

Actual output (by price)

  1. Apple Macbook - 1200.00

  2. Apple Ipad - 420.00

  3. Acer Laptop - 900.00

  4. Acer Mouse - 20.00

It seems like a straightforward issue, but I am new to Angular so just trying to get my head around it. Any help would be great!

<select ng-model="sortBy">
  <option value="" selected="selected">Sort Type</option>
  <option value="+price">Price - high to low</option>
  <option value="-price">Price - low to high</option>
  <option value="-manufacturerName">Manufacturer A-Z</option>
  <option value="+manufacturerName">Manufacturer Z-A</option>
</select>

<div ng-repeat="manufacturer in manufacturer.manufacturers">
  <div ng-repeat="product in manufacturer.products | filter:filterByFeature | orderBy:sortBy">
  // stuff
  </div>
</div>

{
"manufacturers": [
{
  "manufacturerId": 1,
  "manufacturerName": "Apple",
  "products": [
    {
      "name": "Macbook",
      "price": 1200.00
    },
    {
      "name": "Ipad",
      "price": 420.00
    }
  ]
},
{
  "manufacturerId": 2,
  "manufacturerName": "Acer",
  "products": [
    {
      "name": "Laptop",
      "price": 900.00
    },
    {
      "name": "Mouse",
      "price": 20.00
    }
  ]
}
]
}

Answers


tanenbring February 2016

You are not sorting manufacturers. The the ng-repeat around manufacturer.manufacturers does not sort the manufacturers so it will always be the same order, and the sub arrays within a single manufacturer's products will be sorted without regard to the others. You probably want to restructure your data so that it's a single list of products that can be sorted.

$scope.products = _.flatten(manufacturers.map(function(m) {
  return m.products.map(function(p) {
     var o = angular.extend({}, p);
     o.providerName = m.manufacturerName;
     return o;
  });
}));

That should do it (using underscore for the example).

Post Status

Asked in February 2016
Viewed 2,078 times
Voted 5
Answered 1 times

Search




Leave an answer