Issues with Angular JS view not refreshing

I am currently experimenting with promises and AngularJS.

While my backend is returning the correct values, I am facing an issue where my HTML view does not display the table with the data from the backend.

What could be causing this problem?

Here is the snippet of my HTML code:

<div ng-app="clinang" ng-controller="pacientesCtrl">
     <a class='btn btnprimary' href='/getdadospac/?oper=S' >Button</a> 
     <table ng-table="tableParams" class="table" show-filter="true">
        <tr ng-repeat="paciente in $data">
            <td title="'Pront'" filter="{ name: 'text'}" sortable="'pront'">
                {{paciente.pront}}</td>
            <td title="'Nome'" filter="{ age: 'number'}" sortable="'nome'">
                {{paciente.nome}}</td>
        </tr>
    </table>
 </div>

Below is a sample of the JSON data returned by the backend:

{"draw":1,"recordsTotal":5303,"recordsFiltered":5303,
"data":[{"DT_RowId":"4367","pront":"4367","nome":"XXXXXXXXX","endereco":"RUA TEODORO DA SILVA,294\/314","bairro":"VILA ISABEL","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"2567*0440","cpf":"","email":""},
{"DT_RowId":"21","pront":"21","nome":"YYYYYYYYY","endereco":"R ARAGUAIA","bairro":"PARQUE CHUNO","cidade":"DUQUE DE CAXIAS","estado":"RJ","telefone":"35637685","cpf":"02570293709","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2888381878c8ba28b85cc818d8fcc8090">[email protected]</a>"},
{"DT_RowId":"23","pront":"23","nome":"ZZZZZZZZZZ","endereco":"rua 18 de outubro 241 101","bairro":"tijuca","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"","cpf":"","email":""},

... (continued data) ...

{"DT_RowId":"31","pront":"31","nome":"JOAO SDAFSA SOUZA","endereco":"av dom helder camara 312 bl 05 apt 102","bairro":"benfica","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"","cpf":"075422437-64","email":""},
{"DT_RowId":"33","pront":"33","nome":"SKDJFSDAJFLASD","endereco":"fabio da luz 275 bl 04 apt 504","bairro":"meier","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"3979-0859","cpf":"","email":""}]}

JavaScript Code Snippet:

var app = angular.module("clinang", ["ngTable", "ngResource"]);
            (function() {

              app.controller("pacientesCtrl", pacientesCtrl);
              pacientesCtrl.$inject = ["NgTableParams", "$resource"];

              function pacientesCtrl(NgTableParams, $resource) {
              
                // Uncomment the next line to debug using Chrome Dev Tools
                debugger;

                var Api = $resource("/getdadospac/?oper=S");
                this.tableParams = new NgTableParams({}, {
                  getData: function(params) {
                    // Making an AJAX request to API
                    return Api.get(params.url())
                      .$promise
                      .then(function(rows) {
                          params.total(rows.recordsTotal); // Re-calculating page navigation controls
                          return rows.data;
                    });
                  }
                });
                 this.tableParams.reload();
              }
            })();

Answer №1

You've got all the pieces - the controller, the call, everything - but now you just need to connect the controller's variable to the view using scope

    function patientsController(NgTableParams, $resource) {
      vm = this;
      vm.rows = []

      ..
      .then(function(rows) {
        vm.rows = rows.data;
       }

Next, in your HTML:

    <tr ng-repeat="patient in patientsController.rows">

If you want to level up your skills in Angular, consider diving into a good book. It really helped me progress as a developer after hitting some bumps along the way.

I also recommend checking out this interactive course:

Answer №2

It is important to choose between using ControllerAs syntax or $scope in your AngularJS application.

If you opt for ControllerAs syntax: Considering that the tableParams is being set on the controller instance, make sure to use ControllerAs syntax and assign an alias to the controller to access the property:

ng-controller="pacientesCtrl as ctrl" 
and also ng-table="ctrl.tableParams"

Alternatively, if you decide to go with $scope: In order to utilize $scope, you will need to inject $scope into your controller and assign the tableParams property to $scope like this:

var app = angular.module("clinang", ["ngTable", "ngResource"]);
        (function() {

          app.controller("pacientesCtrl", pacientesCtrl);
          pacientesCtrl.$inject = ["NgTableParams", "$resource", "$scope"];

          function pacientesCtrl(NgTableParams, $resource, $scope) {
            // tip: to debug, open chrome dev tools and uncomment the following line 
            debugger;

            var Api = $resource("/getdadospac/?oper=S");
            $scope.tableParams = new NgTableParams({}, {
              getData: function(params) {
                // ajax request to api
                return Api.get(params.url())
                  .$promise
                  .then(function(rows) {
                      params.total(rows.recordsTotal); // recal. page nav controls
                      return rows.data;
                });
              }
            });
            $scope.tableParams.reload();
          }
        })();

Keep in mind that in this case, the tableParams property is set on the $scope rather than the controller instance. Your HTML structure should remain unchanged.

While I personally prefer the ControllerAs syntax, both approaches are valid and should work effectively.

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

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

Fixing the Else part of the If Else statement for my JavaScript Toggle button issue in ASP.net-JavaScript application

I am fairly new to JavaScript and looking for some help. I have a button that I want to toggle its background color using if/else logic in JavaScript. My development environment includes ASP.net, C#, JavaScript, and VS2013 Express. The first part of my co ...

Is there a way to access the parent element within the javascript function of an asp:CustomValidator?

Is there a way to access the parent element in the asp:CustomValidator JavaScript function in order to verify if the associated checkbox has been selected? For instance: I'm faced with this code: <tr> <th class="gray ...

Steps for adding an HTML string to a div element using Ajax

I am facing some major challenges with Ajax, especially when it comes to appending HTML code to a div. I am attempting to append this HTML string to <div id="content-loader"></div> PHP function getLogo(){ $logo = '<div class="bg- ...

Please provide links to both the image and text within a Rails 3.1 application

Hey there! I have a small piece of code and I'm wondering how to add a link to both the icon and text. I am calling an icon from a class. Check out my code below: <td class="cv-class_<%= index + 1 %>"> <a onClick="ad ...

Why isn't the window.scrollTo function in Angular 2 working properly?

I am currently working on making a div element, set to "overflow:auto," scroll when a user is dragging an element. The dragging functionality is functioning correctly, and I am able to retrieve the necessary mouse data, such as the initial x/y position du ...

Tips for detecting the backspace key code in an Android browser using JavaScript?

I am faced with a challenge on my HTML JavaScript page... I have implemented a function to handle the keyup event in order to retrieve the key code. Specifically, when the key code is equal to 8 (backspace), a special action should be executed. However, up ...

What is the method for altering the rendered component?

I'm completely new to React.js and I'm in the process of creating changeable layouts using React.js. I attempted to utilize useState to render specific layouts upon clicking, but encountered an issue when adding setState within a function which r ...

What Causes the "Do Not Push Route with Duplicated Key" Error in React Native with Redux?

I have successfully integrated Redux into my React Native project, specifically for navigation purposes. Below is the code snippet from my navigation reducer file (navReducer.js): import { PUSH_ROUTE, POP_ROUTE } from '../Constants/ActionTypes' ...

How can JavaScript pass a variable through the URL?

I am attempting to pass a variable through the URL: http://localhost/new_wiki/test.php?id=http://example.com In my code, I have var first = getUrlVars()["id"];. This line is supposed to pass the value but it doesn't seem to be working. Can someone pl ...

Executing a separate function after each iteration of an ajax call within a loop using Jquery

I am faced with a situation where an ajax function must be run inside a loop that depends on the array's size. How can I execute another function after the ajax call is completed and outside the loop? Is this achievable? Below is the function: funct ...

Exploring the scope of the modalInstance received from ui-bootstrap's $modal.open() function

When preparing for a test, I am interested in creating a modal instance and then accessing its scope. Here is an example of what I would like to do: var modalInstance = $modal.open({ ... }) var scope = modalInstance.getScope() However, the modalInstance ...

Assistance required in utilizing Objective C to run Javascript for automatically populating web forms

I've been grappling with this issue for a while now and I can't seem to make any progress. As someone who isn't well-versed in JavaScript, I've scoured various forums and websites for a solution but to no avail. My current challenge in ...

Utilize JavaScript for labeling purposes

Currently, I am working on a WebGL project that involves plotting lines across the globe using three.js. While the plotting itself is functioning correctly, I am facing difficulties in labeling the points from where the plot starts and ends. If anyone coul ...

How can I increase the number of input boxes dynamically when clicking a button?

I am currently working on developing a checklist application, and I'm facing a challenge with the functionality. The user should be able to add items by clicking a button which opens input boxes for item name and quantity. While this initial part work ...

Issues with uploading multiple images in AngularJS

I am experiencing an issue with uploading multiple images on AngularJS. Below is my code along with the error I encountered. $scope.saveFile = function(file) { return Upload.upload({ url: CONFIG.apiUrl + '/fileupload', data: { fi ...

Display React component when clicked

As a newcomer to the world of React, I find myself intrigued by its potential. However, I am still in the process of grasping the fundamental concepts and would greatly appreciate any explanations provided. My goal is to display an 'About' compo ...

"Java is experiencing a memory overload issue, resulting in a Stack Overflow error

Struggling with implementing a Camel Route that calls a URL and converts the JSON Response into Pojo using Camel-Jackson. The connection is established with a status of 200, but encountering an issue: at com.fasterxml.jackson.databind.ser.BeanPropertyWri ...

I'm curious why my phone number is being treated as an object when it's passed in as a prop

I am facing an issue with my FooterScroll component while using it on the TvIndex main page. This is the FooterScroll Component const FooterScroll = (Id: number) => { const { event } = useEvent(Id); console.log('Id', Id); return ( ...

Authenticate through navigation on an alternate component

I am in the process of developing a user interface that includes a side navigation and header bar. However, if the user is not logged in, I wish to redirect them to the login page. The primary component structure is as follows: class App extends Componen ...