【问题标题】:Selecting single row on click in a data table在数据表中单击时选择单行
【发布时间】:2016-05-10 07:01:00
【问题描述】:

我一直在尝试选择一个被点击的行,但我面临的问题是分页的表格在不同的页面上显示选定的行,而在其他页面上没有显示。

我只是在单击一行时删除和添加一个 css 类。

有点像 -

function rowClicked (){ 

    var table = $('#test').DataTable();

    $('#test tbody').on( 'click','tr', function () {
        if ( $(this).hasClass('selected') ) {
            $(this).removeClass('selected');
            console.log('helloe 1');
        }
        else {
            table.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
                console.log('helloe 3');
        }
    } );    


}

【问题讨论】:

  • 请出示您的完整代码。
  • 是的,您发布的代码似乎正确,使用 jsfiddle 或 codepen 显示页面 html

标签: angularjs datatable


【解决方案1】:

您可以将这样的 Angualr 指令用于您的表 <table select-row>

angular.module('myApp')
    .directive('selectRow', selectRow);

function selectRow($compile) {
    var directive = {
        bindToController: true,
        controller: testCtrl,
        controllerAs: 'vm',
        link: link,
        restrict: 'EA',
        scope: {}
    };
    return directive;

    function link(scope, element, attrs, vm) {
        var target, compileScope, newTd, template ;
        target = angular.element($('table tr'));
        compileScope = scope;
        scope.arr = [];
        angular.forEach(target, function(item) {
            return scope.arr.push(item.textContent);
        });
        template = '<table><thead><tr><th></th><tbody><tr ng-class="selected[$index]" ng-repeat="t in arr track by $index" ng-click="selectRow($index)"><td >{{t}}</td></tr></tbody></tr></thead></table>';
        template = angular.element(template);
        $compile(template)(compileScope);
        element.replaceWith(template);
        // function to select row 
        scope.selectRow = function($index) {
            scope.selected = [];
            scope.index = $index;
            scope.selected[$index] = scope.selected[$index] === 'selected' ? '' :'selected';
        }

    }

    function testCtrl() {

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多