And*_*rei 32 javascript angularjs angularjs-directive
我正在尝试实现自定义sortBy指令,以便使html表中的列可排序.
HTML:
<thead>
<tr>
<sort-by-directive
ng-repeat="header in headers"
onsort="onSort"
sortdir="filterCriteria.sortDir"
sortedby="filterCriteria.sortedBy"
sortvalue="{{ header.value }}">{{ header.title }}
</sort-by-directive>
</tr>
</thead>
Run Code Online (Sandbox Code Playgroud)
JS:
angular.module('mainApp.directives').directive('sortByDirective', function () {
return {
templateUrl: 'SortHeaderTemplate',
restrict: 'E',
transclude: true,
replace: true,
scope: {
sortdir: '=',
sortedby: '=',
sortvalue: '@',
onsort: '='
},
link: function (scope, element, attrs) {
scope.sort = function () {
if (scope.sortedby == scope.sortvalue)
scope.sortdir = scope.sortdir == 'asc' ? 'desc' : 'asc';
else {
scope.sortedby = scope.sortvalue;
scope.sortdir = 'asc';
}
scope.onsort(scope.sortedby, scope.sortdir);
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
指令模板:
<script id="SortHeaderTemplate" type="text/ng-template">
<th ng-click="sort(sortvalue)">
<span ng-transclude=""></span>
<span ng-show="sortedby == sortvalue">
<i ng-class="{true: 'sorting_asc', false: 'sorting_desc'}[sortdir == 'asc']"></i>
</span>
<span ng-show="sortedby != sortvalue">
<i ng-class="{true: 'sorting', false: 'sorting'}[sortdir == 'asc']"></i>
</span>
</th>
</script>
Run Code Online (Sandbox Code Playgroud)
因此,当我使用th指令模板的根标签时,我检索错误:
Error: [$compile:tplrt] Template for directive 'sortByDirective' must have exactly one root element. SortHeaderTemplate
Run Code Online (Sandbox Code Playgroud)
但是当我改变th到a或span标签一切工作正常.
我究竟做错了什么?
dar*_*ong 22
这不是你的情况,但我遇到了同样的问题,因为我的代码在模板标记之前和之后都有html注释,如下所示:
<!-- Foo Widget -->
<div class="foo-widget">[...]</div>
<!-- end:: Foo Widget -->
Run Code Online (Sandbox Code Playgroud)
我摆脱了评论和vo-问题解决了.
chb*_*own 21
我希望<th>当它在a的上下文之外进行评估时,它会在某个中间点被融化<tr>(将该模板放入网页的某个随机部分以查看<th>消失).
在你的位置,我会<div>在模板中使用a ,更改sort-by-directive为'A'类型指令,并使用a <th sort-by-directive>...</th>之前,不使用 replace: true.
此错误也可能是由于您需要为指令模板中的所有标记创建包装元素.您的指令的模板不能只是:
<nav></nav>
<div></div>
Run Code Online (Sandbox Code Playgroud)
肯定是:
<div>
<nav></nav>
<div></div>
</div>
Run Code Online (Sandbox Code Playgroud)
我知道这很旧,但还有另一种解决方案。我也遇到了这个问题,并尝试了上述所有解决方案,但没有成功。
事实证明,出于某种奇怪的原因,如果“templateUrl”中存在拼写错误,也会抛出此错误 - 如果 angular 无法通过给定路径找到 html 文件 - 您会得到相同的“必须只有一个根”元素”错误。
所以 - 修复 templateUrl 为我修复了错误。
希望这对未来的任何人都有帮助。
| 归档时间: |
|
| 查看次数: |
56271 次 |
| 最近记录: |