AngularJS 过滤器 orderBy,将一个变量按另一个排序 [英] AngularJS filter orderBy, ordering one variable by another

查看:22
本文介绍了AngularJS 过滤器 orderBy,将一个变量按另一个排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由 ngRepeat 从变量 first 制作的表格.通过过滤器,它会写出 second.name 而不是 first.id_second,而且效果很好.现在我正在尝试对列 first.id_second 进行排序,我希望它不是按 first.id_second 排序,而是按 second.name 排序>.这是我的结构:

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"
}]

通常,在我的 html 中我会有

Usually, in my html I would have

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

在控制器中

$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.

有什么想法吗?谢谢.

推荐答案

这个简单的好像没有办法,所以最后写了一个自定义的 orderBy 函数,在里面实现了quicksort.

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));
}

当然,如果有人设法在不使用其他库的情况下将其拉出,这将使我不得不更改 html 过滤器和 orderBy 我已经使用了,那将是最受欢迎的 :)

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 :)

这篇关于AngularJS 过滤器 orderBy,将一个变量按另一个排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆