LoginSignup
21
21

More than 5 years have passed since last update.

TypeScriptでAngularJS

Last updated at Posted at 2014-09-06

参照したスライド

開発環境など

残念。うぃんどうずでした。

  • OS: Windows8.1
  • 開発ツール: VisualStudio Express 2013 for Web Update3

手順

コントローラーのTypeScript化についてだけ以下に記載します。バインドの話やService/Factoryについては参照元スライドをご参照ください。

1.型定義ファイルのインポート

https://github.com/borisyankov/DefinitelyTyped から必要なライブラリについてダウンロードするのは "手仕事感" が強くThe職人芸ですよね。。私はNugetを使います。
http://www.nuget.org/profiles/DefinitelyTyped で登録されているパッケージ一覧を見ることができます。今回はAngularJSのパッケージをインストールします。VisualStudioのパッケージマネージャーコンソールで、

install-package angularjs.TypeScript.DefinitelyTyped

と入力するとAngularJS型定義ファイル一式が /Scripts/typings/angularjs 以下にインストール・プロジェクト追加されます。

2.TypeScriptファイルの作成

(参照したスライドのコードほぼパクらせていただきました。) TypeScriptで記述するのはコントローラークラスだけです。 Angularモジュールへのコントローラー割り付けは従来通りJavaScriptで記述します。

/Scripts/myts/file1.ts
/// <reference path="../typings/angularjs/angular.d.ts" />

module File1 {

    export class SampleCtrl {

        public firstName: string;
        public lastName: string;

        constructor() {
            this.init();
        }

        private init(): void {
            this.firstName = "John";
            this.lastName = "Doe";
        }

        public getFullName(): string {
            return this.firstName + " " + this.lastName;
        }
    }
}

angular.module("MyAngularJs", []).controller("SampleCtrl", [File1.SampleCtrl]);

3.HTMLファイルの作成

これも参照したスライドのをほぼまるパクリです。(ところでng-controllerのas指定なんていう素敵機能以前からありましたっけ?)

/index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="https://code.angularjs.org/1.3.0-rc.0/angular.min.js"></script>
    <script src="Scripts/myts/file1.js"></script>
</head>
<body ng-app="MyAngularJs">
    <div ng-controller="SampleCtrl as c">
        <p>FirstName: {{c.firstName}}</p>
        <p>LastName: {{c.lastName}}</p>
        <p>FullName: {{c.getFullName()}}</p>
    </div>
</body>
</html>
21
21
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
21
21