0

在 stackoverflow 和谷歌上搜索了几个小时后,我没有找到我正在搜索的内容,但我确实找到了一些让我想到替代解决方案的东西。

对象示例:

items = [
{
    title: "This is title", 
    email: "test@test.com",
    status: "confirmed"
},
{
    title: "This another one", 
    email: "someone@something.com",
    status: "pending"
{    
    title: "Just a random string", 
    email: "me@you.co.uk",
    status: "pending"
{    
]

决议:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter',
  pure: false
})
export class FilterPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    if(args == '') { return value; }

    let query = args.toLowerCase();
    return value.filter(task =>
      task.title.toLowerCase().indexOf(query) > -1 ||
      task.email.toLowerCase().indexOf(query) > -1 ||
      task.status.toLowerCase().indexOf(query) > -1 

    );
    
  }
}

<div *ngFor="item of (items | filter:'this is') ">
   {{item | json}}
 </div>

这会给我:

{title: "This is title", email: "test@test.com",status: "confirmed"}

它按原样工作,但我的目的是让它与 RegExp 一起工作,我已经尝试过,但由于某种原因,当我使用 var something = new RegExp(// some rule) 时出现错误。

任何想法都非常感谢。

4

1 回答 1

0

尝试这个

import {Pipe} from 'angular2/core';

// Tell Angular2 we're creating a Pipe with TypeScript decorators
@Pipe({
  name: 'RegexPipe'
})
export class RegexPipe {

  transform(value, args?) {
    // ES6 array destructuring
    let [pattern] = args;
    return value.filter(task => {
        reg = new Regex(pattern);
        found = reg.test(task.title);
      return found;
    });
  }

}

<div *ngFor="item of (items | RegexPipe:'/this is (.)*/') ">
   {{item | json}}
 </div>
于 2016-11-11T14:50:45.883 回答