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

查看:145
本文介绍了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天全站免登陆