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

April 19, 2015

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

公式に説明のある方法

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

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

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

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

ただし、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: ’

’,
link: function(scope, element, attrs) {
return scope.contentUrl = “contents/” + scope.name + “.html”;
}
};
};

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

参考


Profile picture

Written by morizotter who lives and works in Tokyo building useful things. You should follow them on Twitter