简体   繁体   中英

Using a factory as source data in angular-datatables doesn't work

It's possible to use a factory as source data in angular-datatables?

Basically, I wish to return data in a variable and use it as source data.

UPDATED (06/22/2016)

Now this is my factory:

 statisticsModule.factory('globalFactory', function($rootScope, $http){ var globalFactory = {}; globalFactory.getUrl = function(){ return $http.get('../statistics/php/config_statistics.json'); }; return globalFactory; }); 

And this is my Controller

 statisticsModule.controller("dataController", dataController); //Fin controlador function dataController($scope, $http, globalFactory, DTOptionsBuilder, DTColumnBuilder){ //Promise con el factory globalFactory.getUrl().then(function(response){ //Obtener data var urlGlobal = response.data; //Filtrar data. arrayReportBD : Arreglo con las URL de los reportes var deserialize = angular.fromJson(urlGlobal.config.graph_conf_array.arrayReportBD); //Data Distribución de Estatus var urlStatus = deserialize[0]; //Obtener data de Distribución de Estatus $http.get(urlStatus).success(function(data){ console.log(data); var vm = this; vm.dtOptions = DTOptionsBuilder.fromSource(data) .withDOM('lfrtip') .withPaginationType('full_numbers') .withLanguage({ "sEmptyTable": "No hay datos para cargar en la tabla", "sInfo": "Mostrando _START_ de _END_ de _TOTAL_ entradas", "sInfoEmpty": "Mostrando 0 de 0 de 0 entradas", "sInfoFiltered": "(filtradas _MAX_ entradas totales)", "sInfoPostFix": "", "sInfoThousands": ",", "sLengthMenu": "Mostrar _MENU_ entradas", "sLoadingRecords": "Cargando...", "sProcessing": "Procesando...", "sSearch": "Buscar:", "sZeroRecords": "No se encontraron registros", "oPaginate": { "sFirst": "Primera", "sLast": "Última", "sNext": "Siguiente", "sPrevious": "Anterior" }, "oAria": { "sSortAscending": ": activar para ordenar de forma ascendente", "sSortDescending": ": activar para ordenar de forma descendente" } }); vm.dtColumns = [ DTColumnBuilder.newColumn('gob_code').withTitle('Cód. Gob.'), DTColumnBuilder.newColumn('fci_code').withTitle('Cód. FCI'), DTColumnBuilder.newColumn('name').withTitle('NOMBRE'), DTColumnBuilder.newColumn('status').withTitle('ESTATUS') ]; }).error(function(err){ });//Fin $http });//Fin promise }//Fin función 

PD:

  1. I've datatables-scripts in correct position, indeed, if I use the data from a direct URL as source the view loads perfectly.
  2. I've already added the ng-app in html tag
  3. I want that the function to build datatables use data filtered

**SOLVED 06/23/2015**

It was hard, but finally I could solve it!

  1. STEP ONE: CREATE MODULE:

 var statisticsModule = angular.module("statisticsModule", ['datatables', 'datatables.bootstrap']); //Bootstrap was added for best views 

  1. STEP TWO: CREATE FACTORY

 statisticsModule.factory('globalFactory', function($rootScope, $http){ var globalFactory = {}; globalFactory.getUrl = function(){ return $http.get('../statistics/php/reports/r_reports_status.php').success(function(data){ }); }; return globalFactory; }); //Factory pointing to specific URL that contains the data 

  1. STEP THREE: CREATE CONTROLLER

 statisticsModule.controller("dataController", dataController); function dataController(DTOptionsBuilder, DTColumnBuilder, $scope, globalFactory){ var vm = this; //Return data from factory vm.dtOptions = DTOptionsBuilder.fromFnPromise(function(){ return globalFactory.getUrl().then(function(response){ return response.data; }) }) .withDOM('lfrtip') .withPaginationType('full_numbers') //Language Spanish (optional) .withLanguage({ "sEmptyTable": "No hay datos para cargar en la tabla", "sInfo": "Mostrando _START_ de _END_ de _TOTAL_ entradas", "sInfoEmpty": "Mostrando 0 de 0 de 0 entradas", "sInfoFiltered": "(filtradas _MAX_ entradas totales)", "sInfoPostFix": "", "sInfoThousands": ",", "sLengthMenu": "Mostrar _MENU_ entradas", "sLoadingRecords": "Cargando...", "sProcessing": "Procesando...", "sSearch": "Buscar:", "sZeroRecords": "No se encontraron registros", "oPaginate": { "sFirst": "Primera", "sLast": "Última", "sNext": "Siguiente", "sPrevious": "Anterior" }, "oAria": { "sSortAscending": ": activar para ordenar de forma ascendente", "sSortDescending": ": activar para ordenar de forma descendente" } }) //More options for best views .withDisplayLength(1) .withOption('responsive', true) .withBootstrap(); //BELOW GOES vm.dtColumns and } that ends the function 

  1. AND FINALLY, STEP FOUR: PUT INTO VIEW

 <!--THIS IS THE ORDER--> <head> <!--JQUERY SCRIPT--> <!--JQUERY DATATABLES SCRIPT--> <!--ANGULAR SCRIPT--> <!--ANGULAR DATATABLE SCRIPT--> <!--ANGULAR DATATABLE CSS--> <!--DATATABLES BOOTSTRAP CSS--> <!--DATATABLES RESPONSIVE CSS--> <!--MODULE--> <!--CONTROLLER--> <!--FACTORY--> <!--ANGULAR DATATABLES BOOTSTRAP SCRIPT--> <!--BOOTSTRAP SCRIPT--> </head> <body> <div ng-controller="dataController as showCase"> <table datatable="" dt-options="showCase.dtOptions" dt-columns="showCase.dtColumns" class="table table-striped table-bordered"></table> </div> <!--DATATABLES RESPONSIVE SCRIPT--> </body> 

The code should be more like this.
Factory

statisticsModule.factory('globalFactory', ['$http', function ($http) {
    var GetStatistics = function () {
        return $http.get('../statistics/php/config_statistics.json');
    };
    return {
        GetStatistics: GetStatistics
    }
}]);

Controller

statisticsModule.controller("tableController", ['globalFactory', '$http',
    function (globalFactory, $http) {
    //.success is obsolete.
    globalFactory.GetStatistics().then(function (response) {
         //success
         // Initialize DataTable here
    }, function (response) {
        //fail
        //alert(response.data);
    });
}]);
  1. In my attempt, the console throws me an error: [ng-areq] statusController not a function got undefined

Don't understand why you are passing statusController as an argument while registering the controller. Remove that.

Update

You can also use service

statisticsModule.service('globalService', ['$http', function ($http) {
    this.GetStatistics = function () {
        return $http.get('../statistics/php/config_statistics.json');
    };
}]);

And call it in controller like

globalService.GetStatistics().then(function (response) {
  //success
  // Initialize DataTable here
}, function (response) {
  //fail
  //alert(response.data);
});

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