ionic2项目开发中,我们会用到排序功能,原以为angular2和angular1中一样,结果不能用啊
官网是这么说的:
https://angular.io/docs/ts/latest/guide/pipes.html#!#no-filter-pipe
"Some of us may not care to minify this aggressively. That's our choice. But the Angular product should not prevent someone else from minifying aggressively. Therefore, the Angular team decided that everything shipped in Angular will minify safely.
The Angular team and many experienced Angular developers strongly recommend that you move filtering and sorting logic into the component itself. The component can expose a filteredHeroes or sortedHeroes property and take control over when and how often to execute the supporting logic. Any capabilities that you would have put in a pipe and shared across the app can be written in a filtering/sorting service and injected into the component."
大概意思就是,pipe 的 orderBy功能你们自己去实现吧!!
ionic g pipe orderBy会生成文件src/pipes/ordre-by.ts
import { Injectable, Pipe } from '@angular/core'; @Pipe({ name: 'orderBy' }) @Injectable() export class OrderBy { /* Takes a value and makes it lowercase. */ static _orderByComparator(a:any, b:any):number{ if((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))){ //Isn't a number so lowercase the string to properly compare if(a.toLowerCase() < b.toLowerCase()) return -1; if(a.toLowerCase() > b.toLowerCase()) return 1; } else{ //Parse strings as numbers to compare properly if(parseFloat(a) < parseFloat(b)) return -1; if(parseFloat(a) > parseFloat(b)) return 1; } return 0; //equal each other } transform(input:any, [config = '+']): any{ if(!Array.isArray(input)) return input; if(!Array.isArray(config) || (Array.isArray(config) && config.length == 1)){ var propertyToCheck:string = !Array.isArray(config) ? config : config[0]; var desc = propertyToCheck.substr(0, 1) == '-'; //Basic array if(!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+'){ return !desc ? input.sort() : input.sort().reverse(); } else { var property:string = propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-' ? propertyToCheck.substr(1) : propertyToCheck; return input.sort(function(a:any,b:any){ return !desc ? OrderBy._orderByComparator(a[property], b[property]) : -OrderBy._orderByComparator(a[property], b[property]); }); } } else { //Loop over property of the array in order and sort return input.sort(function(a:any,b:any){ for(var i:number = 0; i < config.length; i++){ var desc = config[i].substr(0, 1) == '-'; var property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-' ? config[i].substr(1) : config[i]; var comparison = !desc ? OrderBy._orderByComparator(a[property], b[property]) : -OrderBy._orderByComparator(a[property], b[property]); //Don't return 0 yet in case of needing to sort by next property if(comparison != 0) return comparison; } return 0; //equal each other }); } } }