我想创建一个指令,它将采用树状数据并将其提供给一些树视图脚本(使用标记作为输入),使用特定的 HTML 模板来呈现节点。因此,指令将数据 + 节点模板作为输入,插入 DOM 子树,然后调用第三方插件使其可排序(如果这很重要,我会想到http://dbushell.github.com/Nestable/)。
我有一个解决方案,但它远非优雅。这是 HTML 代码(完整示例可以在http://jsfiddle.net/DQjve/找到):
<div ng-app="TestApp" ng-controller="TestCtrl">
<script type="text/ng-template" id="tree.html">
<div>
<ng-include src="'branch.html'"></ng-include>
</div>
</script>
<script type="text/ng-template" id="branch.html">
<ul>
<li ng-repeat="leaf in leaf.children" ng-include src="'leaf.html'">
</li>
</ul>
</script>
<script type="text/ng-template" id="leaf.html">
<ng-include src="template"></ng-include>
<ng-include src="'branch.html'"></ng-include>
</script>
<script type="text/ng-template" id="my-leaf.html">
<span style="display: block; border: 1px solid gray; border-radius: 4px; background: yellow; margin: 3px 0; padding: 4px;">{{leaf.name}}</span>
</script>
<tree root="tree" template="my-leaf.html"></tree>
</div>
所需的代码如下所示:
<div ng-app="TestApp" ng-controller="TestCtrl">
<tree root="tree" template="my-leaf.html">
<span style="display: block; border: 1px solid gray; border-radius: 4px; background: yellow; margin: 3px 0; padding: 4px;">{{leaf.name}}</span>
</tree>
</div>
目标:
- (不太重要)将所有实用程序模板放在指令 JavaScript 代码中。
- (更重要)使用 <tree> 标签的内容作为节点模板。
但我找不到解决方案。
对于第 1 点:可能,我需要使用$templateCache
预缓存我的模板?有一些独特的模板名称?有没有更好的解决方案?
对于第 2 点:我应该使用ngTransclude
p.2 吗?如果是,如何?有没有办法在任何编译发生之前将初始 <tree> 标记的内容作为字符串获取?