在角度数据表中使用工厂作为源数据并不起作用

时间:2016-06-22 13:29:54

标签: javascript jquery angularjs json datatable

可以在角度数据表中使用工厂作为源数据吗?

基本上,我希望在变量中返回数据并将其用作源数据。

更新(2016年6月22日)

现在这是我的工厂:



statisticsModule.factory('globalFactory', function($rootScope, $http){

  var globalFactory = {};

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

  return globalFactory;

});




这是我的控制器



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. 我的数据表 - 脚本位于正确的位置,实际上,如果我使用来自直接网址的数据作为源,视图会完美加载。
  2. 我已经在html标签中添加了ng-app
  3. 我希望构建数据表的函数使用数据过滤

2 个答案:

答案 0 :(得分:1)

** 2015年6月23日解决**

这很难,但最后我可以解决它!

  1. 第一步:创建模块:
  2. 
    
    var statisticsModule = angular.module("statisticsModule", ['datatables', 'datatables.bootstrap']);
    
    //Bootstrap was added for best views
    
    
    

    1. 第二步:创建工厂
    2. 
      
      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. 第三步:创建控制器
      2. 
        
        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. 最后,第四步:进入视图
        2. 
          
          <!--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>
          &#13;
          &#13;
          &#13;

答案 1 :(得分:0)

代码应该更像这样。

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

<强>控制器

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. 在我的尝试中,控制台抛出了一个错误:[ng-areq] statusController not a function got undefined
  2.   

在注册控制器时,不明白为什么要将statusController作为参数传递。删除它。

<强>更新

您也可以使用服务

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

并在控制器中调用

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