Anto Anto - 5 months ago 21
AngularJS Question

Populate a table dynamically in Angular

I am new to Angular. I have created an app that, given the click of a button, should trigger a call that gets a set of json objects and populate a specific table. In the following controller code I have managed to populate the table directly without the click of a button (via the this.tableParams), but what I want is to trigger this data fetching process and populate the table only when the populateTable() function is called.How do I do it?

(function() {
'use strict';

angular
.module('anomalies')
.controller('controller', ['$log', '$scope', '$http', 'NgTableParams', function ($log, $scope, $http, NgTableParams) {

$scope.populateTable = function () {

//

}


this.tableParams = new NgTableParams({}, {
filterDelay: 300,
getData: function (params) {
return $http({
method: 'GET',
url: '/server/data.json'
}).then(function (response) {
return response.data;
}, function (response) {
$log.log(response);
return [];
});
}
});

}]);

})();

Answer

Why not creating the NgTableParams-object inside the populateTable-function?

angular
    .module('anomalies')
    .controller('controller', ['$log', '$scope', '$http', 'NgTableParams', function ($log, $scope, $http, NgTableParams) {

    $scope.populateTable = function () {
      this.tableParams = new NgTableParams({}, {
        filterDelay: 300,
        getData: function (params) {
            return $http({
                method: 'GET',
                url: '/server/data.json'
            }).then(function (response) {
                return response.data;
            }, function (response) {
                $log.log(response);
                return [];
            });
        }
      });
    }.bind(this);




}]);

Not the .bind(this). This ensures the this keyword means the same inside the populateTable-function as in the controller.