LoginSignup
10
11

More than 5 years have passed since last update.

AngularJSでDirectiveのtemplateを変数を使って動的に変更する方法

Last updated at Posted at 2015-04-19

AngularJS初心者です。Directiveで表示するtemplateを動的に設定したいと思い、なんとか解決したのでその記録を残しておこうと思います。

公式に説明のある方法

まず、AngularJSのDirectiveの解説ページを見て、

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

このようにやってみました。この方法だと下記のように、type="name"と指定するとうまくいきます。

<div ng-controller="Controller">
  <div my-customer type="name"></div>
  <div my-customer type="address"></div>
</div>

変数を指定するとうまくいかない

ただし、type="{{name}}"のようにScopeの変数を指定するとうまく行きません。

GET http://localhost:9000/functions/%7B%7Bname%7D%7D.html 404 (Not Found)

中身を調べてみると、attr.type{{name}}でした。templateUrlを用意する段階でまだ評価されていないようです。

変数を使って動的にtemplateを変更する

そこで、下記のようにした所、変数を使って動的にtemplateを指定することが出来ました。

example = function() {
  return {
    scope: {
      name: "@"
    },
    template: '<pre ng-include="contentUrl"></pre>',
    link: function(scope, element, attrs) {
      return scope.contentUrl = "contents/" + scope.name + ".html";
    }
  };
};

templateng-includeを使って、動的な変化に対応できるようになりました。突っ込みどころ満載と思いますが、おかしな点、言葉遣いの間違いなどご指摘ありましたら。よろしくお願いします!

参考

10
11
0

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
10
11