The datatable fails to render after executing a function in AngularJS

When I load the page without calling a function, the data is displayed in a datatable perfectly fine. However, if I try to generate the datatable after calling a function, it does not work.

HTML:

             <div class="widget-body no-padding">
              <table datatable dt-options="datatables.standardOptions" dt-columns="datatables.standardColumns" class="table table-striped table-bordered table-hover" width="100%">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Section</th>
                    <th>Gender</th>                       
                  </tr>
                </thead>
              </table>
            </div>
           <div class="text-center margin-top-10 margin-bottom-10">
          <button class="btn btn-xs btn-primary" ng-
               click="tableCall();">Apply</button>
           </div>

Controller:

 $scope.tableCall=function(){
    this.standardOptions = DTOptionsBuilder
      .fromFnPromise(call.all('------API----------').getList())
      .withDOM("<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>" +
      "t" +
      "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>")
      .withBootstrap();
    this.standardColumns = [
        DTColumnBuilder.newColumn('name').withOption('defaultContent','-'),
        DTColumnBuilder.newColumn('age').withOption('defaultContent','-'),
        DTColumnBuilder.newColumn('section').withOption('defaultContent','-'),
        DTColumnBuilder.newColumn('gender').withOption('defaultContent','-'),
      ];
}

JSON DATA:

[
{
name: "thomus",
age: 27,
section:"K",
gender:"M" 
},
{
name: "Roy",
age: 67,
section:"m",
gender:"F" 
},
{
name: "Keni",
age: 34,
section:"L",
gender:"F" 
}
]

The datatable functions properly without the need for the tableCall function. It generates as expected without any issues.

See below code:

HTML

 <div class="widget-body no-padding">
              <table datatable dt-options="datatables.standardOptions" dt-columns="datatables.standardColumns" class="table table-striped table-bordered table-hover" width="100%">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Section</th>
                    <th>Gender</th>                       
                  </tr>
                </thead>
              </table>
            </div>

Controller

this.standardOptions = DTOptionsBuilder
          .fromFnPromise(call.all('------API----------').getList())
          .withDOM("<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>" +
          "t" +
          "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>")
          .withBootstrap();
        this.standardColumns = [
            DTColumnBuilder.newColumn('name').withOption('defaultContent','-'),
            DTColumnBuilder.newColumn('age').withOption('defaultContent','-'),
            DTColumnBuilder.newColumn('section').withOption('defaultContent','-'),
            DTColumnBuilder.newColumn('gender').withOption('defaultContent','-'),
          ];

The above code successfully generates the datatable, but my requirement is to implement the datatable functionality after calling the designated function.

Answer №1

It's recommended to initialize this.standardOptions at the beginning of your code

this.standardOptions = {};
$scope.tableCall=function(){
   angular.extend(this.standardOptions, DTOptionsBuilder
  .fromFnPromise(call.all('------API----------').getList())
  .withDOM("<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>" +
  "t" +
  "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>")
  .withBootstrap());
this.standardColumns = [
    DTColumnBuilder.newColumn('name').withOption('defaultContent','-'),
    DTColumnBuilder.newColumn('age').withOption('defaultContent','-'),
    DTColumnBuilder.newColumn('section').withOption('defaultContent','-'),
    DTColumnBuilder.newColumn('gender').withOption('defaultContent','-'),
  ];
}

Another thing that seems odd is that standardOptions is defined on 'this' but tableCall function is defined on $scope. Check if in your DOM you are using ng-controller with the 'as' keyword. Ensure consistency between using $scope or 'this'. There may be an error in how things are set up here.

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

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

The AngularJS request.POST method is returning an empty QueryDict: {}

Currently, I have an AngularJS code snippet where I am making a POST request: 'use strict'; angular.module('app').controller('RegisterController', function($scope, $http) { $scope.login = [] $scope.registrar ...

Encountered an issue when attempting to establish a connection with the REST

I am encountering an issue with connecting to a web service deployed on an Apache server using Jersey. The error message I receive is: Failed to load http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/query: No 'Access-Control-Allow-Origin' ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

React app's setTimeout function fails to execute at the designated time specified

I have a function set up in my React app to handle user authentication and signup. The function is supposed to display an alert message saying "Account Created" upon successful signup, and then redirect the user to their profile page after a 1-second delay ...

Why is the responseText of an AJAX request empty on Chrome?

Why does this simple AJAX request work in IE but not Chrome? Check out the code below: var x = new XMLHttpRequest(); x.open("GET","style.php",true); x.send(); alert(x.responseText); The last line triggers an empty 'alert' window. Here's ...

What could be the reason for NPM failing to work following an update?

Just two days ago, I updated NPM and now it's suddenly not working on my Windows 10 20H2 platform. Every action I take results in the same error message: C:\Users\ethan>npm internal/modules/cjs/loader.js:883 throw err; ^ Error: Canno ...

Conceal certain elements within the DOM depending on the $stateParams parameter in Ionic

I am currently developing an application that consists of three tabs: Home, Profile, and Settings. Within the "Home" tab, there is a list of items. Clicking on an item will navigate to a "Detail" section for that specific item, which includes various butt ...

The form in ReactJs is not functioning properly as it is not properly connected, despite containing only a

When attempting to create a form to add a new item into an array, I encountered the error message: Form submission cancelled because form is not connected. Despite finding some suggestions to change the submit button type from "submit" to "button", it did ...

What is the best way to display time instead of angles in highcharts?

Hey there! I'm currently working with highcharts and I have a polar chart where I want to display time on the y-axis instead of angles. Here's what I've tried so far: On the x-axis, I have angles and I've set tickInterval: 45,. How can ...

Clicking outside of a focused div does not trigger a jQuery function

Check out this HTML snippet: $html .= " <td><div class='edit_course' data-id='{$id}' data-type='_title' contenteditable='true'>{$obj->title}</div></td>"; Next, see the jQuery code below: ...

The integration of Laravel (Homestead) Sanctum is malfunctioning when combined with a standalone Vue application

After running the command php artisan serve my Laravel application successfully resolves on localhost:8000. I have configured Laravel Sanctum as follows: SESSION_DRIVER=cookie SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=localhost:8080 As for m ...

Java's equivalent to the return function in JavaScript

Currently, I am in the process of adapting three.js into Java while also incorporating my own modifications and enhancements. One specific challenge I am facing involves determining the best approach for managing reflection within the code. As part of thi ...

Can React components be saved in an array?

I am currently working on enhancing the code snippet provided below. This code is intended to iterate through elements of an array using keys to locate images within a lengthy SVG file directly embedded in the document under the identifier "SomelongUglySVG ...

Design a div in the shape of a trapezium with clipped overflow

Is there a way to create a trapezium using CSS/Html/Canvas? I have attempted to do so, but my current method is messy and not practical. div { width:0; margin-left:-1000px; height:100px; border-right:1000px solid lightblue; border-top:60px solid tra ...

Adding elements to a roster

Can anyone assist me with appending data from a csv file to an unordered HTML list? The csv file I have contains both single and grouped data for the list, as seen below: Test Group Name A,Test Link Name 1,Test URL 1 Test Group Name A,Test Link Name 2,Tes ...

The click function for the responsive navbar hamburger is not functioning properly

Having some trouble with the code not working in responsive mode. I've tested it on a 600px screen and the hamburger button doesn't seem to work (I click it and nothing happens). I've gone through both the CSS and JS multiple times but can&a ...

What other methods are available to verify null and assign a value?

Is there a more efficient approach for accomplishing this task? theTitle = responsesToUse[i]["Title"]; if(theTitle == null) theTitle = ""; ...

Is it possible to add animation to an SVG filter to create a captivating rotating planet with color effects?

I've added a filter to my self-created SVG and I'm interested in animating it so that the colors move diagonally, giving the appearance of a spinning planet. Below is the code featuring my SVG and how I'd like it to begin with the blue colo ...

Using jQuery within an Angular Controller: The specific function $(...).overhang is not recognized in this context

Recently, I decided to integrate overhang.js into my application because of its appealing alert messages. Initially, it seemed like a simple task... All I needed to do (or so I thought) was replace the line in my controller, alert("An HTTP request has be ...