AngularJS: 'Template for directive must have exactly one root element' when using 'th' tag in directive template

后端 未结 12 1226
梦如初夏
梦如初夏 2020-12-30 19:50

I\'m trying to implement custom sortBy directive in order to make columns in html table sortable.

HTML:


   
            


        
12条回答
  •  无人及你
    2020-12-30 20:21

    As stated by others: this is because your browser ignores the TH before it gets placed inside the table. My prefered way to fix this is to change the directive to an attribute directive and add it to a TH in the table.

    Directive looks like this:

    .directive('sortByDirective', function () {
    
        return {
            templateUrl: 'SortHeaderTemplate',
            restrict: 'A',
            transclude: true,
            replace: false,
            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);
                }
            }
        };
    });
    

    Setting it on your page looks like this:

    {{ header.title }}
    
    

提交回复
热议问题