LoginSignup
43
44

More than 5 years have passed since last update.

AngularJS の custom directive まとめ

Last updated at Posted at 2014-06-24

directiveとは

  • htmlには無い振る舞いを持つ要素を埋め込むことが出来る
    • 例: ng-repeat, ng-model, ng-if などなど
  • 特にDOMを操作したい時に便利
  • コードを部品ごとに分割できる

custom directive

  • 自分が定義した振る舞いを持つ要素を埋め込むことが出来る
    • たとえばドラッグできる要素を作ったりとか

custom directiveを作ってみる

単純な custom directive

したい処理を以下の形で書いていく。

myModule.directive('sayhogeDirective', function() {
  return function(scope, element, attrs, controller) {
    // メイン処理
    var c = parseInt(attrs["sayhoge-directive"], 10);
    while(c--) {
      console.log("hoge");
    }
  };
});
<button sayhoge-directive="10">test</button>

※ 補足 module

  • パーツの依存関係読み込み
  • 起動時の初期化処理

を書くための仕組み

こうに書くことも出来る

link メソッドをreturnしても、上の記述と同様の意味になる。

myModule.directive('directiveName', function() {
  return {
    link: function(scope, element, attrs, controller) {
      // メイン処理
    }
  };
});

directive にはlink等のプロパティ(やメソッド)を指定できる。
以下にそれらを紹介する。

custom directive に指定できるプロパティ

restrict

directiveを、どんな形でhtmlに埋め込むか指定する。
デフォルトは属性名。

  • E: 要素 <directive-name title=Products></directive-name>
  • C: クラス <div class=directive-name></div>
  • M: コメント < !— directive: directive-name Products —>
  • A: 属性 <div directive-name=Products></div>

(※ Eは、ブラウザによってはエラーになるので注意)
複数指定可能らしい。EAとか。

link

  • function(){}を与えて、メイン処理を記述する
  • 受け取れる引数はfunction(scope, element, attrs, controller){}

compile

  • function(){}を与えて、メイン処理を記述する
  • linkとの違い
    • scope生成前に実行される
    • 実行回数がng-repeat内でも一度だけ
    • つまり、無駄を省くために使うっぽい

scope

  • directiveが使うscopeの設定
  • scope: false derectiveがある場所のscopeを使う
  • scope: true directiveがある場所のscopeを継承して作られた、新しいscopeを使う
  • scope: {...} 独自のscopeを使う
"3.独自のscope" の記法

以下の3種類ある。

scope: {
  name: '@', // interpolate(値、string)
  info: '=', // data bind
  cancel: '&' // expression(function)
}
  • @(attr) 属性値を文字列として渡す。{{...}}を使うと、データバインディングする
  • =(attr) このプロパティとディレクティブにとっての親の$scopeとの間でデータバインディングを行う
    • =?(attr) もし親プロパティにattrが存在しなくても、エラーにならない。
  • &(attr) 関数を親の$scopeから渡す

(attr)の部分に文字列を書くと、directiveを使用する側ではscopeのプロパティ名としてその文字列が使える。

require

directiveが必要とするコントローラーを指定する
directiveName: 普通。
^directiveName: 祖先の要素も検索
?directiveName: このコントローラがなくても例外が発生しない

参考

scope関連

43
44
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
43
44