angular2的第一個應用---Hello world!
阿新 • • 發佈:2018-11-29
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <app></app> <script src="https://unpkg.com/[email protected]/dist/zone.js"></script> <script src="https://unpkg.com/[email protected]
/Reflect.js"></script> <script src="https://unpkg.com/[email protected]/bundles/Rx.umd.js"></script> <script src="https://unpkg.com/@angular/[email protected]/bundles/core.umd.js"></script> <script src="https://unpkg.com/@angular/[email protected]/bundles/common.umd.js"></script> <script src="https://unpkg.com/@angular/[email protected]/bundles/compiler.umd.js"></script> <script src="https://unpkg.com/@angular/[email protected]/bundles/platform-browser.umd.js"></script> <script src="https://unpkg.com/@angular/[email protected]/bundles/platform-browser-dynamic.umd.js"></script> <script src="./app.js"></script> </body> </html>
以上html檔案定義了頁面的基本框架。最後引用的是我們自己的應用程式碼。
在index.html的同一個目錄裡面,建立一個app.js檔案如下:
var App = ng.core.Component({
selector: 'app',
template: '<h1>Hello {{target}}!</h1>'
})
.Class({
constructor: function () {
this.target = 'world';
}
});
ng.platform.browser.bootstrap(App);
在以上程式碼中,我們定義了一個名為App的元件,其中帶有一個app選擇器,這個選擇器會匹配整個應用範圍內的所有模版,找出所有app標籤。
我們給Class函式傳遞了一個物件字面量,其中只有一個叫作constructor的方法,在這個函式體中,我們新建了一個叫作target的屬性,值為“world”。
最後一行程式碼呼叫了bootstrap方法來初始化應用,App是應用中的根元件。這裡的bootstrap屬於ng.platformbrowser這個名稱空間,這是因為框架一開始就考慮到應該可以針對不同的平臺而構建,對於不同的平臺把bootstrap方法放在不同的名稱空間下面,這樣angular就可以使用不同的邏輯來初始化應用,包括對不同的平臺引入不同的provider指令集合。
使用http-server指令,開啟瀏覽器即可看到Hello world!字樣。