AngularJS filter orderBy, ordering one variable by another

◇◆丶佛笑我妖孽 提交于 2019-12-11 06:02:01

问题


I have a table that is made by ngRepeat from variable first. By filter, instead of first.id_second it writes out second.name, and it works great. Now I'm trying to sort the column first.id_second and I want it to be sorted not by first.id_second, but by second.name. This is my structure:

var first = [{ 
    "id": 0,
    "id_second": "111"
},{
    "id": 1,
    "id_second": "222"
}]

var second = [{
    "id_second": "111",
    "name": "name1"
},{
    "id_second": "222",
    "name": "name2"
}]

Usually, in my html I would have

ng-click="order('col_name')"

And in controller

$scope.order = function(predicate) {
    $scope.predicate = predicate;
    $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
    $scope.first = orderBy($scope.first, predicate, $scope.reverse);
 };

var orderBy = $filter('orderBy');

I don't know how to filter by a property that is from another variable. I suppose I should write a custom filter, but so far wasn't succesfull in it.

Any ideas? Thanx.


回答1:


It seems that there is no way to do this simple, so in the end I wrote a custom orderBy function in which I implemented quicksort.

// arranging data from second to get to the data easier
var secondKeyVal = {};
for (var i = 0; i < $scope.second.length; i++) {
    secondKeyVal[$scope.second[i].id_second] = $scope.second[i].naziv;
}

// function that is called from html
$scope.orderByCustom = function(predicate) {
    $scope.predicate = predicate;
    $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
    $scope.orderByCustomSort();
};

$scope.orderByCustomSort= function() {
    var sorted = quickSort($scope.first);
    $scope.first = sorted;
};

function quickSort(a) {
    if (a.length <= 1) return a;
    var left=[], right=[], pivot=secondKeyVal[a[0].id_second];
    for (var i = 1; i < a.length; i++) {
        secondKeyVal[a[i].id_second] <= pivot ? left.push(a[i]) : right.push(a[i]);
    }

    return quickSort(left).concat(a[0], quickSort(right));
}

Ofcourse, if anyone manages to pull this out without using additional libraries that would make me have to change html filters and orderBy I already use, it would be most welcome :)



来源:https://stackoverflow.com/questions/39572744/angularjs-filter-orderby-ordering-one-variable-by-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!