user1153484
user1153484

Reputation: 195

Using filter to sort $scope object in ng-repeat

I need to sort a $scope object in ng-repeat based on value. I am able to acheive the sorting by converting it into array through custom filter but either key or value only can be pushed into the array. I needed both key and value to show it in the UI:

$scope.list = {
    test:58uy43: "test:one", 
    test:24ht76: "test:two", 
    test:26df90: "test:three", 
    test:39fg67: "test:four", 
    test:18ds65: "test:five"
}

<div ng-repeat="(key,value) in list">{{key}} : {{value}}</div>

Please help me out on this

Upvotes: 0

Views: 179

Answers (2)

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

I believe that the cleanest way would be to define a function in your controller that returns the sorted list.

$scope.getListSorted = function() {
    $scope.list.sort(function(a, b) { return /*comparison*/; });
};

For numeric values comparison should be a.attr - b.attr if you want to sort ascending.
For string values comparison should be a.attr.localeCompare(b.attr).

Then you can use it in the view

<div ng-repeat="(key,value) in getListSorted()">{{key}} : {{value}}</div>

Upvotes: 1

iDubrovinsky
iDubrovinsky

Reputation: 75

...ng-repeat="o in data | filter: filter | orderBy:sortPredicate:sortReverse"...

where 'filter' is the value you'd like to search on (filter), 'sortPredicate' is a column name which you'd like to order by and 'sortReverse' is a boolean indicating the order of records.

Upvotes: 1

Related Questions