ng-table not working for dynamic data

后端 未结 6 1911
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 23:53

I have created a table and I am using http to load the data in the tables. So, in every click, my table data is changing, but I don\'t see the updated data in the table. I h

6条回答
  •  情书的邮戳
    2020-12-04 00:44

    With some trial and error I found a seemingly better solution to the issue than indicated in the plunkrs. For clarity, I am using $resource in a service to fetch my data. When I add a record via a modal, at first it wouldn't upload the ng-table after closing the modal. I figured out a way that works for me:

    // Get data from factory
    var data = dataFactory.query();
    
    //Use promise to load data to table, note the replacing of the second tableParams 
    //object parameter with a function
    data.$promise.then(function (data){
        $scope.tableParams = new ngTableParams({
            page: 1,            // show first page
            count: 10,
            sorting: {
                name: 'asc'
            },
            filter: {
                name: undefined             
            }
        }, resetTableParams()
        );
    });
    
    //The function that replaces the tableParams param
    var resetTableParams = function(){
        return {
            total: data.length,
            getData: function($defer, params) {
                var filteredData = params.filter() ? $filter('filter')(data, params.filter()) : data;
                var orderedData = params.sorting() ? $filter('orderBy')(data, params.orderBy()) : filteredData; 
    
                params.total(orderedData.length);
                $defer.resolve($scope.data = orderedData.slice((params.page() -1) * params.count(), params.page() * params.count()));           
                }
        }
    }
    
    //A method to update the table that can be called when closing a modal
    var updateTable = function(){
        data = dataFactory.query();
        data.$promise.then(function (data){
            $scope.tableParams.reload();
        });
    }
    
    // Add table row to table in modal and call updateTable() on closing modal
    $scope.addRow = function(){
        var modalInstance = $modal.open({
            templateUrl: 'resources/partials/newrecord.html',
            controller: NewRecordModalCtrl
        })
    
        modalInstance.result.then(function(){
            updateTable();
        });
    }
    

    Unfortunately, I can't give a clear explanation as to why this works and other methods don't. For instance, if you would not use the resetTableparams() function but leave it hardcoded, the table does not update. Somehow, Angular's digest cycle likes this better :) If somebody has a good explanation, please share!

提交回复
热议问题