因公司项目需求,技术栈转到了angular2、(因为1已经过时了),便开始学习,为使用ionic2开发hybird的APP做准备。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>template - component </title>
<script type="text/javascript" src="lib/system@0.16.11.js"></script>
<script type="text/javascript" src="lib/angular2.dev.js"></script>
<script type="text/javascript" src="lib/system.config.js"></script>
</head>
<body>
<ez-app></ez-app>
<script type="module">
import {Component,View,bootstrap} from "angular2/angular2";
@Component({selector:"ez-app"}) //最后渲染到页面的总组件
@View({
directives:[EzCard,LwbCard],
template:`
<div class="ez-app">
<h1>EzApp</h1>
<ez-card></ez-card>
</div>`
})
class EzApp{}
@Component({selector : "ez-card"}) //第一个组件
@View({
template : `
<div class="ez-card">
<h1>EzCard</h1>
</div>`
})
class EzCard{}
@Component({selector : "lwb-card"}) //第二个组件
@View({
template : `
<div class="lwb-card">
<h1>{{title}}</h1>
</div>`
})
class LwbCard{
constructor(){
this.title = "这里是双向绑定咯";
}
}
bootstrap(EzApp);
</script>
</body>
</html>
对于属性的绑定、属性使用中括号[],举例 [style.color]="color",color为属性、style.color为要传的值。传值位置跟双向绑定大致一样。
事件
使用一对小括号包裹事件名称,并绑定 到表达式即可,如(click)="onClick()",具体函数跟事件绑定和属性大致是一样的位置,写法为:
this.onClick = function(){}
import {Component,View,bootstrap} from "angular2/angular2";
@Component({selector:"ez-app"})
@View({
template:`
<h1>Your turn! <b>{{sb}}</b></h1>
<button (click)="roulette()">ROULETTE</button>
`
})
class EzApp{
constructor(){
this.names = ["Jason","Mary","Linda","Lincoln","Albert","Jimmy"];
this.roulette();
}
//轮盘赌
roulette(){
var idx = parseInt(Math.random()*this.names.length);
this.sb = this.names[idx];
}
}
bootstrap(EzApp);