Motomichi Works Blog

モトミチワークスブログです。その日学習したことについて書いている日記みたいなものです。

AngularJS1.x その0011 タグを自作する(Custom Elementsを作成する) templateとng-transclude

参考にさせて頂いたページ

Angular.jsについて

AngularJSカスタムディレクティブのtranscludeオプション、ng-transcludeディレクティブの使用例 | VPSサーバーでWebサイト公開 備忘録 ~Linux、MySQLからAJAXまで

AngularJS Directive なんてこわくない(その1) - AngularJS Ninja Blog

angularjs - Angular directive replace=true - Stack Overflow

AngularJS 入門 - Directive - Qiita

CustomElementsについて

Custom Elements: HTML に新しい要素を定義する - HTML5 Rocks

ng-app.jsの記述内容

例として以下の通り。

// myAppモジュールを作成
var app = angular.module('myApp', []);

// myAppモジュールにSubmitCtrlコントローラーを登録
app.controller('SubmitCtrl', function($scope, $element) {
  $scope.onclick = function($event){
    // ページ遷移をキャンセル
    $event.preventDefault();
    // input要素をクリック $element[0]はSubmitCtrlの要素自身
    $element[0].nextElementSibling.click();
  }
}).directive('modFormFrame0001Outer', function ($parse) {
  return{
    restrict: 'E',
    replace: true,
    transclude: true,
    template: '<div class="outer"><span></span></div>',
  };
});

index.htmlの記述内容

例として以下の通り。

<mod-form-frame-0001-outer ng-transclude>
  内側のコンテント
</mod-form-frame-0001-outer>

このソースコードについて

例としたng-app.jsのソースコードのうち今回必要な部分は

.directive('modFormFrame0001Outer', function ($parse) {
  return{
    restrict: 'E',
    replace: true,
    transclude: true,
    template: '<div class="outer"><span class="inner"></span></div>',
  };
});

の部分。

これは、

.directive('タグ名をローワーキャメルケースで', function ($parse) {
  return{
    restrict: 'E', //このdirecitveはエレメントとして使用する
    replace: true, //htmlに記述した自作の要素をtemplateと置き換える
    transclude: true,//自作の要素の内側にコンテンツを入れられるようにする
    template: '<div class="outer"><span></span></div>',//自作の要素と置き換える文書構造
  };
});

ということらしい。

html側ではハイフン区切りで要素名を記述して、ng-transclude属性を付与すると自作の要素の内側にコンテンツが入れられる。

Custom Elements と Component System について

Custom Elementsについては以下のページを参考にさせて頂きました。

Custom Elements: HTML に新しい要素を定義する - HTML5 Rocks

var XFoo = document.registerElement('x-foo');
document.body.appendChild(new XFoo());

といったようなスクリプトで、documentに対して自作の要素を追加できるのですが、要素名にはハイフンを含める必要があります。

Angular.jsを使用することによって、Custom Elementsをサポートしていないブラウザに対しても、自作の要素でマークアップをすることが可能になります。