angular--双向绑定缓存搜索历史、ToDoList

一、原理

    1、搜索框输入文本,点击搜索,数据添加到数组

    2、数组绑定到搜索历史的 页面 <li>标签

    3、标签后跟按钮可删除

# ts 文件定义
# 搜索内容
public keyWord: string;
# 缓存搜索历史
public historyList: any[] = [];
# 搜索历史加入数组
doSearch() {
    if (this.historyList.indexOf(this.keyWord) < 0) {
      this.historyList.push(this.keyWord);
    }
    this.keyWord = '';
}
# 删除搜索历史
deleteHistory(key) {
    this.historyList.splice(key, 1);
}



# html 文件绑定使用
<div class="search">
  <input type="text" [(ngModel)]="keyWord"/>
  <button (click)="doSearch()">搜索</button>

  <hr/>

  <ul>
    <li *ngFor="let item of historyList; let key=index;">
      {{item}}-----<button (click)="deleteHistory(key)">x</button>
    </li>
  </ul>

</div>

二、ToDoList

# ts 文件定义
public keyWord: any;
public historyList: any[] = [];

doAdd(e) {
    if (e.keyCode == 13) {
      if (!this.todolistHasKeyword(this.historyList, this.keyWord)) {
        this.historyList.push({
          title: this.keyWord,
          status: 0
        });
      } else {
        alert('数据已经存在');
      }
      this.keyWord = '';
    }
}

deleteHistory(key) {
    this.historyList.splice(key, 1);
}
# 去重
todolistHasKeyword(todoList: any, keyword: any) {

    // 异步会存在问题
    // todoList.forEach( value => {
    //   if (value.title == keyword){
    //     return true;
    //   }
    // });

    if (keyword == '') { return true; }
    for (let i = 0; i < todoList.length; i++) {
      if (todoList[i].title == keyword){
        return true;
      }

    }
    return false;
}





# html 引用
<div class="todolist">
  <input type="text" [(ngModel)]="keyWord" (keyup)="doAdd($event)"/>

  <hr/>

  <h3>待办事项</h3>

  <ul>
    <li *ngFor="let item of historyList; let key=index;" [hidden]="item.status==0">
      <input  type="checkbox" [(ngModel)]="item.status">
      {{item.title}}-----<button (click)="deleteHistory(key)">x</button>
    </li>
  </ul>

  <h3>以完成事项</h3>
  <ul>
    <li *ngFor="let item of historyList; let key=index;" [hidden]="item.status==1">
      <input  type="checkbox" [(ngModel)]="item.status">
      {{item.title}}-----<button (click)="deleteHistory(key)">x</button>
    </li>
  </ul>

</div>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值