Updating ng-table within an Angular controller

Having encountered an unusual issue with ng-table. Here is a snippet of code from my controller:

this.category = "Open";
this.category = ["Open", "Accepted", "Rejected"];
this.dataItems = [];

var _this = this;

this.$scope.$watch("vm.category", function(category) {
    _this.dataItems.length = 0; // Clearing items in the array  

    svc.getApplications(category).then(
        function(okResult) {
            angular.copy(okResult.data, _this.dataItems);

            _this.tableParams = new NgTableParams(
            {
                page: 1,
                count: 5,
                sorting: {
                    applicationDate: 'desc'
                }
            },
            {
                total: _this.dataItems.length,
                getData: function ($defer, params) {
                    var filtered = params.filter() ? _this.$filter('filter')(_this.dataItems, _this.filter) : _this.dataItems;
                    var ordered = params.sorting() ? _this.$filter('orderBy')(filtered, params.orderBy()) : filtered;

                    params.total(ordered.length);
                    if (params.total() < (params.page() - 1) * params.count()) {
                        params.page(1);
                    }

                    $defer.resolve(ordered.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                }
            }
    });

I have omitted some parts of the code for brevity. $scope, $filter, NgTableParams are all injected.

The UI has a dropdown like this:

<select id="cbCategory" class="form-control" data-ng-model="vm.category" data-ng-options="category for category in vm.categories"></select>

And the ng-table appears as follows:

<table class="table table-striped table-hover" id="tb1" data-ng-table="vm.tableParams">
    <tbody>
        <tr data-ng-repeat="item in $data">
            <td data-title="'Email'" data-filter="{ email: 'text' }" data-sortable="'email'">{{item.applicant.email}}</td>
            <!-- more... -->
        </tr>
    </tbody>
</table>

The problem I am facing: The table initially renders correctly. However, when I change the selection on the category dropdown, the getApplications call is made and

_this.tableParams = new NgTableParams
is executed (I confirmed through debugging that the service call runs without error). Yet, getData does not seem to trigger, resulting in no changes on the UI. I have used ng-table extensively but have not encountered this particular rerendering scenario before. What could I be overlooking? Just to clarify, there is controllerAs: vm somewhere in the code.

Answer №1

After some troubleshooting, I found a solution to the issue with the code above by reorganizing the logic in the controller:

this.category = "Open";
this.category = ["Open", "Accepted", "Rejected"];
this.dataItems = [];

var _this = this;

_this.tableParams = new NgTableParams(
{
    page: 1,
    count: 5,
    sorting: {
        applicationDate: 'desc'
    }
},
{
    total: _this.dataItems.length,
    getData: function ($defer, params) {
        var filtered = params.filter() ? _this.$filter('filter')(_this.dataItems, _this.filter) : _this.dataItems;
        var ordered = params.sorting() ? _this.$filter('orderBy')(filtered, params.orderBy()) : filtered;

        params.total(ordered.length);
        if (params.total() < (params.page() - 1) * params.count()) {
            params.page(1);
        }

        $defer.resolve(ordered.slice((params.page() - 1) * params.count(), params.page() * params.count()));
    }
}

this.$scope.$watch("vm.category", function(category) {
    _this.dataItems.length = 0; // To clear items already in the array  

    svc.getApplications(category).then(
        function(okResult) {
            angular.copy(okResult.data, _this.dataItems);

            // ADDED THIS...
            if (_this.tableParams) {
                _this.tableParams.reload();
            }
    });

It's worth noting that I experimented with placing the reload() in different sections of the code, but only one specific location proved effective.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with CORS in your Angular application?

I am attempting to retrieve data from a site with the URL: Using the $http service After extensive research, I have come up with this CoffeeScript code snippet: angular.module('blackmoonApp') .controller 'PricingCtrl', ($scope, $ht ...

What is the process for loading an external file within an npm script?

Objective: Testing the linting process of specific components within the source code, without affecting all files. I want to streamline the linting process by running a single command that covers multiple folders specified in a configuration file: //pack ...

Retrieve ALL information from a third-party API request with a limit of 1000 calls

Challenge: Implementation of a third-party API call using Node.JS. The API link restricts the number of users per call to 1000, with an option to retrieve the next set by passing parameters in the URL (?firstResult=1001&maxResults=1000&orderBy=NAME ...

Submit data via POST method on the modified URL

I need assistance with modifying the data of a URL and making a POST request to it. The URL in question is as follows: http://domanin.com/search-result/?start=06%2F08%2F2017&end=06%2F09%2F2017&room_num_search=1&adult_number=1&children_num= ...

data being returned twice onpopstate

After experimenting with onpopstate, I encountered an issue. When I click the back button in my browser, the URL changes as expected, but the page code loads twice, resulting in duplicate lists and div elements. Why is this happening and how can it be reso ...

Steps to dynamically reveal a table row within another row when clicked:

I have a table and I want to show the contents of another row inside the current row when the plus icon is clicked. I'm not sure which HTML element to use for this. Please help me figure it out. Thank you in advance. <div class="pro ...

Error: The document object is not defined when attempting to access it within a

<script type="module" src="/scripts/navbar.js"></script> <script> async function fetchContent(e) { e && e.preventDefault(); const response = await fetch('https: ...

Converting JSON data into an array of a particular type in Angular

My current challenge involves converting JSON data into an array of Recipe objects. Here is the response retrieved from the API: { "criteria": { "requirePictures": true, "q": null, "allowedIngredient": null, "excluded ...

Learn the technique of storing a sequence of functions within a variable using jQuery

For instance, I am looking to assign a sequential process to multiple variables and utilize them in various scenarios. var disable_btn = true; var button_me = $('#contents.getsamplekit .sample-form .form #submit-btn-freeSample-me'); var button_d ...

Transform a single attribute in an array of objects using angularjs and Javascript to a different value

Within an angularjs controller, the following code is used: var ysshControllers = angular.module('theControllers', []); ysshControllers.controller('CommonController', function($scope, $http, $route) { $scope.dbKey = $route ...

Swapping out the document.createElement() method for React.createElement()

In a JavaScript library, I utilize document.createElement() to create an HTMLElement. Now, I am looking to develop a React library with the same functionality. My initial thought was to substitute document.createElement() with React.createElement(). There ...

Looking to showcase duplicate ranks that have been selected, and specifically identify which ranks are being duplicated using JavaScript/jQuery

In this section, we have implemented the logic to identify duplicate ranks. However, in addition to displaying which ranks are duplicated, I also aim to highlight the specific rank that is being duplicated within the range of 0 to 18. function validate( ...

Guide on implementing ES6 script's template literals

I've been tackling a template literal question on hackerrank. It's working smoothly on my local IDE, but encountering an error on the Hackerrank IDE. Here's the code to add two numbers and print the result using a template literal: const sum ...

FFmpeg: audio synchronization issue observed with simultaneous usage of xfade and acrossfade techniques

Experiencing an issue when attempting to concatenate 12 videos together and maintain the audio using xfade and acrossfade filters. Without the audio stream, the video encodes correctly, but when combining with audio, transitions hang and audio sync is off. ...

The header Origin:file:// from the Ionic native app is generating issues

While working on my simple Todo app in Ionic 1, I encountered an issue with the Origin header, specifically related to CORS. Running ionic serve works perfectly fine in the browser and allows me to make requests to my REST API on Apache (Tomcat). Howev ...

What is preventing my code from locating the AngularJS $interval functionality?

Having an issue with my AngularJS Code when trying to call $interval in VS2013. The error message says it is not found. Here's the code snippet: var appRun = [ '$rootScope', function ( $rootScope ) { // This ...

Error: Jasmine cannot access a property of undefined value

Just getting started with js and jasmine Attempting to create a jasmine test case for my method. Encountering an error: TypeError: Cannot read property '0' of undefined. Tried different ways of passing arrays into my method sports but still facin ...

The repeated execution of a Switch Statement

Once again, I find myself facing a puzzling problem... Despite making progress in my game, revisiting one aspect reveals a quirk. There's a check to verify if the player possesses potions, and if so, attempts to use it involves calculating whether the ...

Issue encountered when attempting to remove an element from an array using the delete method

Whenever I attempt to remove an input that has been added, an error message saying "Value is NULL" pops up. I'm looking for a solution where only the selected inputs are deleted when I click on DELETE, instead of all inputs being removed. The myFuncti ...

Is your pure function component not receiving or responding to input props correctly?

Here is my code snippet: const actionCreators = { action: AppReducer.actionCreators.action } interface GlobalState { user: Model.User | null; } interface InputState { setStashBarWidth(width: number); stashWidth: number; } const Header = ...