LoginSignup
7
9

More than 3 years have passed since last update.

ES5で書くAngular v2(1)「Hello, world」

Last updated at Posted at 2016-05-16

※現在この方法は推奨されません

Angular v2がベータ版からRC版となりました。正式リリースが楽しみですね。

1.x系からの変更やTypescriptの採用など、移行に向けて覚える事が多く大変です。

「まずは現行のJavaScriptで動かせないか?」 と思い試行錯誤してみた結果を、
拙筆ではありますが「ES5で書くAngular2」と題して紹介していこうと思います。

Angular v2の入手

自分でnpmしたりビルドできる人はそうされることをおすすめします(最新版を使えるため)。
そうでない場合や手っ取り早くAngular v2を動かしたい場合はCDNを利用すると良いでしょう。

html:Angular v2 Beta.17の利用例
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/Rx.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2-polyfills.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2-all.umd.dev.js"></script>

Hello world サンプルを作る

まずはHTML側を書いていきましょう。
Angular v2はコンポーネント指向であるため、内容は非常にシンプルです。

app.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/Rx.umd.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2-polyfills.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2-all.umd.dev.js"></script>
        <script src="hello-component.js"></script>
    </head>
    <body>
        <hello-component></hello-component>
    </body>
</html>

次にJavaScript側です。

hello-component.js
'use strict';
(function() {
    var app = ng.core
    .Component({
        selector: 'hello-component'
    })
    .View({
        template: '<p>Hello, {{name}} !</p>'
    })
    .Class({
        constructor: function() {
            this.name = 'world';
        }
    });
    document.addEventListener('DOMContentLoaded', function() {
        ng.platform.browser.bootstrap(app);
    });
})();

Componentにはコンポーネント名を、Viewには表示するためのHTMLテンプレートを、Classにはデータモデルの結び付けや処理の内容を書いていきます。

これを実行すると「Hello, world !」と表示されるはずです。
https://codepen.io/puku0x/pen/jqoyXB

まとめ

ES5でもAngular v2を動かすことができました。
今回は簡単なサンプルでしたが、次回からいろいろやっていく予定です。

7
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9