orderBy not working in HTML divs

175 views Asked by At

I am trying to implement a ng-repeat functionality into the divs. For that I need to sort the data first (according to the rank it has, provided from an object) and then name it into the div. So I am creating a custom OrderBy function . My sorting functionality works well. However, I am always getting the order of the divs as the same. (Infact, exactly opposite of what I need). I tried using reverse functionalities, but it doesn't work.

My sorting code looks like this:

var res = {        
        "Toyota": 2,
        "Ford": 1,
        "Chrysler": 4,
        "Hyundai": 3,
        "Nissan": 5
};

sortedVal = Object.keys(res).sort(function (a, b){
    return res[a] - res[b];
});

My HTML div looks like this,

<div class="card" ng-repeat="name in data | orderBy: sortedVal ">

I get the correct output in the console. However, the divs are always arranged in the order given below, no matter what I do.

Nissan, Chrysler, Hyundai, Toyota, Ford.

I need them in the order: Ford, Toyota, Hyundai, Chrysler, Nissan.

Note: Don't worry about the "name in data" part, it works well. I am having problems with "OrderBy".

3

There are 3 answers

0
Numyx On

orderBy either takes a string for an object property or a function which defines the order. So their is no need to calculate the sortedVal yourself, you just need to give orderBy the method used to calculate the sortedVal:

$scope.orderFn = function(a, b) {
  return res[a] - res[b]
}

<div ng-repeat="name in data | orderBy: orderFn"></div>

Plunker: http://plnkr.co/edit/lOeblx28wjAV4RCVRxwq?p=preview

1
ShankarSangoli On

You have to add sortedVal to the controller scope and then it will be available in the view.

var res = {        
        "Toyota": 2,
        "Ford": 1,
        "Chrysler": 4,
        "Hyundai": 3,
        "Nissan": 5
};

$scope.sortedVal = Object.keys(res).sort(function (a, b){
    return res[a] - res[b];
});

Or you can create a custom filter to order the objects by value. Something like this.

Html

<div class="card" ng-repeat="(key, value) in data | orderObjectByValue">
      {{key}} {{value}}
</div>

Js

app.filter('orderObjectByValue', function() {
  return function(items) {
    var filtered = Object.keys(items).sort(function (a, b){
        return items[a] - items[b];
    });
    return filtered;
  };
});

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

1
ReeganLourduraj On

AngularJS orderBy filter does just support arrays - no objects. So you have to write an own small filter. Please go through the following fiddle it helps you

http://jsfiddle.net/4tkj8/1/