由于官网给出JavaScript例子不是很完整,此文主要简单的记录用JavaScript写Angular 2 的Hello World程序。
用javascript实现官网英雄指南教程
本文参照官网实例地址:TypeScript实现的英雄编辑器教程-简介
TypeScript实现的英雄编辑器教程-英雄编辑器
保持项目运行:在项目目录下执行npm start
1.本章结束后项目文件目录
angular-quickstart
|---app
| |
| |---app.component.js
| |---app.module.js
| |---main.js
|
|---node_modules ...
|---package.json
|---systemjs.config.js
|---index.html
|---style.css
2.基本数据绑定
修改app/app.component.js
var ng_core = require('@angular/core');
var AppComponent = (function(){
function AppComponent (){
}
AppComponent = ng_core.Component({
selector: 'my-app',
template: '<h1>{{title}}</h1>'
}).Class({
constructor: function() {
this.title = 'Tour of Heroes';
}
});
return AppComponent;
}());
exports.AppComponent = AppComponent;
模板内的{{title}}会被component的数据’Tour of Heroes’代替
4.对象的绑定
修改app/app.component.js
var ng_core = require('@angular/core');
var Hero = (function(){
function Hero(id,name){
this.id = id;
this.name = name;
}
return Hero;
}());
var AppComponent = (function(){
function AppComponent (){
}
AppComponent = ng_core.Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div><label>name: </label>{{hero.name}}</div>
`
}).Class({
constructor: function() {
this.title = 'Tour of Heroes';
this.hero = new Hero(1,'Windstorm');
}
});
return AppComponent;
}());
exports.AppComponent = AppComponent;
模板template内使用“(Esc下面的键)支持多行html代码
模板内的{{hero.name}}会被component的数据hero对象的name属性的值代替。
5.数据双向绑定
app.module.js需要引入FormsModule模块
var ng_core = require('@angular/core');
var platform_browser_dynamic = require('@angular/platform-browser');
var app_component = require('./app.component');
var forms_module = require('@angular/forms');
var AppModule = (function(){
function AppModule(){
};
AppModule = ng_core.NgModule({
imports: [ platform_browser_dynamic.BrowserModule,forms_module.FormsModule],
declarations: [ app_component.AppComponent ],
bootstrap: [ app_component.AppComponent ]
})
.Class({
constructor: function() {}
});
return AppModule;
}());
exports.AppModule = AppModule;
app/app.component.js的template
var ng_core = require('@angular/core');
var AppComponent = (function(){
function AppComponent (){
}
AppComponent = ng_core.Component({
selector: 'my-app',
template:`
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name">
</div>
`,
}).Class({
constructor: function() {
this.title = 'Tour of Heroes';
this.hero = {
id:1,
name:'Windstorm'
};
}
});
return AppComponent;
}());
exports.AppComponent = AppComponent;
这样,在input标签内,修改hero对象的name,则页面hero的上同步显示修改后的name。
备注:javascript初学,不懂太多。