简体   繁体   中英

Angular - Datatable click row event

I am working with AngularJS and angular-datatable and I want to work with the event in a row, I have setup the controller to listen the event but it is not work. My code is :

html

<div  class="panel panel-flat">
    <div class="panel-heading">
        <h6 class="panel-title">Planilla</h6>
    </div>
    <div class="panel-heading"> 
    <table class="table datatable-basic table-hover" datatable="ng" dt-options="empleadoList.dtOptions"  dt-column-defs="empleadoList.dtColumnDefs" >
        <thead>
            <tr>
                <th style="width: 30px;">Nro.</th>  
                <th>Nombre Completo</th>
                <th class="col-md-2">DNI</th>
                <th class="col-md-2">Celular</th>
                <th class="col-md-2">Teléfono</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="empleado in empleadoList.empleados">
                <td style="width: 30px;">{{$index + 1}}</td>
                <td> <span class="text-muted"><i class="icon-user"></i>{{empleado.apellidoPaterno}} {{empleado.apellidoMaterno}} {{empleado.nombre}}</span></td>
                <td><span class="text-success-600"><span class="status-mark border-blue position-left"></span>{{empleado.dni}}</span></td>
                <td><span class="text-success-600"><i class="icon-mobile position-left"></i> {{empleado.celular}}</span></td>
                <td><h6 class="text-semibold"><i class="icon-phone position-left"></i> {{empleado.telefono}}</h6></td>
            </tr>
        </tbody>
    </table>
    </div>
</div>

controller.js

App.controller('EmpleadoListController', function($scope,$resource,EmpleadoService,DTOptionsBuilder,DTColumnDefBuilder) {

$scope.dtOptions = DTOptionsBuilder.newOptions()
    .withDisplayLength(10)
    .withOption('bLengthChange', false)
    .withPaginationType('full_numbers')
    .withOption('rowCallback', rowCallback);
$scope.dtColumnDefs = [
                   DTColumnDefBuilder.newColumnDef(0),
                   DTColumnDefBuilder.newColumnDef(1),
                   DTColumnDefBuilder.newColumnDef(2),
                   DTColumnDefBuilder.newColumnDef(3),
                   DTColumnDefBuilder.newColumnDef(4)
               ];

function rowCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
    $('td', nRow).unbind('click');
    $('td', nRow).bind('click', function() {
        $scope.$apply(function() {
            console.log('click row');
        });
    });
    return nRow;
}

EmpleadoService.fetch().then(
        function(response){
            return $scope.empleadoList = { empleados: response.data};
        }, 
        function(errResponse){
            console.error('Error while fetching users');
            return $q.reject(errResponse);
        }
);
});

app.js

'use strict';
var App = angular.module('myApp', ['ngRoute','ngResource','datatables']);
App.config(function($routeProvider) {
  var resolveEmpleados = {
    empleados: function (EmpleadoService) {
    return EmpleadoService.fetch();
  }
 };

$routeProvider
 .when('/planilla', {
    controller:'EmpleadoListController as empleadoList',
    templateUrl:'static/js/planilla.html',
  });
});

Thanks for all.

Since you are using the angular way for rendering, why not use ng-click as well :

<tr ng-repeat="empleado in empleadoList.empleados" ng-click="click(empleado)">
$scope.click = function(empleado) {
  console.log(empleado.apellidoPaterno+' clicked')
}

I see you miss function in your code:

function someClickHandler(info) {
    vm.message = info.id + ' - ' + info.firstName;
}

function rowCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
    // Unbind first in order to avoid any duplicate handler (see https://github.com/l-lin/angular-datatables/issues/87)
    $('td', nRow).unbind('click');
    $('td', nRow).bind('click', function() {
        $scope.$apply(function() {
            vm.someClickHandler(aData);
        });
    });
    return nRow;
}

and don't forget this:

vm.someClickHandler = someClickHandler;

you can read document in here

Hope help you.

You were almost there. The row element is accessible from within the row callback function as nRow.

So for instance you can for instance change the colour of the row by toggling the selected class as follows

$scope.$apply(function() {
      $(nRow).toggleClass('selected');
      // do your stuff with the row here
});

nRow gives you access to the row element.

Then there is aData which gives you an array containing the values of the td or column elements in that row.

$scope.$apply(function() {
      console.log(aData);
      // do your stuff with the row here
});

Maybe this code can help us:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-row-click-event',
  templateUrl: 'row-click-event.component.html'
})
export class RowClickEventComponent implements OnInit {
  message = '';
  dtOptions: DataTables.Settings = {};

  constructor() { }

  someClickHandler(info: any): void {
    this.message = info.id + ' - ' + info.firstName;
  }

  ngOnInit(): void {
    this.dtOptions = {
      ajax: 'data/data.json',
      columns: [{
        title: 'ID',
        data: 'id'
      }, {
        title: 'First name',
        data: 'firstName'
      }, {
        title: 'Last name',
        data: 'lastName'
      }],
      rowCallback: (row: Node, data: any[] | Object, index: number) => {
        const self = this;
        // Unbind first in order to avoid any duplicate handler
        // (see https://github.com/l-lin/angular-datatables/issues/87)
        $('td', row).unbind('click');
        $('td', row).bind('click', () => {
          self.someClickHandler(data);
        });
        return row;
      }
    };
  }
}
```

Link where i found this example:
[Link github datatables examples][1]


  [1]: https://github.com/l-lin/angular-datatables/blob/master/demo/src/app/advanced/row-click-event.component.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM