Angular2使用體驗
Angular2開發者預覽版出來已有一段時間,這個以速度與移動性能為目的的框架到底如何,今天我們來嘗試一下。
在官網有一段號稱5分鐘入門的教程:
quick start: https://angular.io/docs/js/latest/quickstart.html
Angular團隊在這個版本上所做的改變可以用激進來形容,我們可以看得到無論是在代碼書寫亦或是結構組織上都有了非常大的差異,那么,既然Angular1.x已經如此成熟了,那為何我們還需要Angular2這樣大的改變呢?
其實無論是Angular2還是ReactNative,他們都肩負了前端許多的愿景,既然目前的前端環境調優已經基本達到巔峰,那么從原生、另一門語言的角度去審視改良只是我們突破與超越的小小嘗試而已。
那么Angular2與1.x對比在寫法與上手難度上到底有什么區別呢?
下面我將用Angular2來制作一個Todo示例應用:
在完成了初始化任務后,首先,確保我們的TypeScript編譯監控處于啟用狀態,以下語句是作為ts文件修改編譯監控:
$ tsc --watch -m commonjs -t es5 --emitDecoratorMetadata app.ts
整理一下我們的思路,文件結構應該是這樣的:
我們看到了熟悉的app.js文件,這是以app.ts編譯過后的產物,app.ts:
/// <reference path="../../typings/angular2/angular2.d.ts" />import {Component, View, bootstrap, For, If} from "angular2/angular2"; import {TodoStore} from 'services/todo/TodoStore';
@Component({ selector: 'app', injectables: [TodoStore]//注入TodoStore })
@View({ template:
<div class="page-header"> <div class="form-group"> <div class="input-group"> <div class="input-group-addon">Todo</div> <input type="text" class="form-control" placeholder="輸入TodoItem" autofocus #newtodo (keyup)="add($event,newtodo)"> </div> </div> <ul class="list-group"> <li class="list-group-item" *for="#todo of todoStore.todoList"> <input type="checkbox" [checked]="todo.done" (click)="toggleTodoState(todo)"/> <span [class.done]="todo.done">{{todo.text}}</span> </li> </ul> </div>
, directives: [For, If] })class AppComponent { todoStore : TodoStore;
constructor(todoStore: TodoStore) { this.todoStore = todoStore; } add($event,newtodo){ if($event.which === 13){//判斷是否回車鍵 this.todoStore.add(newtodo.value); newtodo.value = ''; } } toggleTodoState(todo){ todo.done = !todo.done;//反轉done值 }
}
bootstrap(AppComponent);</pre>
在當前版本中,Template關鍵字已經被替換為View關鍵字,文檔傳送門:View
inde.html(墻內用戶推薦將traceur-runtime.js/system.src.js/angular2.dev.js這幾個文件保存在本地,這樣可以不必忍受各種404,超時加載):
<html> <head> <title>Angular 2 Test</title> <link rel="stylesheet" type="text/css" href="styles/bootstrap.min.css"> <script src="lib/traceur-runtime.js"></script> <script src="lib/system.src.js"></script> <script src="lib/angular2.dev.js"></script> </head><body> <!-- The app component created in app.ts --> <app></app> <script> System.import('app'); </script> </body> </html></pre>
services/todo/todo.ts:
export class TodoStore { constructor(){ this.todoList = []; } add(item){ this.todoList.unshift({text:item,done:false,style:'bg-success'}); } }
運行示例:
原創文章轉載請注明:
轉載自AlloyTeam:http://www.alloyteam.com/2015/07/angular2-shi-yong-ti-yan/