【AngularJS】directiveで読み込むtemplateを動的に切り替える
最近、AngularJSをプロジェクトで触る機会が多くなってきました (AngularJSといってもバージョン1)
慣れると便利なAngularJSですが、普段jQueryとかやってると根本的な考え方から変えないと行けないので中々大変ですね…w
AngularJSではdirectiveという仕組みがあり、そこでhtmlをtemplateとして読み込む事が出来ますが、
今回は同じdirectiveで複数のtemplateを使い分けるやり方を解説していきたいと思います。
なお、そもそもAngularJSって?directiveってなに?みたいな所は今回割愛します。
やりたいこと
angularのdirective内で、条件によって動的に使用するtemplateを切り替える。
方法
directiveのtemplateUrlにfunctionを使用して、HTML側のタグのパラメータを渡して判断させる。
サンプル
シンプルなテンプレートの呼び出し
1 2 3 4 5 6 |
var myModlue = angular.module('myModlue', []); myModule.directive('templateDirective', function(){ return { restrict : 'AE', templateUrl: 'template.html' }); |
1 2 3 |
<div> <p>テンプレートになるHTMLです</p> </div> |
1 2 3 4 5 6 7 8 9 10 11 |
<html ng-app="myModule"> <head> <script type="text/javascript" src="angular.min.js"></script> <script type="text/javascript" src="myModule.js"></script> </head> <body> <div template-directive></div> </body> </html> |
複数のテンプレートを分けて呼び出し
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var myModlue = angular.module('myModlue', []); myModule.directive('templateDirective', function(){ return { restrict : 'AE', templateUrl: function(elem, attrs) { if (attrs.type === 'first') { return 'template_1.html' } else if (attrs.type === 'second' ) { return 'template_2.html' } else { return 'default.html' } }); |
1 2 3 |
<div> <p>テンプレートになるHTMLその1です</p> </div> |
1 2 3 |
<div> <p>テンプレートになるHTMLその2です</p> </div> |
1 2 3 4 5 6 7 8 9 10 11 12 |
<html ng-app="myModule"> <head> <script type="text/javascript" src="angular.min.js"></script> <script type="text/javascript" src="myModule.js"></script> </head> <body> <div template-directive type="first"></div> <div template-directive type="second"></div> </body> </html> |
まとめ
出力結果は、type=”first”属性を持っているタグの中にtemplate_1.htmlが入り、”second”を持つタグの中にtemplate_2.htmlが入る形となります。
directiveに渡す属性は今回は便宜的にtypeとしましたが、特に制約はありません。
注意点として、directiveに渡す値を動的に変更させたい場合、angulerの初期化処理が走るより先にHTML側には記述されてるようにしておかないと、directiveを初期化する際に値が足りず思うように動作してくれません。どうしてもJSで切り替えたい場合は他の手段も検討するべきでしょう。
これで同じdirectiveの処理、振る舞いを使いまわしつつ、見た目を構築するHTMLのtemplate部分を出し分けることが出来ます。
関連記事
http://astone.jeez.jp/angular_directive_template/【AngularJS】directiveで読み込むtemplateを動的に切り替える | astone.jeez.jphttp://astone.jeez.jp/wp-content/uploads/2016/01/Life-of-Pix-free-stock-photos-city-woman-camera-leeroy.jpghttp://astone.jeez.jp/wp-content/uploads/2016/01/Life-of-Pix-free-stock-photos-city-woman-camera-leeroy-150x150.jpgProgramminganguler.js,HTML,JavaScript,template,フロントエンド
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 15233 bytes) in /home/milksoap/www/_itblog/wp-content/plugins/crayon-syntax-highlighter/crayon_wp.class.php on line 854