简体   繁体   中英

AngularJS dataTable, $http get doesn't work

Data table in angularJS doesn't work when i ng-repeat object from $http.get Here's ex. (The first table works, the second table does not work) https://codepen.io/bafu2203/pen/VzBVmy

JS:

var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
app.controller('validationCtrl',function($scope, $http, $timeout){
  $scope.getapi = function(){
        $http({
            method: 'GET',
            url: 'https://www.w3schools.com/angular/customers_mysql.php',
        })
            .then(function successCallback(data) {
                $scope.test = data.data.records;
                console.log($scope.test);
                $timeout($scope.getapi, 1000);
            }, function errorCallback(response) {
                console.log(response);
                console.log('error');
            });

    };
    $scope.getapi();


  $scope.data={ "records":[ {"Name":"Alfreds Futterkiste","City":"Berlin","Country":"Germany"}, {"Name":"Ana Trujillo Emparedados y helados","City":"México D.F.","Country":"Mexico"}, {"Name":"Antonio Moreno Taquería","City":"México D.F.","Country":"Mexico"}, {"Name":"Around the Horn","City":"London","Country":"UK"}, {"Name":"B's Beverages","City":"London","Country":"UK"}, {"Name":"Berglunds snabbköp","City":"Luleå","Country":"Sweden"}, {"Name":"Blauer See Delikatessen","City":"Mannheim","Country":"Germany"}, {"Name":"Blondel père et fils","City":"Strasbourg","Country":"France"}, {"Name":"Bólido Comidas preparadas","City":"Madrid","Country":"Spain"}, {"Name":"Bon app'","City":"Marseille","Country":"France"}, {"Name":"Bottom-Dollar Marketse","City":"Tsawassen","Country":"Canada"}, {"Name":"Cactus Comidas para llevar","City":"Buenos Aires","Country":"Argentina"}, {"Name":"Centro comercial Moctezuma","City":"México D.F.","Country":"Mexico"}, {"Name":"Chop-suey Chinese","City":"Bern","Country":"Switzerland"}, {"Name":"Comércio Mineiro","City":"São Paulo","Country":"Brazil"} ] }



$scope.dataTableOpt = {
   //custom datatable options 
  // or load data through ajax call also
  "aLengthMenu": [[10, 50, 100,-1], [10, 50, 100,'All']],
  "aoSearchCols": [
      null
    ],
  };
});

Make the Api call one time. Then add it to and object or array. Then filter that object/array. Now it seems that you are making the Api call everytime you press any filtering function. Make it accessible outside the api function.

//Outside function
$scope.testData = {};

//Inside
$scope.testdata = data.data.records;

This is why you should use angular dataTables . AngularJS and jQuery dataTables ends up in a race where they both try to manipulate DOM, and the one is not aware of what the other is doing, or even exists. angular-ui-jq does not solve this issue, it basically just do a $('table').DataTable() at some arbitrary point.

You can implement a simple dataTable along with angular, but as soon are using multiple tables or the more fancy dataTables stuff the entire setup will break. Angular dataTables is jQuery dataTables wrapped into directives so they actually works in the angular environment.

Your code can very easily be refactored to

$scope.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
   var defer = $q.defer();
   $http.get('https://www.w3schools.com/angular/customers_mysql.php').then(function(result) {
     defer.resolve(result.data.records);
   });
   return defer.promise;
 })    
 .withOption('lengthMenu', [[10, 50, 100,-1], [10, 50, 100,'All']]);

$scope.dtColumns = [       
  DTColumnBuilder.newColumn(null).withTitle('#').renderWith(function(data, type, full, meta) {
     return meta.row + 1
  }),  
  DTColumnBuilder.newColumn('Name').withTitle('name'),
  DTColumnBuilder.newColumn('City').withTitle('position')
]       

markup

<table datatable
   dt-options="dtOptions" 
   dt-columns="dtColumns">
</table>

demo -> http://plnkr.co/edit/sca9WflpKNn2EIYct0EL?p=preview

You can render with ng-repeat if you use datatable="ng" , but this is not recommendable since it is far slower compared to dataTables optimized rendering.


If you get confused over the dtColumns construct, you can use good old dataTables columns instead :

$scope.dtColumns = [       
  { data: null, title: '#', 
    render: function(data, type, full, meta) {
     return meta.row + 1
    })
  },
  { data: 'Name', title: 'Name' },
  { data: 'City', title: 'City' }
]   

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