为什么sort函数正常工作:
<th (click)="sort('transaction_date')">Transaction Date <i class="fa" [ngClass]="{'fa-sort': column != 'transaction_date', 'fa-sort-asc': (column == 'transaction_date' && isDesc), 'fa-sort-desc': (column == 'transaction_date' && !isDesc) }" aria-hidden="true"> </i></th>
当这一个人工作时
<th (click)="sort('user.name')">User <i class="fa" [ngClass]="{'fa-sort': column != 'user.name', 'fa-sort-asc': (column == 'user.name' && isDesc), 'fa-sort-desc': (column == 'user.name' && !isDesc) }" aria-hidden="true"> </i></th>
HTML
<tr *ngFor="let inner of order.purchase_orders | orderBy: {property: column, direction: direction}">
<td>{{ inner.transaction_date | date }}</td>
<td>{{ inner.user.name }}</td>
</tr>
TS
sort(property){
this.isDesc = !this.isDesc; //change the direction
this.column = property;
this.direction = this.isDesc ? 1 : -1;
console.log(property);
};
管
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform(records: Array<any>, args?: any): any {
if(records && records.length >0 ){
return records.sort(function(a, b){
if(a[args.property] < b[args.property]){
return -1 * args.direction;
}
else if( a[args.property] > b[args.property]){
return 1 * args.direction;
}
else{
return 0;
}
});
}
};
}
提前致谢。
答案 0 :(得分:3)
这里的问题是:
对象的嵌套属性,orderBy必须提供排序 第一级属性的基础
我在考虑,inner
应该是这样的,
{
transaction_date : '10/12/2014'
user : {
name : 'something',
...
}
}
尝试使这个对象成为,在第一级获取所有可排序属性 (或者你必须改变顺序)
{
transaction_date : '10/12/2014'
user_name : 'something',
user : {
name : 'something',
...
}
}
试试。
<th (click)="sort('user_name')">
User <i class="fa" [ngClass]="{'fa-sort': column != 'user_name',
'fa-sort-asc': (column == 'user_name' && isDesc),
'fa-sort-desc': (column == 'user_name' && !isDesc) }"
aria-hidden="true">
</i>
</th>
将records.map(record => record['user_name'] = record.user.name);
添加到transform
功能中,如下所示:
这将按照我的建议生成对象:
export class OrderByPipe implements PipeTransform {
transform(records: Array<any>, args?: any): any {
if(records && records.length >0 ){
records.map(record => record['user_name'] = record.user.name); // add here
return records.sort(function(a, b){
....
}
};
}