您的位置:首页 > Web前端 > AngularJS

[Angular 2] Using Pipes to Filter Data

2016-03-21 20:25 495 查看
Pipes allow you to change data inside of templates without having to worry about changing it in the Controller. Creating a custom Pipe is as simple as giving it a name and a transform function that output what you expect.

Create a Pipe:

import {Pipe} from 'angular2/core';
@Pipe({
name: 'search'
})

export class SearchPipe{
transform(todos){
return todos.filter(
(todoModel) => {
// Only showing the todo starts with 'e'
return todoModel.title.startsWith('e');
}
)
}
}


Using a pipe:

import {Component} from 'angular2/core';
import {TodoService} from './TodoService';
import {TodoItemRenderer} from './TodoItemRenderer';
import {SearchPipe} from './search-pipe';

@Component({
selector: 'todo-list',
pipes: [SearchPipe],
directives: [TodoItemRenderer],
template: `
<ul>
<li *ngFor="#todo of todoService.todos | search">
<todo-item-renderer [todo]="todo"></todo-item-renderer>
</li>

</ul>
`
})


-------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: