0

I have a multiple objects array:

{
   "option_12": {
      "id": "0",
      "name": "6 x 330ml",
      "price": "0.00"
   },
   "option_14": {
      "id": 1,
      "name": "12 x 330ml",
      "price": "2.00"
   },
   "option_17": {
      "id": 1,
      "name": "15 x 330ml",
      "price": "4.00"
   },
   "option_10": {
      "id": 1,
      "name": "30 x 330ml",
      "price": "1.00"
   }
}

I'm using the AngularJS Filter orderBy attempting to sort the objects by the price value. So in this case, option_12 should be first and option_10 should be second.

In controller:

$scope.pOptions = $filter('orderBy')($scope.pOptions, 'price');

In my view where I am populating select options using ng-options:

<select ng-model="SelectedPOption" ng-options="option.name for option in pOptions|orderBy:'price'"></select>

Neither of these have any effect. https://docs.angularjs.org/api/ng/filter/orderBy

1 Answer 1

1

Your markup for select is fine. It's the array that has a few problems.

  • Don't use quotes for keys in js.
  • Price should be numeric to sort correctly
  • Enclose all elements of the array using []
  • Don't call filter from js since you call it from the markup.

Example:

$scope.pOptions = [{
    id: "0",
    name: "6 x 330ml",
    price: 0.00
}, {
    id: 1,
    name: "12 x 330ml",
    price: 2.00
}, {
    id: 1,
    name: "15 x 330ml",
    price: 4.00
}, {
    id: 1,
    name: "30 x 330ml",
    price: 1.00
}];

Working example: https://plnkr.co/edit/n09iupr70zRX56kVrYK9?p=preview

EDIT: Since the data arrives like that from the backend API you can iterate the object keys/properties and use map to project the sub-objects to an array:

$scope.pOptions = Object.keys($scope.pOptions).map(function(k) {
   var obj = $scope.pOptions[k];
   obj.price = parseFloat(obj.price);
   return obj;
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer, I tried out the working example. Firstly, I wasn't using the filter in both controller and view - that was just to show what I had tried in both. I tried manipulating the data in your working example to see where exactly it's going wrong. The price and keys being in quotes does not seem to make a difference. Problem is my objects are not enclosed in an array and have names eg '"option_10": '. That's how the data is received from the API - how can i correct this?
Just as you answered I managed with forEach like so: $scope.pOptions = []; angular.forEach($scope.pOptions_, function(option) { $scope.pOptions.push(option); });
It's almost always great to have options :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.