カスタムディレクティブのrestrictの使い分け
ぼんやりしていたカスタムディレクティブのrestrictの違いがようやく分かったのでメモ。
普通の人にはあまりに自明なことなのかもしれませんが・・・。
あーだこーだ書くよりサンプルを見た方が速いかと思うので、
まずはサンプルコード。
■index.html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>AngularJS samples</title> <script src="js/angular.min.js"></script> <script src="js/custom-directive.js"></script> </head> <body ng-app="myApp"> <div ng-controller="Controller"> <!-- Restrict A --> <div my-directive-a></div> <!-- Restrict E --> <my-directive-e></my-directive-e> <!-- Restrict C --> <div class="my-directive-c"></div> </div> </body> </html>
■custom-directive.js
var app = angular.module('myApp', []) .controller('Controller', ['$scope', function($scope){ console.log("AAA"); $scope.message = 'Test message from controller'; }]) .directive('myDirectiveA', function(){ return { templateUrl: 'my-directive-a.html' }; }) .directive('myDirectiveE', function(){ return { restrict: 'E', templateUrl: 'my-directive-e.html' }; }) .directive('myDirectiveC', function(){ return { restrict: 'C', templateUrl: 'my-directive-c.html' }; });
■my-directive-a.html
Message from custom directive A: {{message}}<br>
■my-directive-e.html
Message from custom directive E: {{message}}<br>
■my-directive-c.html
Message from custom directive C: {{message}}<br>
上記を実行すると、
Message from custom directive A: Test message from controller Message from custom directive E: Test message from controller Message from custom directive C: Test message from controller
・・・と表示される。
結局、restrictの違いは、どうやってHTMLから指定するか、
ということだけらしい。
CSSでclassを指定しながらカスタムディレクティブを表示したりするときに
Cを使ったりするんだろうなー、と想像中。