Anto
Anto

Reputation: 4305

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 [];
                });
            }
        });

    }]);

})();

Upvotes: 0

Views: 272

Answers (2)

Johannes Reuter
Johannes Reuter

Reputation: 3547

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.

Upvotes: 2

Ladmerc
Ladmerc

Reputation: 1158

Move this.tableParams into the $scope.populateTable function. Bind this function to a button in the view e.g <button ng-click="populateTable()">Click Me!</button>

Upvotes: 1

Related Questions