Custom loading in Angular Datatables

2019-02-18 07:36发布

问题:

im trying to implement my custom loading in angular datatables. I checked the docs :https://l-lin.github.io/angular-datatables/#/overrideLoadingTpl, there suggest an implementation:

   angular.module('showcase', ['datatables']).
factory('DTLoadingTemplate', dtLoadingTemplate);
function dtLoadingTemplate() {
    return {
        html: '<img src="images/loading.gif">'
    };
}

So, in my custom Options i inject the loading in the option sLoadingRecords and sProcessing, but doesnt works.

    .factory('myDTOptions', function (DTOptionsBuilder,DTLoadingTemplate) {

  return {
    option1: function(){
      return DTOptionsBuilder.newOptions()
      .withPaginationType('full_numbers')
      .withDisplayLength(10)
      .withBootstrap()
      .withOption('responsive', true)
      .withLanguage({
            "sEmptyTable":     "No hay información disponible",
            "sInfo":           "Mostrando _START_ a _END_ de _TOTAL_ entradas",
            "sInfoEmpty":      "Mostrando 0 a 0 de 0 entradas",
            "sInfoFiltered":   "(filtrada de _MAX_ entradas totales)",
            "sInfoPostFix":    "",
            "sInfoThousands":  ",",
            "sLengthMenu":     "Mostrando _MENU_ entradas",
            "sLoadingRecords": DTLoadingTemplate,
            "sProcessing":     DTLoadingTemplate,,
            "sSearch":         "Buscar: ",
            "sZeroRecords":    "No se encuentra coincidencias en la búsqueda",
            "oPaginate": {
                        //Dos opciones: https://github.com/DataTables/Plugins/issues/62
                          "sFirst":    '<i class="fa fa-angle-double-left"></i>',
                          "sLast":     '<i class="fa fa-angle-double-right"></i>',
                          "sNext":     '<i class="fa fa-angle-right"></i>',
                          "sPrevious": '<i class="fa fa-angle-left"></i>'
                        },
            "oAria": {
                "sSortAscending":  ": activar para ordenar columna ascendentemente",
                "sSortDescending": ": activar para ordenar columna descendentemente"
              }
        })
        /*
            .withColVis()
            .withColVisOption('aiExclude', [0,1,6,7,8])*/
      }

回答1:

I had the same problem; after investigating the source it turns out to be quite simple. datatables.options should be injected as a dependency exactly as all the other dataTables features :

angular.module('myModule', [
  'datatables',
  'datatables.buttons',
  'datatables.bootstrap',
  'datatables.fixedheader',
  ...
  'datatables.options', //<---

])

Then the DTDefaultOptions service should be included as well (example) :

.controller('myCtrl', ['$scope', 'DTOptionsBuilder', 'DTDefaultOptions',
    function ($scope, DTOptionsBuilder, DTDefaultOptions) {

Now the default <h3>Loading...</h3> template can be changed by (example) :

DTDefaultOptions.setLoadingTemplate('<em>Fetching data</em> ...')

The Loading... element has nothing to do with dataTables language settings, but is angular dataTables own initialisation message. BTW this element can be styled through the CSS class .dt-loading :

.dt-loading {
  color: red;
}


回答2:

you create a loading div with your custom html and add these to options to the setup :

.withOption('fnPreDrawCallback', function () { console.log('loading..') })
.withOption('fnDrawCallback', function () { console.log('stop loading..') })
  • on 'fnPreDrawCallback' show the html
  • on 'fnDrawCallback' hide it.


回答3:

I've had success declaring my module/factory this way. I think essentially what happens is you inject the factory into your DT Module (myDataTables) which you "extended" from datatables and datatables.bootstrap.

Also, I found out for my own purposes there are two semi-ambiguous notions of loading/processing. The loading template and the processing text... if you're using server side processing they both come into play. I'm including usage for both here for posterity.

var dtLoadingTemplate;

dtLoadingTemplate = function() {
  return {
    html: '<img src="images/loading.gif">'
  };
};

angular.module('myDataTables', ['datatables', 'datatables.bootstrap']).run(function(DTDefaultOptions) {
  DTDefaultOptions.setLanguage({
    // ...
    sProcessing: '<img src="images/loading.gif">'
  });
}).factory('DTLoadingTemplate', dtLoadingTemplate);

Then your controller might look something like this:

myApp.controller('UsersController', [
    '$scope', 'DTOptionsBuilder', 'DTColumnBuilder', function($scope, DTOptionsBuilder, DTColumnBuilder) {

        $scope.dtInstance = null;
        $scope.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
            dataSrc: 'data',
            url: '/users.json',
            type: 'POST'
        })
        .withOption('processing', true)
        .withOption('serverSide', true)
        .withPaginationType('full_numbers').withBootstrap()
        .withOption('aaSorting', [0, 'desc'])
        .withOption('createdRow', function(row, data, dataIndex) {
            $scope.users.push(data);
            return $compile(angular.element(row).contents())($scope);
        });
        return $scope.dtColumns = [
            DTColumnBuilder.newColumn('id').withTitle('ID').withClass('user-id'),
            DTColumnBuilder.newColumn('name').withTitle('Title').withClass('user-name'),
            DTColumnBuilder.newColumn(null).withTitle('Actions').withClass('users_actions').notSortable().renderWith(function(user, type, full, meta) {
                return "<a class='btn btn-link' href='/users/" + user.id + "'>" + "<span class='fa fa-external-link fa-lg text-default' tooltip-placement='bottom' tooltip='View User'></span></a>";
            })
        ];
    }
]);

http://l-lin.github.io/angular-datatables/#/overrideLoadingTpl