LoginSignup
16
19

More than 5 years have passed since last update.

AngularJSでDirectiveのtemplateUrlを動的に変更する方法

Last updated at Posted at 2014-08-07

機能的には同じDirectiveで扱いたいけど、例えば記事の種類などで見た目は変えたい場合のために、DirectiveのtemplateUrlを後から書き換える方法です。

templateUrlでなく、templateで指定したhtmlの中でng-includeを使います。
scopeでtemplateの判定に使える何かを渡します。

App.directive 'Article', ->
  restrict: 'E'
  replace: 'true'
  scope: { template: "=" }
  template: "<div data-ng-include src=\"'templates/' +  template + '.html'\"></div>"
]

もう少し簡潔な解決方法がありそうな気もする(or あってほしい)のですが、一旦上記で対応出来ました。

[追記] 普通にtemplateUrlに関数渡せるよ!という指摘が @izumin5210 からありました!当然こちらの方がスマートですね!(1.3.x~以降のdeveloper guideに載ってるそうです。昔はなかったのかなと思いきや1.2.xのapi referenceにもキッチリ載ってました。悲しい!)

angular.module('docsTemplateUrlDirective', [])
.directive('myCustomer', function() {
  return {
    templateUrl: function(elem, attr){
      return 'customer-'+attr.type+'.html';
    }
  };
});

以上です。

16
19
2

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
16
19