沿着單指令路線走下去可能是最容易的,在這種情況下,我可以想到兩個解決方案。最好取決於各個模板的大小。
小模板:ng-switch
給你的指令,一個HTML文件,因爲它是templateUrl
其中包含一個ng-switch
有ng-switch-when
情況下,每個type
。這將是這個樣子:
// directive.js
angular.directive('directive', function() {
return {
scope: {type: '@'},
templateUrl: '/path/to/directive/template.html'
};
});
// template.html
<div ng-switch="type">
<div ng-switch-when="somethingType">
<!-- template for (type === "somethingType") -->
</div>
<div ng-switch-when="otherType">
<!-- template for (type === "otherType") -->
</div>
<!-- ... -->
</div>
大模板:ng-include
使用相同的行爲在上面directive.js
但保留所有的模板中自己個人的HTML文件的本地該指令的目錄,然後根據type
的值使用ng-include
拉入正確的模板。
/path/to/directive
- /templates
- somethingType.html
- otherType.html
- directive.js
- template.html
// template.html
<div ng-include="'/path/to/directive/templates/' + type + '.html'"></div>
謝謝,這幾乎完全回答了我的問題。唯一的問題是'type'的值是不變的 - 在指令編譯之後不會改變。這是否改變了處理它的最佳方式?因爲你說你的解決方案是針對「改變類型」的情況。 –
任何一種解決方案對於'type'的靜態值也都可以正常工作。我已經從我的帖子中刪除了這個警告 - 我只是在大聲思考。 – sdgluck
好的。我認爲也許對於靜態值還有其他解決方案。感謝您的幫助! –