Skip to content

AngularJS チートシート

JavaScript ベースのフロントエンド Web フレームワーク(Angular 1.x)。

01

はじめに

セットアップとブートストラップ

AngularJS (1.x) は script タグで読み込みます。ng-app がアプリケーションをブートストラップし、ng-controller が DOM のサブツリーにコントローラを接続します。二重波括弧 {{ }} はモデルデータを描画する Angular 式です。

angularjs
<!-- include AngularJS 1.8.x -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="MainCtrl">
    {{ message }}
  </div>
</body>

<script>
  var app = angular.module('myApp', []);
  app.controller('MainCtrl', function($scope) {
    $scope.message = 'Hello AngularJS!';
  });
</script>

ng-app と自動ブートストラップ

モジュール名付きの ng-app は DOMContentLoaded で AngularJS を自動ブートストラップします。ng-strict-di を付けると明示的な依存性アノテーションが強制され、圧縮(minify)によるバグを開発の早い段階で発見できます。1 ページで自動ブートストラップされる ng-app は 1 つだけです。

angularjs
<!-- ng-app on <html> makes the whole page an Angular app -->
<html ng-app="myApp" ng-strict-di>
  <head><title>App</title></head>
  <body>
    <div>{{ 1 + 2 }}</div>
  </body>
</html>

<!-- ng-strict-di enforces dependency injection annotations -->
<!-- (errors if a service uses implicit DI without annotation) -->

手動ブートストラップ

起動を遅らせたい場合(非同期のモジュールロードや設定の取得を待つなど)は angular.bootstrap() を使います。これにより 1 ページに複数の Angular アプリを、それぞれ別のルート要素で動かせます。

angularjs
<!-- HTML has NO ng-app attribute -->
<div id="appRoot">
  {{ message }}
</div>

<script>
  angular.element(document).ready(function() {
    angular.bootstrap(document.getElementById('appRoot'), ['myApp']);
  });
</script>

最初のデータバインディング

ng-app をモジュール名なしで使うと、Angular はデフォルトの ng モジュールによる 'auto' モードで動きます。ng-model が入力を暗黙のスコープの 'name' プロパティに束縛し、{{ }} がリアルタイムに描画します。これが最も単純な形の双方向データバインディングです。

angularjs
<div ng-app>
  <label>Your name:
    <input type="text" ng-model="name">
  </label>
  <p>Hello {{ name || 'stranger' }}!</p>
</div>

モジュールとコントローラの基本

angular.module('name', [deps]) でモジュールを作成し、angular.module('name') で既存のモジュールを取得します。インライン配列アノテーション ['$scope', function($scope){}] はコントローラを minify セーフにします。モジュール作成時には必ず依存関係を明示的に渡しましょう。

angularjs
var app = angular.module('myApp', []); // create module
//          ^name   ^dependencies

app.controller('GreetCtrl', ['$scope', function($scope) {
  $scope.user = { name: 'Ada' };
  $scope.greet = function() {
    return 'Hi ' + $scope.user.name;
  };
}]);
02

モジュール

モジュールの作成と取得

2 引数形式の angular.module(name, deps) は新しいモジュールを作成します。1 引数形式の angular.module(name) は既に定義されたモジュールを取得します。うっかり [] を 2 回渡すと、モジュールへの登録が黙って消えてしまいます。

angularjs
// CREATE a module (second arg = dependency array)
var app = angular.module('myApp', []);

// RETRIEVE an existing module (NO second arg)
// var app = angular.module('myApp');

// common mistake: passing [] again overwrites the module

モジュールの依存関係

依存配列には、このモジュールにプロバイダを注入する他のモジュールを列挙します。ngRoute のような組み込みモジュールはオプションで、明示的に列挙し(かつそのスクリプトを読み込む)必要があります。サブモジュールを使うと大きなアプリを再利用可能な部品に分割できます。

angularjs
var app = angular.module('myApp', [
  'ngRoute',          // built-in routing
  'ngAnimate',        // animation hooks
  'ui.router',        // 3rd-party router
  'myApp.common',     // your own sub-module
]);

Config ブロック

config() はプロバイダ登録の間に、サービスインスタンスが 1 つも作られる前に実行されます。Provider を注入して設定できる唯一の場所です($routeProvider、$locationProvider など)。ルート設定、HTML5 モードの有効化、カスタムバリデーターの登録に使います。

angularjs
app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/home', { templateUrl: 'home.html' })
    .when('/about', { templateUrl: 'about.html' })
    .otherwise({ redirectTo: '/home' });
}]);

Run ブロック

run() はインジェクタが作られ、すべてのプロバイダが設定された後に実行されます — アプリの 'main' エントリポイントです。インスタンスを注入します(プロバイダではなく)。ルート変更や認証チェックのためのグローバルな $rootScope リスナー登録によく使われます。

angularjs
app.run(['$rootScope', 'AuthService', function($rootScope, AuthService) {
  $rootScope.$on('$routeChangeStart', function(event, next) {
    if (!AuthService.isAuthenticated()) {
      event.preventDefault();
    }
  });
}]);

Constant と Value

constant() で登録した値は config() ブロックにも注入できます — プロバイダが必要とする設定に最適です。value() は run フェーズの構成物(サービス、コントローラ)にのみ注入できます。早い段階で必要な設定には constant を使います。

angularjs
// constant: available in BOTH config and run phases
app.constant('API_BASE', 'https://api.example.com');

// value: available only in run phase (injectable as instance)
app.value('defaultPageSize', 20);

// usage in a service:
app.factory('UserSvc', ['API_BASE', function(API_BASE) {
  return { all: function() { /* use API_BASE */ } };
}]);
03

コントローラ

基本のコントローラ

コントローラは $scope の初期状態を設定し、振る舞い(関数)を追加します。コントローラは薄く保ちましょう — ビジネスロジックはサービスに置くべきです。コントローラのコンストラクタは新しいインスタンスが必要になるたび(ng-controller の使用ごとなど)に実行されます。

angularjs
app.controller('TodoCtrl', ['$scope', function($scope) {
  $scope.todos = [
    { text: 'Learn AngularJS', done: true },
    { text: 'Build an app', done: false }
  ];

  $scope.addTodo = function() {
    $scope.todos.push({ text: $scope.todoText, done: false });
    $scope.todoText = '';
  };

  $scope.remaining = function() {
    return $scope.todos.filter(function(t) { return !t.done; }).length;
  };
}]);

controllerAs 構文

controllerAs はコントローラインスタンスをスコープ上の別名(main)で公開します。プロパティやメソッドには $scope の代わりに this を使います。これにより $scope 継承の落とし穴を避け、ネストしたビューでどのコントローラ由来のプロパティかが明確になります。

angularjs
<div ng-controller="MainCtrl as main">
  <p>{{ main.title }}</p>
  <button ng-click="main.save()">Save</button>
</div>

<script>
app.controller('MainCtrl', function() {
  this.title = 'Controller As';
  this.save = function() { /* ... */ };
});
</script>

minify セーフな DI

ミニファイアは関数の引数名を書き換えるため、Angular の名前ベースの依存推論が壊れます。インライン配列アノテーションは関数の前にサービス名を文字列で列挙するため、名前が minify を生き延びます。必ずこのアノテーションか ng-annotate / $inject を使いましょう。

angularjs
// SAFE: inline array annotation (parameter names are string literals)
app.controller('SafeCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('/api/items').then(function(res) { $scope.items = res.data; });
}]);

// UNSAFE: implicit DI breaks when minified
app.controller('UnsafeCtrl', function($scope, $http) { /* ... */ });

$inject プロパティアノテーション

インライン配列の代わりの方法として、コンストラクタ関数にサービス名の $inject 配列を付けられます。関数宣言を読みやすく再利用しやすく保てます。両スタイルは等価です — どちらかに統一するか、ng-annotate で自動化しましょう。

angularjs
function UserCtrl($scope, UserService) {
  UserService.list().then(function(users) {
    $scope.users = users;
  });
}
// explicit dependency list on the function
UserCtrl.$inject = ['$scope', 'UserService'];

app.controller('UserCtrl', UserCtrl);

ネストしたコントローラと継承

子スコープは親スコープをプロトタイプ的に継承するため、子のコントローラは親のプロパティを読めます。しかし子でプリミティブを代入すると親を更新せず覆い隠す新しいローカルプロパティが作られます — よくある落とし穴です。オブジェクト(ドット記法)か controllerAs で回避しましょう。

angularjs
<div ng-controller="ParentCtrl">
  <p>{{ shared }}</p>      <!-- sees parent's 'shared' -->
  <div ng-controller="ChildCtrl">
    <p>{{ shared }}</p>    <!-- inherits, can shadow -->
    <p>{{ childOnly }}</p>
  </div>
</div>

app.controller('ParentCtrl', ['$scope', function($scope) {
  $scope.shared = 'from parent';
}]);
app.controller('ChildCtrl', ['$scope', function($scope) {
  $scope.childOnly = 'child only';
  $scope.shared = 'overridden by child'; // shadows parent
}]);

コントローラの後始末($destroy)

コントローラのスコープが破棄されるとき(ページ遷移など)の後始末には、$scope の $destroy イベントを購読します。$interval/$timeout のタイマーをキャンセルし、window/リスナーをunbind し、参照を解放してメモリリークを防ぎましょう。Angular 自身のスコープウォッチャーは自動的に片付きます。

angularjs
app.controller('TimerCtrl', ['$scope', '$interval', function($scope, $interval) {
  var timer = $interval(function() { $scope.now = Date.now(); }, 1000);

  $scope.$on('$destroy', function() {
    $interval.cancel(timer); // free the resource
  });
}]);
04

$scope

$scope の基本

$scope はコントローラとビューをつなぐ糊です — テンプレートが束縛するモデルと振る舞いを保持します。Angular はコントローラごとに新しいスコープを作り、テンプレートの式はそのスコープ(とその親)に対して評価されます。

angularjs
app.controller('MsgCtrl', ['$scope', function($scope) {
  $scope.message = 'Hi';          // model on scope
  $scope.count = 0;
  $scope.inc = function() {
    $scope.count++;
  };
}]);

// In HTML: {{ message }}, {{ count }}, ng-click="inc()"

スコープの継承(プロトタイプ的)

子スコープは JavaScript のプロトタイプチェーンで親スコープを継承します。親のプロパティの読み取りは可能ですが、子でプリミティブを代入する(例:$scope.name = 'x')と親を覆い隠すローカルコピーができます。オブジェクト(user.name)に束縛すれば、書き込みがチェーンの上へ伝播します。

angularjs
<!-- primitive on parent: child writes a NEW copy -->
<div ng-controller="ParentCtrl">
  <div ng-controller="ChildCtrl">
    <input ng-model="name"> <!-- shadows parent.name -->
  </div>
</div>

<!-- object avoids the shadowing gotcha -->
app.controller('ParentCtrl', ['$scope', function($scope) {
  $scope.user = { name: 'Ada' }; // child edits user.name -> updates parent
}]);

$rootScope

$rootScope はスコープ階層の頂点で、他のすべてのスコープはそこから派生します。ここに置いたプロパティはすべてのテンプレートから見えます。本当にグローバルな値(アプリ名、セッションフラグ)だけに控えめに使いましょう — 乱用すると隠れた結合が生まれ状態を追跡しにくくなります。

angularjs
app.run(['$rootScope', function($rootScope) {
  $rootScope.appName = 'MyApp';     // available everywhere
  $rootScope.version = '1.0';
}]);

<!-- any template -->
<footer>© {{ appName }} {{ version }}</footer>

スコープイベント:$emit / $broadcast / $on

$emit は $rootScope まで上方向へ伝わるイベントを発火し、$broadcast はすべての子スコープへ下方向に伝えます。$on はリスナーを登録し、登録解除用の関数を返します。データは第 2 引数で渡します。リークを避けるため $destroy でリスナーを解除しましょう。

angularjs
// travel UP toward $rootScope
$scope.$emit('userLoggedOut', { userId: 7 });

// travel DOWN to all descendant scopes
$scope.$broadcast('itemAdded', { id: 99 });

// listen for an event
var unbind = $scope.$on('itemAdded', function(event, args) {
  console.log('item', args.id);
});
// stop listening when scope is destroyed
$scope.$on('$destroy', unbind);

$new、$id、$parent

$new(isolated, parent) で子(または分離)スコープを作れます。$id は一意の数値 id、$parent は親スコープへの参照です。主にディレクティブ内部で使われます。手動で作ったスコープは必ず $destroy() を呼び、ウォッチャーを取り除いてメモリリークを防ぎましょう。

angularjs
var child = $scope.$new();        // create a child scope
child.extra = 'child data';
console.log(child.$id);          // unique scope id
console.log(child.$parent === $scope); // true
// ...
child.$destroy();                // remove from hierarchy

分離スコープ(ディレクティブのプレビュー)

ディレクティブで scope: {} を設定すると、親からプロトタイプ的に継承しない分離スコープができます — 再利用可能なコンポーネントに不可欠です。親との通信は宣言されたバインディング(@、=、&)だけを通じて行われます。これによりコンポーネントが周囲のスコープを誤って読んだり汚染したりするのを防ぎます。

angularjs
app.directive('userCard', function() {
  return {
    scope: {              // ISOLATE scope: does NOT inherit parent
      user: '=',          // two-way binding
      onKick: '&'         // expression binding
    },
    template: '<p>{{ user.name }}</p>'
  };
});

<!-- usage -->
<user-card user="currentUser" on-kick="removeUser()"></user-card>
05

式

基本の式

Angular 式は JavaScript 風ですが、$scope(window ではなく)をコンテキストに評価されます。算術、文字列連結、メンバーアクセス、三項演算子をサポートします。JS と違い、undefined/null は空文字列として表示されます('undefined' という文字列にはならない)。オプショナルチェーン演算子はサポートされていません。

angularjs
<p>{{ 1 + 2 }}</p>                <!-- 3 -->
<p>{{ 'Hello, ' + name }}</p>
<p>{{ user.name }}</p>
<p>{{ items.length }} items</p>
<p>{{ obj?.nested }}</p>           <!-- AngularJS does NOT support ?. -->

式と JavaScript の違い

式は JS より制限されます:文(if/for/while)が書けず、new/throw もなく、カンマも関数定義も使えず、一部のバージョンではビット演算も不可です。$scope をコンテキストに評価され、エラーは静かに握りつぶされます($exceptionHandler に記録)。これでテンプレートが安全かつ宣言的に保たれます。

angularjs
<!-- ALLOWED in expressions -->
{{ a + b }}
{{ cond ? 'yes' : 'no' }}
{{ user.getName() }}
{{ [1,2,3].length }}

<!-- NOT allowed: control flow, new, throw, comma operator -->
{{ if (x) { ... } }}     <!-- SyntaxError -->
{{ throw new Error() }}  <!-- not allowed -->

1 回だけのバインディング(::)

:: 接頭辞は 1 回限りのバインディングを作ります:Angular は式を評価し、定義済み(非 undefined)になったらウォッチャーを削除します。これでダイジェストサイクルのウォッチャー数が大幅に減り、初回ロード後に変わらないデータのパフォーマンスが向上します。

angularjs
<!-- AngularJS 1.3+ -->
<p>{{ ::user.name }}</p>           <!-- evaluated once, then unwatched -->
<li ng-repeat="item in ::items">{{ ::item.label }}</li>

<!-- good for static data that never changes -->
<h1>{{ ::conferenceTitle }}</h1>

$eval と $parse

$scope.$eval(expr) は式文字列をスコープに対してパースして実行します。$parse は式を 1 回コンパイルして再利用可能な getter/setter 関数にします — 文字列を何度も再評価するよりはるかに効率的です。式バインディングを消費するディレクティブ/サービス内では $parse を使いましょう。

angularjs
// evaluate an expression against $scope
var result = $scope.$eval('1 + 2 * count');   // 1 + 2*count
// $scope.$eval(expr, locals)

// compile once, reuse: more efficient for repeated eval
var getter = $parse('user.name');
var name = getter($scope);
getter.assign($scope, 'Ada'); // two-way: sets user.name

式の中のフィルタ

パイプ | は式にフィルタを適用し、複数のフィルタは左から右へ連結されます。引数はコロンで渡します。フィルタは便利ですが、ダイジェストのたびに再実行されます — 大きなリストはコントローラ側で $filter か計算済みプロパティを使ってフィルタする方が高性能です。

angularjs
<p>{{ price | currency }}</p>             <!-- $1.99 -->
<p>{{ today | date:'yyyy-MM-dd' }}</p>    <!-- 2025-01-01 -->
<p>{{ name | uppercase }}</p>
<p>{{ items | filter:query | orderBy:'name' }}</p>

<!-- chained with |, arguments after : -->

ng-bind と ng-cloak

Angular がブートストラップする前、ブラウザは生の {{ }} を表示します(「未コンパイルコンテンツのフラッシュ」)。ng-bind は Angular が動いた後にのみ要素のテキストへ値を書き込むため、フラッシュを避けられます。ng-cloak を CSS ルールと併用すると、Angular がコンパイルし終えるまで要素を隠せます。

angularjs
<!-- raw {{ }} may flash before Angular compiles -->
<p>{{ message }}</p>

<!-- ng-bind avoids the flash -->
<p ng-bind="message"></p>

<!-- ng-cloak hides elements until compiled -->
<style>[ng-cloak] { display: none; }</style>
<p ng-cloak>{{ message }}</p>
06

組み込みディレクティブ

ng-model(双方向バインディング)

ng-model はフォーム入力をスコープのプロパティに双方向同期で束縛します:入力の変更がモデルを更新し、モデルの変更が入力を更新します。input、textarea、select、checkbox/radio で動作します。プリミティブを覆い隠す問題を避けるため、必ずドット付きプロパティ(user.name)に束縛しましょう。

angularjs
<input type="text" ng-model="user.name">
<p>Hello, {{ user.name }}</p>

<!-- checkbox binds to boolean -->
<input type="checkbox" ng-model="agree"> I agree

<!-- select binds the chosen option's value -->
<select ng-model="color">
  <option value="r">Red</option>
  <option value="g">Green</option>
</select>

ng-repeat

ng-repeat はコレクションの各アイテムに対して要素を複製します。$index、$first、$last、$middle、$even、$odd が公開されます。必ず track by で安定した識別子を与え、配列が変わったときに DOM ノードを再利用できるようにしましょう — 全体の再描画を避け、重複キーエラーも解消できます。

angularjs
<ul>
  <li ng-repeat="item in items track by item.id">
    {{ $index }}: {{ item.name }}
    <span ng-if="$first">(first)</span>
    <span ng-if="$last">(last)</span>
  </li>
</ul>

<!-- ng-repeat over object -->
<li ng-repeat="(key, value) in config">{{ key }} = {{ value }}</li>

ng-if / ng-show / ng-hide

ng-if は要素(とその子スコープ)を DOM に条件付きで挿入/削除します — トグルは高コストですが、非表示のときは安価です。ng-show/ng-hide は CSS クラスを切り替えるだけで要素は DOM に残ります — トグルは安価ですが、要素は常にコンパイルされています。めったに表示しないコンテンツには ng-if を推奨します。

angularjs
<!-- ng-if: removes/adds element from DOM -->
<div ng-if="user.isAdmin">Admin tools</div>

<!-- ng-show/ng-hide: toggles display:none only -->
<div ng-show="isLoading">Loading...</div>
<div ng-hide="isLoggedIn">Please log in</div>

ng-class と ng-style

ng-class はオブジェクト(真と評価されたキーがクラスになる)、クラス名の配列、文字列を受け付けます。ng-style は CSS プロパティ名を値にマッピングするオブジェクトを取ります。どちらもダイジェストごとに再評価されるため、静的なスタイリングには素の class 属性を使い、これらは状態駆動のスタイリングに使いましょう。

angularjs
<!-- object form: keys are classes, truthy values apply them -->
<div ng-class="{ active: tab === 1, disabled: !enabled }"></div>

<!-- array form -->
<div ng-class="[styleA, styleB]"></div>

<!-- ng-style: object of CSS properties -->
<div ng-style="{ color: theme.color, 'font-size': theme.size + 'px' }">
  Styled text
</div>

ng-bind-template と ng-init

ng-bind-template は複数の式を要素のテキストへ、生の {{ }} なしで束縛します。ng-init は要素の初期化時に 1 回式を評価します — デモには便利ですが、ロジックをマークアップに置くことになるため実アプリでは非推奨です。初期状態はコントローラで設定しましょう。

angularjs
<!-- bind multiple expressions to text -->
<p ng-bind-template="Hello {{ first }} {{ last }}"></p>

<!-- ng-init: set a local (use sparingly, prefer controller) -->
<div ng-init="qty = 1; cost = 5">
  Total: {{ qty * cost }}
</div>

ng-src / ng-href / ng-disabled

src='{{ }}' の代わりに ng-src と ng-href を使いましょう。そうしないと Angular が補間する前にブラウザがリテラルの '{{ }}' URL へリクエストを送ってしまいます。ng-disabled は式に基づいて disabled 属性を切り替えます — フォームが無効な間やリクエスト中に送信ボタンを無効化するのに最適です。

angularjs
<!-- avoid broken requests before binding resolves -->
<img ng-src="{{ user.avatarUrl }}" alt="avatar">
<a ng-href="{{ profileUrl }}">Profile</a>

<button ng-disabled="form.$invalid || saving">
  {{ saving ? 'Saving...' : 'Save' }}
</button>
07

カスタムディレクティブ

基本のディレクティブ

ディレクティブは HTML を拡張します。restrict: 'E' はカスタム要素(<greeting>)、'A' は属性になります。最も単純なディレクティブはテンプレートを返すだけです。デフォルトでは Element/Attribute の restrict を使い、Class/Comment はまれです。テンプレートベースのディレクティブにはモダンなベストプラクティスとしてコンポーネントを推奨します。

angularjs
app.directive('greeting', function() {
  return {
    restrict: 'E',              // E=element, A=attr, C=class, M=comment
    template: '<h1>Hello there!</h1>'
  };
});

<!-- usage -->
<greeting></greeting>
<!-- or as attribute: <div greeting></div> -->

ディレクティブ定義オブジェクト(DDO)

ディレクティブ定義オブジェクトはあらゆる側面を設定します:restrict、scope(分離するかどうか)、template/templateUrl、transclude、controller、link 関数。templateUrl はテンプレートを $http で(キャッシュ付きで)読み込み、template はインラインです。DOM 操作は link に、ビューモデルのロジックは controller に置きましょう。

angularjs
app.directive('card', function() {
  return {
    restrict: 'E',
    scope: {},                  // isolate scope
    templateUrl: 'card.html',
    transclude: true,
    controller: function() { /* ... */ },
    controllerAs: 'vm',
    bindToController: {},
    link: function(scope, el, attrs) { /* DOM work */ }
  };
});

分離スコープのバインディング(@ = &)

@ は属性を文字列として読みます(片方向、親→子、補間あり)。= は親の式への双方向バインディングを作ります。& は親スコープで式を実行する関数を公開します — イベントコールバックに使います。この 3 つのバインディングが再利用可能なディレクティブコンポーネントの心臓部です。

angularjs
app.directive('profile', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@',          // read attribute as STRING (one-way)
      user: '=',          // two-way binding to expression
      onSave: '&'         // callback: evaluate expression in parent scope
    },
    template: '<p>{{ name }} / {{ user.email }}</p>'
  };
});

<profile name="{{ n }}" user="currentUser" on-save="save()"></profile>

Link 関数

link 関数はディレクティブの要素がコンパイルされた後に実行されます。直接の DOM 操作、イベントリスナー(jQuery Lite の .on 経由)、attrs.$observe による補間属性の監視に使います。scope はディレクティブのスコープ、element は jqLite でラップされた DOM ノード、attrs は正規化された属性です。

angularjs
app.directive('highlight', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.on('mouseenter', function() {
        element.css('background', 'yellow');
      });
      element.on('mouseleave', function() {
        element.css('background', '');
      });
      attrs.$observe('highlight', function(val) {
        // react to attribute interpolation changes
      });
    }
  };
});

Compile 関数

compile 関数は Angular が ng-repeat などのためにテンプレートを複製する前に、元のテンプレート要素に対して 1 回だけ実行されます。スコープを必要としないテンプレートレベルの変換に使います。link 関数(または pre/post link のオブジェクト)を返します。ほとんどのディレクティブは compile を必要とせず、インスタンス単位の処理には link を推奨します。

angularjs
app.directive('repeatN', function() {
  return {
    restrict: 'E',
    compile: function(tElement, tAttrs) {
      // runs ONCE on the TEMPLATE element, before cloning
      var n = parseInt(tAttrs.count, 10);
      for (var i = 1; i < n; i++) {
        tElement.after(tElement.clone());
      }
      // optionally return a (post) link function
      return function link(scope, el, attrs) {
        el.addClass('repeated');
      };
    }
  };
});

トランスクルージョン

transclude: true は元の要素の内容を取り込んで、テンプレート内の ng-transclude の位置に挿入します。トランスクルードされたコンテンツは、ディレクティブの分離スコープではなく元の(親の)スコープを保ちます。これによりパネル、モーダル、カードのようなラッパーディレクティブが、呼び出し側が渡す任意のコンテンツを包めます。

angularjs
app.directive('panel', function() {
  return {
    restrict: 'E',
    transclude: true,
    template: '<div class="panel"><div class="panel-body" ng-transclude></div></div>'
  };
});

<!-- the inner content lands inside ng-transclude -->
<panel>
  <h3>Title</h3>
  <p>Body content goes here.</p>
</panel>
08

フィルタ

組み込みフィルタ

Angular には number、currency、date、lowercase、uppercase、json、limitTo、orderBy、filter が付属します。コロンの後の引数がフィルタを設定します。currency は ISO 記号やカスタム文字を受け付けます。フィルタはダイジェストのたびに再実行されるため、重い計算はキャッシュするかコントローラ側で計算しましょう。

angularjs
<p>{{ 1234.5 | number:2 }}</p>          <!-- 1,234.50 -->
<p>{{ 9.99 | currency:'USD' }}</p>     <!-- $9.99 -->
<p>{{ 128 | currency:'&euro;' }}</p>   <!-- €128.00 -->
<p>{{ 'hi' | uppercase }}</p>          <!-- HI -->
<p>{{ 'HI' | lowercase }}</p>          <!-- hi -->
<p>{{ 'a b c' | limitTo:2 }}</p>       <!-- a  -->

date フィルタ

date フィルタは Date オブジェクト、ISO 8601 文字列、エポックミリ秒を整形します。定義済みの書式には 'short'、'medium'、'long'、'full'、'shortDate'、'mediumDate'、'shortTime' があります。カスタム書式はトークンを使います:y(年)、M(月)、d(日)、H(時)、m(分)、s(秒)、EEEE(曜日の正式名)。

angularjs
<p>{{ now | date }}</p>                       <!-- Jan 1, 2025 -->
<p>{{ now | date:'yyyy-MM-dd' }}</p>        <!-- 2025-01-01 -->
<p>{{ now | date:'shortTime' }}</p>         <!-- 3:45 PM -->
<p>{{ now | date:'EEEE, MMMM d, y' }}</p>   <!-- Wednesday, January 1, 2025 -->

<!-- accepts a Date, ISO string, or millis timestamp -->

filter フィルタ(配列検索)

filter フィルタは文字列、オブジェクト、述語関数に一致する配列の要素を選びます。オブジェクトは、指定したフィールドに値を含む要素に一致します。省略可能な第 3 引数 true で完全一致を強制できます。大きな配列は、ダイジェストごとの再実行を避けるためコントローラ側でフィルタしましょう。

angularjs
<!-- match any field containing the query string -->
<li ng-repeat="u in users | filter:query">{{ u.name }}</li>

<!-- match a specific field with an object -->
<li ng-repeat="u in users | filter:{ role: 'admin' }">{{ u.name }}</li>

<!-- strict equality on a field -->
<li ng-repeat="u in users | filter:{ id: 5 }:true">{{ u.name }}</li>

orderBy フィルタ

orderBy は配列をフィールド名(降順は接頭辞 '-')、そのようなフィールドの配列、または比較関数でソートします。ダイジェストごとに新しいソート済み配列を作るため、大きなリストはコントローラで 1 回ソートして再利用しましょう。filter と組み合わせると検索 + ソートの UI を実現できます。

angularjs
<!-- ascending by 'name' -->
<li ng-repeat="u in users | orderBy:'name'">{{ u.name }}</li>

<!-- descending -->
<li ng-repeat="u in users | orderBy:'-name'">{{ u.name }}</li>

<!-- multiple fields -->
<li ng-repeat="u in users | orderBy:['role','-age']">{{ u.name }}</li>

<!-- by a function -->
<li ng-repeat="u in users | orderBy:scoreFn">{{ u.name }}</li>

カスタムフィルタ

app.filter でフィルタファクトリを登録します。ファクトリは、入力(パイプの前の値)と追加の引数を受け取って変換する関数を返します。フィルタは純粋で副作用がない必要があります。注入可能なので、ファクトリ内で他のサービスに依存できます。

angularjs
app.filter('capitalize', function() {
  return function(input) {
    if (!input) return '';
    input = String(input);
    return input.charAt(0).toUpperCase() + input.slice(1).toLowerCase();
  };
});

<!-- usage -->
<p>{{ 'hELLo' | capitalize }}</p>   <!-- Hello -->

コントローラでの $filter サービス

$filter を注入すると JS 内(コントローラ、サービス)でフィルタを適用できます。$filter('name')(value, arg1, arg2) のように呼びます。これでダイジェストごとのフィルタ再実行を避け、結果を再利用できます。ビューだけでなくロジック内でフィルタ済みの値が必要なときに有用です。

angularjs
app.controller('ListCtrl', ['$scope', '$filter', function($scope, $filter) {
  $scope.users = [/* ... */];

  // run the orderBy filter programmatically
  $scope.sorted = $filter('orderBy')($scope.users, 'name');

  // currency filter to format a number
  $scope.priceText = $filter('currency')(99.5, '$');
}]);
09

サービス($http、$location など)

$http の基本

$http は XHR リクエストを実行し Promise を返します。解決される値は data、status、headers、config を持つレスポンスオブジェクトです。.then が成功を、.catch がエラーを処理します。Angular 1.6 から .success/.error コールバックは削除されたので、一貫して promise の .then/.catch を使いましょう。

angularjs
app.controller('ApiCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('/api/users')
    .then(function(response) {
      $scope.users = response.data;       // response: {data, status, headers, config}
    })
    .catch(function(error) {
      console.error('failed', error.status);
    });
}]);

設定付きの $http POST/PUT

get/post/put/delete/patch/jsonp/head にはショートカットメソッドがあります。完全に制御したい場合は設定オブジェクトを渡します:params はクエリ文字列になり、headers はリクエストヘッダーを設定し、responseType はボディのパース方法を制御します。$http はデフォルトの変換(JSON パース)を自動的に適用します。

angularjs
$http.post('/api/users', { name: 'Ada' })
  .then(function(res) { console.log('created', res.data); });

// with headers / query params / response type
$http({
  method: 'GET',
  url: '/api/report',
  params: { format: 'pdf' },
  headers: { 'X-Auth': token },
  responseType: 'arraybuffer'
}).then(function(res) { /* res.data is binary */ });

$location サービス

$location は window.location のラッパーで、ブラウザ URL とダイジェストサイクルの同期を保ちます。パス、クエリパラメータ、ハッシュの読み書きに使います。HTML5 のきれいな URL を有効にするには、$locationProvider.html5Mode(true) を設定し <base> タグを追加します。

angularjs
// read the URL
$location.path();          // '/users/42'
$location.search();        // { tab: 'edit' }
$location.hash();          // 'top'
$location.absUrl();        // full URL

// change without full reload
$location.path('/dashboard');
$location.search('q', 'angular');   // ?q=angular
$location.hash('section-2');

$timeout と $interval

$timeout と $interval は setTimeout/setInterval のダイジェスト対応ラッパーです — $apply を発火するためスコープの更新が反映されます。リークや「破棄済みスコープでのダイジェスト」エラーを防ぐため、$destroy で必ずキャンセルしましょう。ダイジェストが不要なら第 3 引数に false を渡してスキップできます。

angularjs
// $timeout: like setTimeout but triggers a $digest
var promise = $timeout(function() {
  $scope.status = 'ready';
}, 1000);

// cancel
$timeout.cancel(promise);

// $interval: like setInterval, also digest-aware
var ticker = $interval(function() { $scope.now = Date.now(); }, 5000);
$scope.$on('$destroy', function() { $interval.cancel(ticker); });

$log と $window / $document

$log は console の薄いラッパーで、log/info/warn/error/debug をサポートし、本番用ロギングへ decorate できます。$window と $document はグローバルをラップします — window/document を直接呼ぶのではなく必ず注入しましょう。そうすればテストでモックでき、コードは環境非依存のままになります。

angularjs
app.controller('LogCtrl', ['$log', '$window', function($log, $window) {
  $log.log('plain');
  $log.info('info');
  $log.warn('warning');
  $log.error('error');

  $window.alert('Hi');      // safer than bare alert()
  $window.innerWidth;
}]);

// $document wraps document; $window wraps window.
// Injecting them (instead of using globals) makes testing easy.

$rootScope.broadcast とグローバルイベント

アプリ全体のイベント(ログイン/ログアウト、テーマ変更)には $rootScope.$broadcast を使います。どのスコープのリスナーも受け取ります。$rootScope のリスナーだけが聞くべきイベントには、$rootScope.$emit の方が安価です(下降しない)。グローバルイベントの乱用は避け、ほとんどの通信には明示的な API を持つサービスを推奨します。

angularjs
// anywhere: broadcast a global event
$rootScope.$broadcast('auth:logout');

// in a controller: listen
$scope.$on('auth:logout', function() {
  $scope.currentUser = null;
});

// $emit on $rootScope = effectively global too
$rootScope.$emit('something', data); // only $rootScope.$on hears this
10

Factory、Service、Provider

factory()

factory() はサービスインスタンスを返す関数を受け取ります — ファクトリは 1 回だけ実行され(シングルトン)、戻り値が共有されます。サービス作成の最も一般的な方法で、きれいな API の背後にプライベート状態をカプセル化するのに最適です。返したもの(オブジェクト、関数、プリミティブ)が何であれ、それがサービスになります。

angularjs
app.factory('UserService', ['$http', function($http) {
  var current = null;            // private state

  return {
    login: function(creds) {
      return $http.post('/login', creds).then(function(res) {
        current = res.data;
        return current;
      });
    },
    getCurrent: function() { return current; },
    isLoggedIn: function() { return !!current; }
  };
}]);

service()

service() はコンストラクタを new でインスタンス化するため、this にプロパティを付けます。新しいインスタンスを返すファクトリと等価で、どちらもシングルトンです。コンストラクタ/クラススタイルが好みなら service()、特定のオブジェクトを返したいときや何かをラップしたいときは factory() を使いましょう。

angularjs
app.service('Counter', function() {
  // invoked with 'new' -> 'this' is the instance
  this.count = 0;
  this.inc = function() { this.count++; };
  this.reset = function() { this.count = 0; };
});

// usage: Counter.inc(); Counter.count;

provider()

provider() は最も低レベルのレシピです:設定時のオブジェクト(セッター付き)と、インスタンスを構築する $get ファクトリを公開します。config() ブロックに注入できるのはプロバイダだけです(接尾辞 'Provider')。サービスがインスタンス化前に設定を必要とするときに provider() を使い、それ以外は factory() を推奨します。

angularjs
app.provider('Greeter', function() {
  // config-time: defaults settable from .config()
  this.greeting = 'Hello';        // default

  this.setGreeting = function(g) { this.greeting = g; };

  // factory that produces the service instance
  this.$get = function() {
    var self = this;
    return {
      greet: function(name) { return self.greeting + ', ' + name + '!'; }
    };
  };
});

// configure in a config block:
app.config(['GreeterProvider', function(GreeterProvider) {
  GreeterProvider.setGreeting('Bonjour');
}]);

constant() と value() の違い

どちらもシンプルな注入可能な値を登録します。constant() は config フェーズでも利用可能(プロバイダから使える)で不変です。value() は run フェーズでのみ利用できます。経験則:プロバイダが依存する設定には constant、実行時に共有するデータやヘルパーには value を使いましょう。

angularjs
// constant: injectable in config AND run phases
app.constant('MAX_USERS', 1000);

// value: injectable in run phase only (not config)
app.value('toastConfig', { duration: 3000 });

// value can hold any type, even a function
app.value('logger', function(msg) { console.log(msg); });

factory と service と provider

内部ではすべてのレシピが provider です:factory の関数は $get になり、service はコンストラクタを new するファクトリです。読みやすさで選びましょう:ほとんどのケースは factory、コンストラクタスタイルのクラスは service、インスタンス化前の設定が必要なら provider。利用側コンポーネントは消費するだけなので、選択は内部的なものです。

angularjs
// all three are singletons; the difference is HOW the instance is built

// factory: function returns the instance
app.factory('A', function() { return { x: 1 }; });

// service: constructor is 'new'-ed
app.service('B', function() { this.x = 1; });

// provider: $get returns the instance (configurable)
app.provider('C', function() {
  this.$get = function() { return { x: 1 }; };
});

$provide.decorator()

decorator() は既存サービスのインスタンス化を横取りします — $delegate が元のインスタンスで、ラップ・拡張・置き換えが可能です。元のサービスに触れずに横断的関心事(ロギング、キャッシュ、エラー報告)を扱えます。デコレータは遅延実行で、サービスが最初に注入されたときにだけ動きます。

angularjs
app.decorator('$log', ['$delegate', function($delegate) {
  // $delegate is the original $log instance
  var origError = $delegate.error;
  $delegate.error = function(msg) {
    // e.g., send to error tracking, then call original
    trackError(msg);
    origError.apply($delegate, arguments);
  };
  return $delegate;   // return the (modified) service
}]);
11

ルーティング(ngRoute と ui-router)

ngRoute のセットアップ

ngRoute は組み込みルーターです(別ファイル angular-route.js)。.when(path, config) でルートを登録し、.otherwise() でフォールバックを設定します。ng-view がマッチしたテンプレート + コントローラを描画するアウトレットです。ngRoute は 1 つのアウトレットと単純な :param URL しかサポートしないため、ネストしたビューには ui-router を使いましょう。

angularjs
<!-- include angular-route.js (separate file in 1.x) -->
<script src="angular-route.js"></script>

var app = angular.module('myApp', ['ngRoute']);

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/home', { templateUrl: 'home.html', controller: 'HomeCtrl' })
    .when('/users/:id', { templateUrl: 'user.html', controller: 'UserCtrl' })
    .otherwise({ redirectTo: '/home' });
}]);

<!-- where the matched view renders -->
<div ng-view></div>

ngRoute のルートパラメータ

$routeParams は URL セグメント(:id)を文字列キーのオブジェクトとして公開します — 値は常に文字列なので、数値は parseInt で変換します。ルート変更後に更新されます。動的なリンクには ng-href を使います。デフォルトのハッシュバン接頭辞は #!(1.6 以降)で、$locationProvider.hashPrefix('') で設定できます。

angularjs
app.controller('UserCtrl', ['$routeParams', 'UserSvc',
  function($routeParams, UserSvc) {
    // URL /users/42  ->  $routeParams.id === '42' (always a string)
    this.user = UserSvc.get($routeParams.id);
  }]);

<!-- links -->
<a href="#!/users/42">View user 42</a>
<!-- with HTML5 mode, use a plain href="/users/42" -->

ngRoute のライフサイクルイベント

ngRoute は $routeChangeStart(event.preventDefault でキャンセル可能)、$routeChangeSuccess、$routeChangeError を broadcast します。'next'/'current' 引数はルート設定(resolve の結果を含む)を運びます。認証ガード、ローディング表示、パンくずリストのタイトルに使いましょう。resolve の拒否は $routeChangeError を発火させます。

angularjs
app.run(['$rootScope', function($rootScope) {
  $rootScope.$on('$routeChangeStart', function(event, next, current) {
    if (next.requireAuth && !AuthService.isLoggedIn()) {
      event.preventDefault();             // cancel navigation
    }
  });

  $rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
    $rootScope.pageTitle = current.$$route.title;
  });

  $rootScope.$on('$routeChangeError', function(event, current, previous, rejection) {
    console.error('route failed', rejection);
  });
}]);

ui-router のステート

ui-router はアプリを名前付きステート(URL パスではなく)で整理します。ui-sref はステート名とパラメータでリンクを作り、ui-view がアウトレットです。ステートはネストでき、独自の URL を持てます。これでナビゲーションが URL から切り離され、複数/名前付きビューもサポートされます — 実アプリでは ngRoute よりはるかに強力です。

angularjs
var app = angular.module('myApp', ['ui.router']);

app.config(['$stateProvider', function($stateProvider) {
  $stateProvider
    .state('home', { url: '/home', templateUrl: 'home.html' })
    .state('users', { url: '/users', templateUrl: 'users.html' })
    .state('users.detail', {
      url: '/:id',
      templateUrl: 'user-detail.html',
      controller: 'UserDetailCtrl'
    });
}]);

<!-- outlet -->
<div ui-view></div>
<!-- links: state name instead of URL -->
<a ui-sref="users.detail({ id: 42 })">User 42</a>

ui-router の resolve とネストしたステート

resolve はキーを promise にマッピングし、すべてが解決されるまでコントローラはインスタンス化されません。resolve が拒否すると $stateChangeError が発火し、そのステートには入りません。resolve の値はそのキーでコントローラへ注入できます。子ステートは親の resolve を継承してアクセスできるため、データの先読みに有用です。

angularjs
$stateProvider.state('users.detail', {
  url: '/:id',
  templateUrl: 'user-detail.html',
  controller: 'UserDetailCtrl',
  controllerAs: 'vm',
  resolve: {
    // injected into the controller; waits for these before activating
    user: ['UserSvc', '$stateParams', function(UserSvc, $stateParams) {
      return UserSvc.get($stateParams.id);   // returns a promise
    }]
  }
});

app.controller('UserDetailCtrl', ['user', function(user) {
  this.user = user;   // already resolved
}]);

ui-router の複数名前付きビュー

ui-router は 1 つのステートで複数の名前付き ui-view アウトレットを描画できます。views マップのキーはテンプレート内の ui-view 名に一致し、空文字列のキーが名前なしアウトレットをターゲットにします。これにより 1 つのステートで複数の領域(ヘッダー、サイドバー、メイン)を構成できます — ngRoute の単一 ng-view では不可能です。

angularjs
$stateProvider.state('dashboard', {
  url: '/dashboard',
  views: {
    '':        { templateUrl: 'dashboard/main.html' },
    'sidebar': { templateUrl: 'dashboard/sidebar.html', controller: 'SideCtrl' },
    'header':  { templateUrl: 'dashboard/header.html' }
  }
});

<!-- index.html -->
<div ui-view="header"></div>
<div ui-view="sidebar"></div>
<div ui-view></div>          <!-- the unnamed '' view -->
12

フォームとバリデーション

ng-model 付きのフォーム

フォームに name 属性を付けると、そのバリデーション状態がスコープ上に公開されます。novalidate はブラウザ組み込みの吹き出しを無効化し、Angular がバリデーションを制御します。名前付きの各入力は独自の状態を公開します(myForm.email.$valid、$dirty、$error)。バリデーションが入力を追跡するには ng-model が必要です。

angularjs
<form name="myForm" novalidate>
  <input name="email" type="email" ng-model="user.email" required>
  <input name="age" type="number" ng-model="user.age" min="18" required>

  <button ng-disabled="myForm.$invalid" ng-click="save()">Save</button>
</form>

<!-- novalidate disables the browser's native validation so Angular handles it -->

バリデーション状態

各入力は $pristine/$dirty(変更したか)、$touched/$untouched(フォーカスが外れたか)、$valid/$invalid、$error(失敗したバリデーターのマップ)を公開します。フォームはこれらを集約します:どれか 1 つでも入力が無効なら myForm.$invalid が true です。ユーザーが入力する前に叱らないよう、$touched か $dirty の後にだけメッセージを表示しましょう。

angularjs
<input name="email" ng-model="user.email" required>
<p ng-show="myForm.email.$touched && myForm.email.$error.required">
  Email is required.
</p>

<!-- states available on each input / the form -->
<!-- $pristine, $dirty, $touched, $untouched, $valid, $invalid, $error -->

組み込みバリデーター

組み込みバリデーター:required、type=email/url/number、min/max、ng-minlength/ng-maxlength、ng-pattern。失敗したバリデーターは $error にキーを設定します($error.required、$error.minlength、$error.pattern など)。HTML 属性内の ng-pattern の正規表現ではバックスラッシュをエスケープしてください。

angularjs
<input name="email" type="email" ng-model="user.email" required>
<input name="age" type="number" ng-model="user.age" min="18" max="120">
<input name="code" ng-model="user.code"
       ng-minlength="4" ng-maxlength="8" required>
<input name="url" type="url" ng-model="user.url">
<input name="zip" ng-model="user.zip" ng-pattern="/^\d{5}$/">

カスタムバリデーター(ディレクティブ)

ngModel を require し、ctrl.$validators に関数を登録するディレクティブでカスタムバリデーターを追加します。有効なら true、無効なら false を返すと、失敗が $error にあなたのキー(ここでは 'even')で現れます。非同期バリデーションには、promise を返す ctrl.$asyncValidators を使います。

angularjs
app.directive('evenNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, el, attrs, ctrl) {
      ctrl.$validators.even = function(modelValue, viewValue) {
        if (ctrl.$isEmpty(modelValue)) return true;   // let 'required' handle empty
        return parseInt(modelValue, 10) % 2 === 0;
      };
    }
  };
});

<input ng-model="n" even-number>
<p ng-show="form.n.$error.even">Must be even!</p>

ngMessages

ngMessages は最初に一致したエラーを表示します(ng-messages-multiple で全部も可能)。バリデーターごとに ng-if を積み重ねるよりはるかにきれいです。共通のメッセージは部分テンプレートへ切り出し、ng-messages-include='messages.html' で読み込みましょう。組み込みでもカスタムでもバリデーターのキーで動きます。

angularjs
<!-- include angular-messages.js, add module 'ngMessages' -->
<script src="angular-messages.js"></script>

<div ng-messages="myForm.email.$error" ng-if="myForm.email.$touched">
  <div ng-message="required">Email is required.</div>
  <div ng-message="email">Enter a valid email.</div>
  <div ng-message="server">That email is taken.</div>
</div>

<!-- a template can be reused across fields with ng-messages-include -->

フォーム送信

ng-submit はフォーム送信時(Enter キーや type='submit' ボタン)に発火し、上書きしない限り ng-model のバリデーションが通ったときだけです。ハンドラに安全確認として myForm.$valid を渡しましょう。novalidate により、ブラウザではなく Angular がバリデーションを主導します。二重送信防止には ng-disabled でボタンを無効化します。

angularjs
<form name="myForm" ng-submit="save(myForm.$valid)" novalidate>
  <input name="email" ng-model="user.email" required>
  <button type="submit" ng-disabled="myForm.$invalid">Save</button>
</form>

app.controller('FormCtrl', ['$scope', function($scope) {
  $scope.save = function(isValid) {
    if (!isValid) return;
    // ...submit to server
  };
}]);
13

イベント(ng-click、ng-change など)

ng-click

ng-click は要素がクリックされたときに式を評価します。$event はネイティブの DOM イベントなので stopPropagation/preventDefault を呼べます — ただし可能な限り、フォームには ng-submit、組み込みディレクティブを使いましょう。ng-click はボタンに限らず任意の要素で動きます。

angularjs
<button ng-click="count = count + 1">Inc</button>
<span>{{ count }}</span>

<!-- call a scope method -->
<button ng-click="save()">Save</button>

<!-- pass the native event with $event -->
<button ng-click="save($event)">Save</button>
<button ng-click="save($event); $event.stopPropagation()">Save</button>

ng-change

ng-change は ng-model がモデルを更新した後に発火します — つまり $scope.country はすでに新しい値です。同じ要素に ng-model が必要です。独自の change リスナーを組まずに、input/select/checkbox の変更へ反応できます(カスケードドロップダウン、ライブフィルタリングなど)。

angularjs
<select ng-model="country" ng-change="onCountryChange()">
  <option value="us">US</option>
  <option value="uk">UK</option>
</select>

app.controller('LocCtrl', ['$scope', function($scope) {
  $scope.onCountryChange = function() {
    // fires AFTER ng-model updates $scope.country
    $scope.cities = CityService.forCountry($scope.country);
  };
}]);

ng-submit と ng-focus/blur ファミリー

ng-submit はフォーム送信を処理します。Angular は多くの DOM イベントに対してイベントディレクティブも公開しています:ng-focus、ng-blur、ng-change、ng-copy、ng-cut、ng-paste、ng-keydown/up/press、ng-mousedown/up/enter/over/leave/move、ng-dblclick。それぞれ式を評価し、$event が使えます。

angularjs
<!-- ng-submit: on form submission -->
<form ng-submit="search()">
  <input ng-model="query">
</form>

<!-- the ng-focus / ng-blur / ng-copy / ng-cut / ng-paste directives -->
<input ng-model="q" ng-focus="onFocus()" ng-blur="onBlur()">
<input ng-copy="copied = true">

キーボードとマウスイベント

Angular は ng-keydown/ng-keypress/ng-keyup、ng-mousedown/up/enter/leave/over/move、ng-dblclick を提供します。それぞれ $event を渡すので、$event.keyCode や $event.shiftKey を調べられます。アプリ全体のショートカットは、テンプレートにハンドラを散らすのではなく、サービス内で $document や $window に束縛しましょう。

angularjs
<!-- keyboard events -->
<input ng-keydown="onKey($event)">
<input ng-keypress="onKey($event)">

<!-- mouse events -->
<div ng-mouseenter="hover = true" ng-mouseleave="hover = false">
  {{ hover ? 'Hovering' : 'Not hovering' }}
</div>
<button ng-dblclick="open()">Double-click</button>

$event オブジェクト

$event はハンドラに渡されるネイティブの DOM イベントです。target、座標、修飾キーを読み、preventDefault/stopPropagation を呼べます。クリックハンドラに重いロジックを置くのは避け、コントローラ/サービスのメソッドを呼びましょう。$event はすべてのイベントディレクティブで使えます。

angularjs
<button ng-click="onClick($event)">Click</button>

app.controller('ClickCtrl', ['$scope', function($scope) {
  $scope.onClick = function(event) {
    console.log(event.target);    // clicked element
    console.log(event.clientX, event.clientY);
    event.preventDefault();
    event.stopPropagation();
  };
}]);

イベント修飾子(手動)

Vue や Angular 2+ と違い、AngularJS には .stop/.prevent/.once 修飾子がなく、ハンドラ内で自分でイベントメソッドを呼びます。冗長ですが明示的です。頻出する動作(送信時の自動 preventDefault)は、ng-submit がフォームに対してすでに行ってくれます。

angularjs
<!-- AngularJS has NO built-in modifiers like .stop / .prevent.
     Call the method on $event instead. -->
<a href="/delete" ng-click="del($event)">Delete</a>

app.controller('DelCtrl', ['$scope', function($scope) {
  $scope.del = function(event) {
    event.preventDefault();   // stop the link navigation
    $scope.removeItem();
  };
}]);
14

$watch / $digest / $apply

$scope.$watch

$watch はダイジェスト中に監視対象の値が変わるたびに実行されるリスナーを登録します。第 1 引数は文字列式か関数で、コールバックは (newVal, oldVal) を受け取ります。$watch は登録解除用の関数を返すので、それを呼べば監視を停止できリークを防げます — 特にディレクティブ内で重要です。

angularjs
app.controller('WatchCtrl', ['$scope', function($scope) {
  $scope.user = { name: 'Ada' };

  // watch a path expression (string)
  var unbind = $scope.$watch('user.name', function(newVal, oldVal) {
    console.log('name changed', oldVal, '->', newVal);
  });

  // stop watching (frees resources)
  unbind();
}]);

$watchCollection

$watchCollection は配列やオブジェクトの 1 レベルを監視します:要素の追加/削除/置換で発火しますが、要素のプロパティを深くは比較しません。深い $watch(第 3 引数 true)よりはるかに安価です。プリミティブの配列や、リストの構成要素だけを気にする場合に使いましょう。

angularjs
$scope.items = [1, 2, 3];

// watch array/object shallowly: detects add/remove/replace but NOT deep mutation
$scope.$watchCollection('items', function(newItems, oldItems) {
  console.log('collection changed', newItems);
});

// fires on push/splice, or when an item is replaced,
// but NOT when an item's own properties change.

深い $watch(第 3 引数)

第 3 引数に true を渡すと $watch は深い値比較を行います — ネストしたプロパティが変わるたびに発火します。これは高コストです(毎ダイジェストでオブジェクト全体を走査)。特定のパスの監視や $watchCollection を推奨します。深い監視は本当に必要な小さなオブジェクトに限定しましょう。

angularjs
$scope.config = { ui: { theme: 'dark' } };

// third arg true -> deep comparison by value (expensive!)
$scope.$watch('config', function(n, o) {
  console.log('config (deep) changed');
}, true);

// prefer watching a specific path when possible:
$scope.$watch('config.ui.theme', function(n, o) { /* cheaper */ });

$scope.$apply

Angular の世界の外にあるコード(生の setTimeout、$http を使わない XHR、jQuery イベント、Promise コールバック)はモデルを更新しても Angular は知りません — $apply() を呼んで $digest を発火させましょう。関数形式なら変更を例外処理で包み、1 回のダイジェストを実行します。Angular のサービス内($http、$timeout)では $apply は既に実行済みです — 二重に apply しないでください。

angularjs
// NON-Angular async callback (e.g., a 3rd-party library) won't trigger a digest
externalLib.onReady(function() {
  $scope.message = 'Ready!';

  // tell Angular to run a digest so the view updates
  $scope.$apply();
});

// or wrap the change so errors are caught and digest runs once
$scope.$apply(function() {
  $scope.message = 'Ready!';
  $scope.ready = true;
});

$evalAsync と $timeout(安全な apply)

ダイジェストが既に進行中か分からない場合は、手動の $apply の代わりに $evalAsync か $timeout(fn, 0) を使いましょう — 「digest already in progress」エラーを避けられます。$evalAsync は現在のダイジェストにバッチされ、$timeout は次のティックへ先送りします。DOM が描画済みであることも必要なら $timeout を使います。

angularjs
// $evalAsync: schedule work later in the SAME digest if one is running,
//             otherwise start a new one. Safer than $apply.
$scope.$evalAsync(function() {
  $scope.computed = heavyCompute();
});

// $timeout(..., 0) always runs in a fresh digest — useful when you
// need the DOM updated before your code runs.
$timeout(function() {
  $scope.deferred = true;
}, 0);

$digest サイクルの仕組み

$digest はモデルの変更をビューへ伝播するループです:値が変わらなくなるまで(ダーティチェック)すべてのウォッチャーを再評価し、10 回で上限となります。すべてのウォッチャーが毎ダイジェスト実行されるため、パフォーマンスはウォッチャー数に比例します。1 回限りバインディング(::)、track by、計算のコントローラ側への移動でウォッチャーを減らしましょう。

angularjs
// a $digest iterates over ALL watchers on $scope and its children:
//   1. read each watched value, compare to previous
//   2. if changed, call the listener
//   3. listeners may change other watched values -> re-run
//   4. repeat until stable (max 10 iterations -> error)

// so: keep watchers cheap and few.
// track by, one-time binding (::), and compute in controllers help.
15

コンポーネント(.component())

.component() の基本

.component() はディレクティブの糖衣で、テンプレートベースのコンポーネントに最適化されています。デフォルトで restrict 'E'、分離スコープ、controllerAs '$ctrl' となるため、$scope の代わりに this(別名 $ctrl)を使います。bindings は scope:{...} を置き換え、入力には 1.5 以降 '=' より '<'(片方向の入力)が推奨です。

angularjs
app.component('heroDetail', {
  template: '<h2>{{$ctrl.hero.name}}</h2><p>{{$ctrl.hero.power}}</p>',
  bindings: {
    hero: '<'        // one-way ('<'), two-way ('='), string ('@'), expr ('&')
  }
});

<!-- usage -->
<hero-detail hero="selectedHero"></hero-detail>

コントローラとバインディングを持つコンポーネント

コンポーネントの controller は this(テンプレートでは $ctrl として参照)を使います。bindings は入力('<'、'=')と出力('&')を宣言します。入力には片方向の '<' が推奨です。出力は '&' で、引数オブジェクト付きで呼ぶと親の式のローカル変数になります:onChange({ value: ... })。

angularjs
app.component('counter', {
  bindings: {
    start: '<',
    onChange: '&'
  },
  template: `
    <button ng-click="$ctrl.dec()">-</button>
    <span>{{ $ctrl.count }}</span>
    <button ng-click="$ctrl.inc()">+</button>
  `,
  controller: function() {
    this.$onInit = function() { this.count = this.start || 0; };
    this.inc = function() { this.count++; this.onChange({ value: this.count }); };
    this.dec = function() { this.count--; this.onChange({ value: this.count }); };
  }
});

コンポーネントのライフサイクルフック

AngularJS 1.5+ のコンポーネントフックは Angular 2+ のライフサイクルを反映します:$onInit(初期化)、$onChanges(バインディングの変更、isFirstChange 付き)、$doCheck(各ダイジェスト)、$postLink(子 DOM のリンク後)、$onDestroy(後始末)。ロジックをコンストラクタに詰め込む代わりにこれらを使いましょう — コンポーネントの振る舞いが明示的になりテストしやすくなります。

angularjs
app.component('editor', {
  bindings: { doc: '<', onClose: '&' },
  controller: function() {
    this.$onInit = function() { /* after bindings, before first render */ };
    this.$onChanges = function(changes) {
      // changes.doc: { currentValue, previousValue, isFirstChange() }
    };
    this.$doCheck = function() { /* every digest: custom dirty checking */ };
    this.$onDestroy = function() { /* cleanup: timers, listeners */ };
    this.$postLink = function() { /* after child linking, DOM ready */ };
  }
});

$onChanges の詳細

$onChanges は片方向('<')バインディングの参照が変わるたびに発火し、changes オブジェクトを受け取ります:各キーには currentValue、previousValue、isFirstChange() があります。同じオブジェクトのミューテーションでは発火しません(参照が変わらないため)— それには $doCheck を使います。初期化時に isFirstChange() が true で必ず 1 回発火します。

angularjs
app.component('userView', {
  bindings: { user: '<' },
  controller: function() {
    this.$onChanges = function(changesObj) {
      // changesObj is keyed by binding name
      if (changesObj.user) {
        var c = changesObj.user;
        console.log(c.previousValue, '->', c.currentValue);
        console.log('first time?', c.isFirstChange());
      }
    };
  }
});

コンポーネントのトランスクルージョン

transclude: true を設定しテンプレートに ng-transclude を含めると、呼び出し側がコンテンツを注入できます。コンポーネントでは transclude: { slotName: 'elementName' } によるマルチスロットのトランスクルージョンもサポートされます。トランスクルージョンにより、本文を親が供給する再利用可能なラッパー(パネル、モーダル、カード)を作れます。

angularjs
app.component('modal', {
  transclude: true,
  template: `
    <div class="modal">
      <div class="modal-body" ng-transclude></div>
    </div>
  `,
  bindings: { title: '@' }
});

<!-- caller's content lands in ng-transclude -->
<modal title="Confirm">
  <p>Are you sure?</p>
  <button>Yes</button>
</modal>

コンポーネントとディレクティブの使い分け

テンプレートを描画するものはすべてコンポーネントにしましょう — より単純で、Angular 2+ のモデル(分離スコープ、this/controllerAs、ライフサイクルフック)へ近づきます。ディレクティブはテンプレートを持たない属性スタイルの振る舞い(オートフォーカス、ツールチップのトリガー、入力マスク)と、link での直接 DOM 操作のために取っておきましょう。

angularjs
// COMPONENT: template-based, isolate scope, controllerAs by default
app.component('userCard', {
  template: '...',
  bindings: { user: '<' }
});

// DIRECTIVE: still needed for attribute behavior / DOM manipulation
app.directive('autoFocus', function() {
  return { restrict: 'A', link: function(scope, el) { el[0].focus(); } };
});
16

$q Promise サービス

$q.defer() の基本

$q は Angular の Promise 実装(Promises/A+)です。$q.defer() で作成し、resolve(value) か reject(reason) します。promise はダイジェスト対応で、解決時に $digest が発火してビューが更新されます。Angular の自動ダイジェストが必要ならネイティブ Promise より $q を推奨します。それ以外はネイティブ Promise でも構いません。

angularjs
app.factory('AsyncWork', ['$q', function($q) {
  return function() {
    var deferred = $q.defer();

    setTimeout(function() {
      if (success) deferred.resolve('done');
      else         deferred.reject(new Error('failed'));
    }, 100);

    return deferred.promise;     // { then, catch, finally }
  };
}]);

// consume
AsyncWork().then(function(v) { console.log(v); })
          .catch(function(e) { console.error(e); });

$q.when / $q.all / $q.reject

$q.when はプレーンな値や非 $q の promise をラップします。$q.all は promise の配列やオブジェクトの完了を待ち、同じ形状の結果で解決します。$q.reject(reason) は拒否された promise を返す便利な方法です(チェーン内の早期バリデーションなど)。すべてダイジェスト対応です。

angularjs
// $q.when: wrap a value (or foreign promise) in an Angular promise
$q.when(42).then(function(v) { /* v === 42 */ });

// $q.all: wait for many promises in parallel
$q.all([getUser(), getPosts(), getFriends()]).then(function(results) {
  var user = results[0], posts = results[1], friends = results[2];
});

// $q.all with an object (named results)
$q.all({ user: getUser(), posts: getPosts() }).then(function(r) {
  r.user; r.posts;
});

// $q.reject: shortcut to return a rejected promise
return $q.reject(new Error('bad input'));

Promise のチェーン

.then から値を返すと次のハンドラに渡り、promise を返すとチェーンは待ちます。1 つの .catch が上流のどの拒否でも処理します。.finally は成功でも失敗でも実行されるので、ローダーの非表示に最適です。各ハンドラは Angular のダイジェスト内で実行されるため、スコープの更新はそのまま動きます。

angularjs
getUser(id)
  .then(function(user) {
    return getOrders(user);    // return a promise -> chain waits
  })
  .then(function(orders) {
    return orders.filter(paid); // return a value -> next step
  })
  .then(function(paidOrders) {
    $scope.paid = paidOrders;
  })
  .catch(function(err) {
    // any rejection above lands here
    console.error(err);
  })
  .finally(function() {
    $scope.loading = false;    // runs regardless
  });

$http は Promise を返す

$http は既に $q promise を返すので、.then でレスポンスを変換し(多くは .data の取り出し)、よりきれいな値を返しましょう。$http をサービスに包むと、呼び出し側に整った API を与え、URL/ベース URL/エラー処理を一元化できます。インターセプターは横断的な $http の振る舞いを適用するもう 1 つの方法です。

angularjs
app.factory('UserApi', ['$http', function($http) {
  return {
    list: function() { return $http.get('/users').then(function(r) { return r.data; }); },
    get:  function(id) { return $http.get('/users/' + id).then(function(r) { return r.data; }); }
  };
}]);

// caller doesn't deal with response.data, just the user
UserApi.get(42).then(function(user) { $scope.user = user; });

$q コンストラクタ(ES6 スタイル)

1.6 以降、$q は ES6 の Promise コンストラクタ形式をサポートします:$q(function(resolve, reject){...})。$q.defer() より簡潔で、ネイティブ Promise の構文と一致します。単一の非同期 API をラップするときに使いましょう。得られる promise は依然ダイジェスト対応なので、解決時にビュー更新が自動で発火します。

angularjs
// Angular 1.6+ supports the resolver-style constructor, like native Promise
app.factory('loadImg', ['$q', function($q) {
  return function(src) {
    return $q(function(resolve, reject) {
      var img = new Image();
      img.onload  = function() { resolve(img); };
      img.onerror = function() { reject(new Error('load failed')); };
      img.src = src;
    });
  };
}]);

$q とネイティブ Promise

重要な違い:$q は解決時に $digest を発火しますが、ネイティブ Promise はしません。モダンブラウザで動く現代の AngularJS アプリではネイティブ Promise も使えますが、モデルの更新を $apply(または $evalAsync)で包む必要があります。一貫性と利便性のため、Angular のコード内では $q を推奨します。

angularjs
// native Promise: no auto-digest; you must $apply manually
Promise.resolve().then(function() {
  $scope.x = 1;
  $scope.$apply();           // otherwise the view won't update
});

// $q promise: resolves inside a $digest automatically
$q.when().then(function() { $scope.x = 1; });   // view updates
17

アニメーション(ngAnimate)

ngAnimate のセットアップ

ngAnimate は別モジュールです(専用の JS ファイル)。依存関係に追加すると、組み込みディレクティブが enter/leave/move の遷移中に CSS クラスを付けるよう自動的に拡張されます — あとは CSS を書くだけです。よくあるケースでは JS は不要です。ngAnimate がないとこれらのディレクティブは DOM を即時に変更します。

angularjs
<!-- include angular-animate.js, then depend on 'ngAnimate' -->
<script src="angular-animate.js"></script>

var app = angular.module('myApp', ['ngAnimate']);

<!-- ngAnimate now adds classes automatically to:
     ng-repeat (enter/leave/move), ng-if, ng-show, ng-hide,
     ng-class, ng-view, ng-include, ui-view -->

CSS トランジションのクラス

ngAnimate はイベントごとに 2 つのクラスを付けます:開始クラス(例:.ng-enter)と、1 フレーム後に付く -active クラス(.ng-enter-active)。開始クラスに CSS トランジションを、active クラスに終了状態を定義すると、Angular はトランジション終了時に両方を取り除きます。最も単純で高性能なアニメーションのアプローチです。

angularjs
/* .ng-enter / .ng-leave / .ng-move are added automatically */
.fade.ng-enter        { transition: opacity 0.3s; opacity: 0; }
.fade.ng-enter-active { opacity: 1; }

.fade.ng-leave        { transition: opacity 0.3s; opacity: 1; }
.fade.ng-leave-active { opacity: 0; }

<!-- apply the .fade class to your ng-if / ng-repeat element -->
<div class="fade" ng-if="show">Hello</div>

CSS キーフレームアニメーション

トランジションの代わりに CSS の @keyframes アニメーションも使えます — ngAnimate は同じ .ng-enter/.ng-leave/.ng-move クラスをトグルし、キーフレームが再生されます。キーフレームではアニメーションが全シーケンスを駆動するため、開始クラス 1 つだけでよく(-active は不要)バウンス/スプリング効果に向いています。

angularjs
/* use @keyframes; ngAnimate still toggles the classes */
.pop.ng-enter { animation: pop-in 0.3s; }

@keyframes pop-in {
  0%   { transform: scale(0); }
  100% { transform: scale(1); }
}

<div class="pop" ng-if="visible">Pop!</div>

ng-repeat の enter / leave / move

ng-repeat のアイテムには .ng-enter(新規)、.ng-leave(削除)、.ng-move(並べ替え)のクラスが付きます。track by を使うと Angular が変更をまたいでアイテムを照合でき、move が正しくアニメーションします。.ng-enter-stagger / .ng-leave-stagger で各アイテムに遅延を持たせるスタッガーアニメーションも可能です — リストの順次表示エフェクトに最適です。

angularjs
/* list items animate when added, removed, or reordered */
.list-item.ng-enter        { transition: all 0.3s; opacity: 0; transform: translateY(-10px); }
.list-item.ng-enter-active { opacity: 1; transform: translateY(0); }

.list-item.ng-leave-active { opacity: 0; transform: translateX(20px); }

/* .ng-move animates reordering (track by recommended) */
.list-item.ng-move        { transition: transform 0.3s; }
.list-item.ng-move-active { }

<ul><li class="list-item" ng-repeat="t in todos track by t.id">{{ t.text }}</li></ul>

$animate サービス(JS アニメーション)

app.animation(cssSelector, factory) でセレクタに一致する要素への JS アニメーションを登録します。enter/leave/move/class メソッドは要素と done コールバックを受け取ります。CSS だけでは足りないとき(jQuery.animate や物理演算ライブラリなど)に有用です。後始末用に cancel 関数を返せます。JS アニメーションは CSS より重いため、可能な限り CSS を推奨します。

angularjs
app.animation('.fade-js', ['$animate', function($animate) {
  return {
    enter: function(element, done) {
      element.css('opacity', 0);
      element.animate({ opacity: 1 }, 300, done);
      return function(cancelled) { /* cleanup if cancelled */ };
    },
    leave: function(element, done) {
      element.animate({ opacity: 0 }, 300, done);
    }
  };
}]);

<div class="fade-js" ng-if="show">Hello</div>

アニメーションの無効化

$animate.enabled でグローバルまたはサブツリー単位でアニメーションをオフにできるほか、ng-animate-disabled クラスでも無効化できます。大きなリストのパフォーマンス対策や、テスト中にアニメーションを止めるのに有用です。ng-animate-children を使うと親が子たちも一緒にアニメーションさせるよう選択できます(デフォルトでは親のアニメーションは子のアニメーションをスキップします)。

angularjs
<!-- ng-animate-ref / ng-animate-sref control animation between routes -->

<!-- opt out per-element -->
<div ng-if="x" ng-animate-children>...</div>
<div ng-if="y" class="ng-animate-disabled">...</div>

// programmatically
$animate.enabled(false);                    // globally off
$animate.enabled(false, element);           // off for subtree
$animate.enabled(true, element);            // back on
18

テスト(Karma と Jasmine)

Karma 設定の概要

Karma は AngularJS の標準テストランナーです:実ブラウザを起動し、スクリプトと angular-mocks を読み込み、Jasmine の結果を報告します。angular-mocks は module() と inject() のヘルパー、モックサービス($httpBackend)を提供します。singleRun:true で 1 回実行して終了(CI 用)、省略するとウォッチモードです。

angularjs
// karma.conf.js (sketch)
module.exports = function(config) {
  config.set({
    frameworks: ['jasmine'],
    files: [
      'node_modules/angular/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'src/**/*.js',
      'test/**/*.spec.js'
    ],
    browsers: ['ChromeHeadless'],
    singleRun: true
  });
};

// run: karma start karma.conf.js

Jasmine の基本

Jasmine は describe(スイート)、it(スペック)、beforeEach/afterEach(セットアップ/ティアダウン)、マッチャー付きの expect(toBe、toEqual、toContain、toBeTruthy、toThrow など)を提供します。xit/xdescribe でスペックをスキップします。テストはデフォルトで同期です。非同期には done コールバックか Jasmine の async/await サポートを使います。

angularjs
describe('UserService', function() {
  beforeEach(function() { /* setup */ });
  afterEach(function() { /* teardown */ });

  it('isLoggedIn is false by default', function() {
    var svc = makeService();
    expect(svc.isLoggedIn()).toBe(false);
  });

  it('greets by name', function() {
    expect(greet('Ada')).toEqual('Hi, Ada');
  });

  // pending / disabled
  xit('not yet implemented', function() {});
});

コントローラのテスト

module('myApp') が Angular モジュールを読み込み、inject() がサービスを解決します(前後にアンダースコアを付けた別名がよく使われます)。$controller('Name', { $scope: scope }) でフェイクの依存関係を渡してコントローラを作り、スコープに対して検証します。このパターンは controllerAs でも動きます:this に束縛されたメソッドを呼び、返されたインスタンスを検証します。

angularjs
describe('TodoCtrl', function() {
  beforeEach(module('myApp'));

  var $controller, $scope;
  beforeEach(inject(function(_$controller_, _$rootScope_) {
    $scope = _$rootScope_.$new();
    $controller = _$controller_;
  }));

  it('starts with two todos', function() {
    $controller('TodoCtrl', { $scope: $scope });
    expect($scope.todos.length).toBe(2);
  });

  it('addTodo pushes and clears the input', function() {
    $controller('TodoCtrl', { $scope: $scope });
    $scope.todoText = 'New';
    $scope.addTodo();
    expect($scope.todos.length).toBe(3);
    expect($scope.todoText).toBe('');
  });
});

サービスのテスト

テスト対象のサービスと、angular-mocks から $httpBackend を注入します。expectGET(url).respond(data) でフェイクのレスポンスを用意し、flush() で保留中のリクエストを同期的に解決します。afterEach の verifyNoOutstandingExpectation() が未達の期待を検出します。これで $http を使うサービスを実サーバーなしで完全にテストできます。

angularjs
describe('UserService', function() {
  var UserService, $httpBackend;

  beforeEach(module('myApp'));
  beforeEach(inject(function(_UserService_, _$httpBackend_) {
    UserService = _UserService_;
    $httpBackend = _$httpBackend_;
  }));

  afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); });

  it('list() fetches users', function() {
    $httpBackend.expectGET('/api/users').respond([{ name: 'Ada' }]);
    var users;
    UserService.list().then(function(u) { users = u; });
    $httpBackend.flush();          // resolve the pending request
    expect(users.length).toBe(1);
  });
});

ディレクティブのテスト

$compile(html)(scope) で HTML の断片をコンパイルし、scope.$digest() を実行してバインディングを評価しディレクティブをリンクします。結果の jqLite 要素を検証します(el.find、el.text、el.attr)。templateUrl の場合は $httpBackend.expectGET でテンプレートを提供し、digest の前に flush します。分離スコープは el.isolateScope() でテストします。

angularjs
describe('greeting directive', function() {
  var $compile, $rootScope;
  beforeEach(module('myApp'));
  beforeEach(inject(function(_$compile_, _$rootScope_) {
    $compile = _$compile_; $rootScope = _$rootScope_;
  }));

  it('renders the template', function() {
    var scope = $rootScope.$new();
    scope.name = 'Ada';
    var el = $compile('<greeting name="name"></greeting>')(scope);
    scope.$digest();              // process watchers / bindings
    expect(el.find('h1').text()).toContain('Ada');
  });
});

$httpBackend のモック

expectGET(および expectPOST など)はリクエストが行われることを検証し、行われないと失敗します。whenGET は呼ばれれば静かにデータを返し、呼ばれなくても問題ありません。「これは起こるはず」という検証には expect、セットアップには when を使いましょう。flush() が保留中のリクエストを順に解決します。不一致を検出するため、afterEach で必ず verifyNoOutstanding* を呼びましょう。

angularjs
// EXPECT: a specific request must happen (asserts it was made)
$httpBackend.expectGET('/api/users').respond(200, [{ id: 1 }]);
// WHEN:  just stub a request if it happens (no assertion)
$httpBackend.whenGET('/api/users').respond(200, [{ id: 1 }]);

// flush triggers all pending requests:
$httpBackend.flush();

// verify nothing was left unflushed:
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
19

依存性注入

DI の基本

Angular の DI は関数の引数名を検査して依存関係を解決します。この「暗黙的」スタイルは簡潔ですが、minify で壊れます(引数名が短縮される)。プロトタイプやデモなら問題ありません。本番ではインライン配列や $inject のいずれかのアノテーションスタイルを使うか、ng-annotate で自動化しましょう。

angularjs
// services are injected by NAME into the constructor's parameters
app.controller('A', function($scope, $http, UserService) { /* ... */ });

// Angular inspects the parameter names to resolve dependencies.
// works in development but BREAKS after minification (see below).

インライン配列アノテーション

最も一般的な minify セーフなスタイルです:サービス名(文字列)を要素とする配列を渡し、最後にコンストラクタを置きます。文字列は minify を生き延びるため、Angular は正しく解決できます。minify されるコードには必ずこのスタイルを使いましょう。手作業での維持は面倒ですが、ng-annotate や babel プラグインで自動追加できます。

angularjs
app.controller('A', ['$scope', '$http', 'UserService',
  function($scope, $http, UserService) {
    // parameter names no longer matter; the strings drive DI
    $scope.users = UserService.list();
  }
]);

$inject プロパティアノテーション

コンストラクタ関数にサービス名の文字列配列 $inject を付けます。Angular はそれを読んで依存関係を解決し、引数名は無視されます。関数宣言が読みやすく、同じコンストラクタを再利用できます。ng-annotate はビルド時に引数名から $inject を自動生成できます。

angularjs
function ACtrl($scope, UserService) {
  $scope.users = UserService.list();
}
ACtrl.$inject = ['$scope', 'UserService'];   // explicit list

app.controller('A', ACtrl);

// equivalent to the inline array form; useful when you want
// a separately-declared, reusable constructor function.

$injector サービス

$injector は DI コンテナです:.get(name) はシングルトンを返し、.annotate(fn) は依存リストを返し、.instantiate/.invoke は依存関係付きで関数を構築/呼び出します。アプリコードで必要になることはまれですが、動的シナリオ(名前でサービスをロードする)やカスタムディレクティブ・ルーターの resolve 内で有用です。

angularjs
// resolve and instantiate on demand
var svc = $injector.get('UserService');          // retrieve singleton
var fn  = $injector.annotate(MyCtrl);            // [' $scope', ...] via reflection
var inst = $injector.instantiate(MyCtrl);        // 'new' with DI
var res  = $injector.invoke(MyCtrl, context);    // call with DI

// list all registered service names (debug)
// $injector has modules / providers info

ng-annotate(ビルド時)

ng-annotate はビルド時ツールで、インライン配列アノテーションを自動追加します。きれいな暗黙 DI を書きながら、minify セーフなコードを ship できます。曖昧なケースには /* @ngInject */ を使います。gulp、grunt、webpack、babel と統合できます。後継の ng-annotate-patched がモダンなツールチェーンのサポートを維持しています。

angularjs
// Write clean code with a hint comment:
app.controller('A', /* @ngInject */ function($scope, UserService) {
  $scope.users = UserService.list();
});

// ng-annotate (run by your build tool) rewrites it to:
app.controller('A', ['$scope', 'UserService', function($scope, UserService) {
  $scope.users = UserService.list();
}]);

Strict DI モード

ng-strict-di を付けると、暗黙的(アノテーションなし)な依存性注入が実行時に例外を投げます。本番での障害ではなく開発中に minify に安全でないコードを発見できます。開発とテストでは有効のままにしましょう。わずかにパフォーマンスへ影響するため(追加チェック)、本番ビルドでは通常外します。

angularjs
<html ng-app="myApp" ng-strict-di>
  ...
</html>

// or when bootstrapping manually:
angular.bootstrap(root, ['myApp'], { strictDi: true });

// in strict-DI mode, any service using IMPLICIT (unannotated) DI
// throws an error, catching minification bugs during development.
20

ベストプラクティスとパフォーマンス

controllerAs を使う

controllerAs は各プロパティがどのコントローラに属するかを明確にし、スコープ継承によるプリミティブの覆い隠しを避け、Angular 2+ の「コンポーネント」モデルに近づきます。$scope ではなく this(別名付き)に束縛しましょう。コンポーネントでは $ctrl がデフォルトの別名です — 一貫して使いましょう。

angularjs
<!-- prefer controllerAs over $scope -->
<div ng-controller="UsersCtrl as users">
  <li ng-repeat="u in users.list">{{ u.name }}</li>
</div>

app.controller('UsersCtrl', function(UserService) {
  // 'this' is exposed as 'users' in the template
  this.list = UserService.list();
  this.remove = function(id) { UserService.remove(id); };
});

1 回限りのバインディング(::)

式に :: を接頭辞として付けると 1 回限りのバインディングになります:Angular は 1 回評価し、定義されたらウォッチャーを削除します。変わらないデータ(タイトル、タイムスタンプ、静的なリスト)にはこれでウォッチャー数が大幅に削減されます — AngularJS アプリで最大のパフォーマンス向上です。

angularjs
<!-- static data: bind once, drop the watcher -->
<h1>{{ ::conference.name }}</h1>
<span>{{ ::user.createdAt | date }}</span>

<!-- ng-repeat over a static list -->
<li ng-repeat="item in ::staticItems">{{ item.label }}</li>

<!-- less watchers = faster digest for the whole app -->

ng-repeat の track by

track by がないと Angular は内部の $$hashKey でアイテムを照合します — 配列が変わると実際には変わっていないアイテムの DOM を再描画・再作成し、子の状態を失うことがあります。track by u.id は安定した識別子を与え、Angular がノードを再利用します。大きなリストのパフォーマンスに不可欠で、「ng-repeat の重複」エラーも解消します。

angularjs
<!-- BAD: Angular uses $$hashKey, re-renders everything on change -->
<li ng-repeat="u in users">{{ u.name }}</li>

<!-- GOOD: stable identity -> Angular reuses DOM nodes -->
<li ng-repeat="u in users track by u.id">{{ u.name }}</li>

<!-- for primitives, use $index (only if list doesn't reorder) -->
<li ng-repeat="n in nums track by $index">{{ n }}</li>

ロジックをサービスへ移す

コントローラはテストが難しく $scope に結合しますが、サービスはシングルトンで、注入可能で、ユニットテスト可能です。ビジネスロジック、データアクセス、共有状態をサービスへ押し込み、コントローラはビューとサービスを結線することに専念させましょう。この分離により複数のコントローラが同じロジックを共有できます。

angularjs
// BAD: logic crammed in the controller
app.controller('BadCtrl', function($scope) {
  $scope.calc = function() { /* 50 lines of business logic */ };
});

// GOOD: controller delegates to a testable service
app.controller('GoodCtrl', function(PriceService) {
  this.total = PriceService.calcTotal(this.items);   // thin
});

app.factory('PriceService', function() {
  return { calcTotal: function(items) { /* ... */ } };
});

Bind Once / ウォッチャーの削減

すべての {{ }} とほとんどのバインディングは、毎ダイジェスト実行されるウォッチャーを追加します。バインディング内での関数呼び出しは避けましょう(入力が変わらなくても毎ダイジェスト再実行される)— 事前計算して結果を保存します。1 回限りバインディング(::)、track by、コントローラ側の計算を組み合わせ、大きなページでもウォッチャー数を低く保ちましょう。

angularjs
<!-- compute once in the controller, render many times -->
app.controller('Ctrl', function() {
  this.sortedUsers = this.users.slice().sort(byName); // do it once
});

<!-- avoid function calls in bindings: they re-run each digest -->
<!-- BAD:  {{ heavyCompute() }} -->
<!-- GOOD: compute once, bind the result -->
<p>{{ cachedResult }}</p>

モジュールの整理

ファイル種別ではなく機能で整理しましょう。各機能がコントローラ、サービス、テンプレート、ルート、テストを持つ自己完結したモジュールになり、ルートのアプリモジュールは機能モジュールを構成するだけです。関連コードがまとまり、機能はアプリをまたいで再利用でき、1 つの巨大なモジュールよりはるかにスケールします。

angularjs
// split features into sub-modules, each self-contained
angular.module('myApp.users', ['myApp.common']);
angular.module('myApp.posts', ['myApp.common']);
angular.module('myApp', ['myApp.users', 'myApp.posts', 'ngRoute']);

// file layout per feature:
//   users/users.module.js
//   users/users.controller.js
//   users/users.service.js
//   users/users.html
//   users/users.routes.js
//   users/users.spec.js

Was this helpful?