使用脚手架新建一个angular项目

cnpm new todo-ng
cd todo-ng
ng serve
// cnpm start

下载模板文件

git clone https://github.com/tastejs/todomvc-app-template.git --depth 1

如果不想下载的话,我已经把模板文件拷贝在这里(index.html)

<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Template • TodoMVC</title><link rel="stylesheet" href="node_modules/todomvc-common/base.css"><link rel="stylesheet" href="node_modules/todomvc-app-css/index.css"><!-- CSS overrides - remove if you don't need it --><link rel="stylesheet" href="css/app.css"></head><body><section class="todoapp"><header class="header"><h1>todos</h1><input class="new-todo" placeholder="What needs to be done?" autofocus></header><!-- This section should be hidden by default and shown when there are todos --><section class="main"><input id="toggle-all" class="toggle-all" type="checkbox"><label for="toggle-all">Mark all as complete</label><ul class="todo-list"><!-- These are here just to show the structure of the list items --><!-- List items should get the class `editing` when editing and `completed` when marked as completed --><li class="completed"><div class="view"><input class="toggle" type="checkbox" checked><label>Taste JavaScript</label><button class="destroy"></button></div><input class="edit" value="Create a TodoMVC template"></li><li><div class="view"><input class="toggle" type="checkbox"><label>Buy a unicorn</label><button class="destroy"></button></div><input class="edit" value="Rule the web"></li></ul></section><!-- This footer should hidden by default and shown when there are todos --><footer class="footer"><!-- This should be `0 items left` by default --><span class="todo-count"><strong>0</strong> item left</span><!-- Remove this if you don't implement routing --><ul class="filters"><li><a class="selected" href="#/">All</a></li><li><a href="#/active">Active</a></li><li><a href="#/completed">Completed</a></li></ul><!-- Hidden if no completed items are left ↓ --><button class="clear-completed">Clear completed</button></footer></section><footer class="info"><p>Double-click to edit a todo</p><!-- Remove the below line ↓ --><p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p><!-- Change this out with your name and url ↓ --><p>Created by <a href="http://todomvc.com">you</a></p><p>Part of <a href="http://todomvc.com">TodoMVC</a></p></footer><!-- Scripts here. Don't remove ↓ --><script src="node_modules/todomvc-common/base.js"></script><script src="js/app.js"></script></body>
</html>

当然你也可以选择自己写…

移植栽培

将下载模板的html代码移植到我们的项目中(app文件夹下的app.component.html)

<section class="todoapp"><header class="header"><h1>todos</h1><input class="new-todo" placeholder="What needs to be done?" autofocus></header><!-- This section should be hidden by default and shown when there are todos --><section class="main"><input id="toggle-all" class="toggle-all" type="checkbox"><label for="toggle-all">Mark all as complete</label><ul class="todo-list"><!-- These are here just to show the structure of the list items --><!-- List items should get the class `editing` when editing and `completed` when marked as completed --><li class="completed"><div class="view"><input class="toggle" type="checkbox" checked><label>Taste JavaScript</label><button class="destroy"></button></div><input class="edit" value="Create a TodoMVC template"></li><li><div class="view"><input class="toggle" type="checkbox"><label>Buy a unicorn</label><button class="destroy"></button></div><input class="edit" value="Rule the web"></li></ul></section><!-- This footer should hidden by default and shown when there are todos --><footer class="footer"><!-- This should be `0 items left` by default --><span class="todo-count"><strong>0</strong> item left</span><!-- Remove this if you don't implement routing --><ul class="filters"><li><a class="selected" href="#/">All</a></li><li><a href="#/active">Active</a></li><li><a href="#/completed">Completed</a></li></ul><!-- Hidden if no completed items are left ↓ --><button class="clear-completed">Clear completed</button></footer>
</section>
<footer class="info"><p>Double-click to edit a todo</p><!-- Remove the below line ↓ --><p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p><!-- Change this out with your name and url ↓ --><p>Created by <a href="http://todomvc.com">you</a></p><p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>

接下来将我们的样式下载并导入进去(我这里使用less:styles.less)

cnpm i todomvc-common todomvc-app-css
/* You can add global styles to this file, and also import other style files */
@import url('todomvc-common/base.css');
@import url('todomvc-app-css/index.css');

实现项目逻辑

模拟数据使用ngFor渲染到界面测试一下(数据列表展示–有数据)

  1. 遍历一个对象数组(app.component.ts定义一个对象数组)
import { Component } from '@angular/core';
const todos = [{id:1,skill:'vue',bool: true},{id:2,skill:'react',bool: true},{id:3,skill:'angular',bool: true}
]
@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.less']
})
export class AppComponent {public todos:{id:number,skill:string,bool:boolean}[] = todos
}
  1. app.component.html的每个li是一个项(使用*ngFor进行循环数组)
<!-- These are here just to show the structure of the list items -->
...<ul class="todo-list"><li *ngFor="let todo of todos"><div class="view"><input class="toggle" type="checkbox" checked><label>{{todo.skill}}</label><button class="destroy"></button></div><input class="edit" value="Create a TodoMVC template"></li></ul>
...
  1. 不同的类状态不同
<!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
completed:该类是完成状态
editing:该类是编辑状态
没有添加任何类:正常状态

隐藏我们的内容(数据列表展示–无数据)

  1. 有数据我们展示,没有数据我们将内容隐藏掉;
  2. 使用*ngIf条件渲染;使用ng-template避免产生额外的标签
  3. 测试一下
export class AppComponent {public todos:{id:number,skill:string,bool:boolean}[] = []
}

添加任务

  1. 在文本框输入文字回车后将该条数据添加到列表中
  2. 使用()绑定事件
<input class="new-todo" placeholder="What needs to be done?" autofocus (keyup.enter)='addTodo($event)'>
  1. 处理业务逻辑
export class AppComponent {...addTodo(e):void {const inpVal = e.target.valueif(!inpVal.length){return;}let id = this.todos[this.todos.length-1].id+1this.todos.push({id,skill:inpVal,bool:false})e.target.value = ''console.log(todos)}
}
  1. 点击选择按钮切换完成和正常状态
  2. 实现数据双向绑定,根据bool的值来给其是否添加completed(表示以完成)该类
      <li *ngFor="let todo of todos" [ngClass]='{completed:todo.bool}'><div class="view"><input class="toggle" type="checkbox" [(ngModel)]="todo.bool"><label>{{todo.skill}}</label><button class="destroy"></button></div><input class="edit" value="Create a TodoMVC template"></li>
  1. 我们需要配置双向绑定(app.module.ts)
...
import { FormsModule } from '@angular/forms';
...imports: [BrowserModule,AppRoutingModule,FormsModule],
...

实现#toggle-all选择框的全选与反选

  1. 当所有的todo,每一条都是已完成(即bool:true)时,那么checkbox(即左上角的小图标高亮显示)
  get toggleAll () {return this.todos.every(t => t.bool)}
<input id="toggle-all" class="toggle-all" type="checkbox" [checked]="toggleAll">
  1. 点击该选择按钮时,当该按钮为true,每一条todo都需要选中,反之亦然…
<input id="toggle-all" class="toggle-all" type="checkbox" [checked]="toggleAll" (change)="toggleAll=$event.target.checked">
  set toggleAll(val:boolean) {console.log(val)this.todos.forEach(t=>t.bool=val)}

删除单个todo

  1. 可以根据id删除,也可以根据索引值删除;使用splice或则filter进行删除都可以,我们高档一点,使用filter+索引值
      <li *ngFor="let todo of todos; let i = index;" [ngClass]='{completed:todo.bool}'><div class="view"><input class="toggle" type="checkbox" [(ngModel)]="todo.bool"><label>{{todo.skill}}</label><button class="destroy" (click)='removeTodo(i)'></button></div><input class="edit" value="Create a TodoMVC template"></li>
  removeTodo(index){this.todos = this.todos.filter((t,i)=>{if(i==index){return false}return true})}

编辑功能

  1. 定义该条编辑项
...public currentEditing: {id: number,skill: string,done: boolean} = null
...
  1. 双击可以编辑该条todo
  2. 离开不选中
      <li *ngFor="let todo of todos; let i = index;" [ngClass]='{completed:todo.bool,editing: currentEditing === todo}'><div class="view"><input class="toggle" type="checkbox" [(ngModel)]="todo.bool"><label (dblclick)='currentEditing = todo'>{{todo.skill}}</label><button class="destroy" (click)='removeTodo(i)'></button></div><input class="edit" [value]="todo.skill" (blur)="saveEdit(todo)"></li>
  saveEdit(t){this.currentEditing = null}
  1. 保存编辑
        <input class="edit" [value]="todo.skill" (keyup.enter)="saveEdit(todo, $event)"(blur)="saveEdit(todo,$event)">
  saveEdit(t,e){t.skill = e.target.valuethis.currentEditing = null}
  1. 取消编辑
...(keyup)="handleEditKeyUp($event)"...
...handleEditKeyUp(e){const {keyCode,target} = eif (keyCode === 27) {// 取消编辑target.value = this.currentEditing.skillthis.currentEditing = null}}
item lift
<span class="todo-count"><strong>{{remaningCount}}</strong> item left</span>
  get remaningCount (){return this.todos.filter(t=>!t.bool).length}

切换按钮(All、Active、Completed)

<ul class="todo-list"><li *ngFor="let todo of filterTodos; let i = index;" [ngClass]='{completed:todo.bool,editing: currentEditing === todo}'>...<ul class="filters"><li><a [ngClass]="{selected:'all'===visibility}" href="#/">All</a></li><li><a [ngClass]="{selected: visibility === 'active'}" href="#/active">Active</a></li><li><a [ngClass]="{selected: visibility === 'completed'}" href="#/completed">Completed</a></li></ul>
 public visibility: string = 'all'hashchangeHandler () {// 当用户点击了锚点的时候,我们需要获取当前的锚点标识// 然后动态的将根组件中的 visibility 设置为当前点击的锚点标识const hash = window.location.hash.substr(1)switch (hash) {case '/':this.visibility = 'all'break;case '/active':this.visibility = 'active'break;case '/completed':this.visibility = 'completed'break;}}get filterTodos () {if (this.visibility === 'all') {return this.todos} else if (this.visibility === 'active') {return this.todos.filter(t => !t.bool)} else if (this.visibility === 'completed') {return this.todos.filter(t => t.bool)}}ngOnInit () {// 初始化的时候手动调用一次this.hashchangeHandler()// 注意:这里要 bind this绑定window.onhashchange = this.hashchangeHandler.bind(this)}

数据持久化

export class AppComponent {public todos:{id:number,skill:string,bool:boolean}[] = JSON.parse(localStorage.getItem('todos') || '[]')
...public visibility: string = 'all'ngDoCheck() {window.localStorage.setItem('todos', JSON.stringify(this.todos))}
}

参考文档

angular 命令

angular-todomvc相关推荐

  1. 开发过程中常用学习资源网站

    @[TOC]目录 一 Golang Go语言中文网 Golang基础-进阶-实战 Go语言标准库文档中文版 语雀 Golang官网 awesome-go Golang学习资料与社区索引 Go语言资料收 ...

  2. angular react_Angular 2 vs React:将会有鲜血

    angular react Angular 2 has reached Beta and appears poised to become the hot new framework of 2016. ...

  3. JavaScript MVC框架PK:Angular、Backbone、CanJS与Ember

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html 内部邀请码:C8E245J (不写邀请码,没有现金送) 国 ...

  4. 史上最全的Angular.js 的学习资源

    Angular.js 的一些学习资源 基础 官方: http://docs.angularjs.org angularjs官方网站已被墙,可看 http://www.ngnice.com/: 官方zi ...

  5. 用Angular制作单页应用视图切换动画

    视图,动画 单页应用(Single Page Web Application)往往有一个基本的要点,那就是把多个视图集成到一个网页内,然后去控制这些视图的显示和隐藏.此外,视图的切换动作几乎都会引入动 ...

  6. angular和vue和react的区别

    一些历史 Angular 是基于 TypeScript 的 Javascript 框架.由 Google 进行开发和维护,它被描述为"超级厉害的 JavaScript MVW 框架" ...

  7. todoMVC 案例一

    todoMVC案例 todoMVC项目可以把Angular的语法基本都能练习一遍,通过项目加强,先看下官网的效果 官网:https://todomvc.com/ todoMVC环境搭建 1.下载模板 ...

  8. AngularJS实现TodoMVC

    一个小的to do list,界面如下 首先安装angular js,出现了无非安装到桌面的问题,安装到D盘了 npm install angular 文件结构: index.html: <!d ...

  9. Angular No name was provided for external module 'XXX' in output.globals 错误

    Angular 7 开发自定义库时,引用ngZorroAntd,build过程中出现 No name was provided for external module 'ng-zorro-antd' ...

  10. angular.isUndefined()

    <!DOCTYPE html> <html><head><meta charset="UTF-8"><title>ang ...

最新文章

  1. 自定义input type=file 样式的方法
  2. oracle addm报告
  3. 蓝桥杯 如何计算 X^X = 10 来求X呢?
  4. Python 基础教程(第2版) 中文版+英文原版下载
  5. elasticSearch6源码分析(7)node
  6. 主键约束、外键约束、唯一约束、检查约束、默认值约束实例
  7. vivo NEX 3 5G真机曝光:瀑布屏+升降镜头
  8. 数据库Sharding的基本思想和切分策略(转)
  9. 你知道这些SOLIDWORKS零件图知识吗?
  10. ANT:修改测试报告的样式jmeter-results-shanhe-me.xsl
  11. 安装无人值守称重系统费用
  12. 关于数学基础的研究现状
  13. win10装sql2000卡在选择配置_win10系统安装SQL2000卡在MADC不动的解决方法
  14. 关于微信手机确认登录问题
  15. 使用IP代理池伪装你的IP(python)
  16. 递归算法中的时间复杂度分析
  17. python plt绘制多子图
  18. vim开启行号显示及全局设置
  19. ibatis mysql 函数_Ibatis+MySql范例(转)
  20. 【C语言】 从零开始的学习历程(一)

热门文章

  1. 华为OD机试 - 热点网站统计(Java JS Python)
  2. 收集的photoshop教程
  3. 在项目上不使用UML是致命的
  4. Prometheus无人机开源项目仿真报错记录
  5. android 内置第三方apk
  6. 是男人就撑100秒自制版(VB)
  7. oracle 优化逻辑读过高(实战详解:逻辑读与arraysize关系)
  8. 【3】Python3 环境搭建
  9. R语言绘制三元相图(ggtern包)
  10. 从旺店通·企业版到金蝶云星空通过接口配置打通数据