小编典典

AngularJS:在指令模板中使用“ th”标记时,“指令模板必须完全具有一个根元素”

angularjs

我正在尝试实现自定义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>

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);
                }
            }
        };
    });

指令模板:

<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>

因此,当我将其th用作指令模板的根标记时,会检索到错误:

Error: [$compile:tplrt] Template for directive 'sortByDirective' must have exactly one root element. SortHeaderTemplate

但是当我更改thaspan标记时,一切正常。

我究竟做错了什么?


阅读 227

收藏
2020-07-04

共1个答案

小编典典

我希望<th>在上下文之外进行评估时,它会在某个中间点消失<tr>(将该模板放入您网页的某个随机部分以查看<th>消失)。

在您的位置上,我将<div>在模板中使用a ,更改sort-by-directive为“ A”类型指令,并<th sort-by- directive>...</th>像以前一样使用a , 不使用 replace: true

2020-07-04