angular2的第一个应用---Hello world!

<!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!字样。

猜你喜欢

转载自blog.csdn.net/sanlingwu/article/details/79347543