沿着单指令路线走下去可能是最容易的,在这种情况下,我可以想到两个解决方案。最好取决于各个模板的大小。
小模板: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
好的。我认为也许对于静态值还有其他解决方案。感谢您的帮助! –