2014年11月13日木曜日

AngularJsを使ってみる―独自のDirectiveを作る―

今回は独自のDirectiveを作成します。

前提:
表示する大本のページを"index.html"、読み込むAngularソースを"sampleAngular-app.js"であるとします。また、"sampleAngular-app.js"が適用されるソースは"sample.html"です。

①AngularJsの記法で書かれた、sample.htmlファイルを用意します。
このソースを、index.htmlに埋め込む形になります。

②sampleAngular-app.jsに、次のようなDirectiveを作成します。

app.directive("sampleDirective", function() {
    return {
      restrict: 'E', //E is Element, A is attribute.
      templateUrl: "sample.html"
    };
});

③作成したDirectiveを、index.htmlに埋め込みます。埋め込み方は、restrictの設定値によって微妙に変わります。

A(attribute)の場合:

<sample-directive></sample-directive>

E(element)の場合:

<div sample-directive>

また、次のように書くことで、sample.htmlをコントローラで囲っている状態が得られます。

app.directive("sampleDirective", function() {
    return {
      restrict: 'E', //E is Element, A is attribute.
      templateUrl: "sample.html",
      controller: function(){
            //parameters and functions are here.
      },
      controllerAs: sample //You can also put alias
    };
});

0 件のコメント:

コメントを投稿