AngularJS view fails to update after modification to model

Utilizing Angular, I am populating a table with data that is loaded asynchronously from JSON using $http. There is also a date-picker feature which, when a new date is selected, should display the data for that specific date. However, even though the new data is successfully loaded, the view does not refresh. Here is an abridged version of my code:

<tbody>
    <tr ng-repeat="row in tableKPI"> 
        <td ng-repeat="index in tableKPIColsInt">{{ row[index]}}</td>
        <td ng-repeat="index in tableKPIColsFloat">{{ row[index] | number:2}}</td>
    </tr>
</tbody>

In this code snippet, tableKPIColsInt and Float are simply lists of strings containing column names.

loadDailyDataFromJSON = function ($plantName,$http,$scope,$timeout) {

    var formattedDate = dateFormat($scope.selectedDate,"yyyy-mm-dd");

    $http.get("json/"+formattedDate+".json")
    .then(function (response) {
        $scope.tableKPI = response.data[$plantName];
    },
    function(error) {
        $scope.tableKPI = {};
        console.log("No data for KPI for "+formattedDate);
    });

    // Attempted to use $apply as well
    $timeout(function() { $scope.$apply();}, 500);
};

Below is the controller:

app.controller("tableController", function($scope,$routeParams,$rootScope,$http,$timeout){
    $scope.tableKPI = {};
    $scope.reloadData = function(){
        loadDailyDataFromJSON($rootScope.currentPlant, $http, $scope, $timeout);
    };

}

The issue arises after the initial page load - subsequent changes to the date result in the correct loading of new data, but the view does not update accordingly. Attempts to resolve this through $scope.$apply() or calling $apply() after a timeout have proven unsuccessful, yielding errors such as "digest already in progress...". Even structuring the code differently by moving the function elsewhere did not solve the problem.

It is possible that the issue lies within the model itself. The nested loops and iteration over rows and string indexes may be causing complications. Including the code below while specifying the controller has not resulted in any changes:

<tbody ng-controller="dailyCtrl as dc">
    <tr ng-repeat="row in dc.tableImbalance"> 
        <td ng-model="row[index]" ng-repeat="index in dc.tableImbalanceCols" ng-bind-html="row[index].toString()"></td> 
    </tr>
</tbody>

Answer №1

Revise it in this manner

 app.controller("tableController", function($scope,$routeParams,$rootScope,$http,$timeout){
    $scope.tableKPI = {};
    $scope.reloadData = function(){
        loadDailyDataFromJSON($rootScope.currentPlant,);
    };


  // assuming the function is in same file as controller 
    loadDailyDataFromJSON = function ($plantName) {

        var formattedDate = dateFormat($scope.selectedDate,"yyyy-mm-dd");

        $http.get("json/"+formattedDate+".json")
        .then(function (response) {
            $scope.tableKPI = response.data[$plantName];
        },
        function(error) {
            $scope.tableKPI = {};
            console.log("No data for KPI for "+formattedDate);
        });

    };

}

Alternatively, if you prefer a service-oriented approach

app.service("testService", function($http){

 this.loadDailyDataFromJSON = function ($username) {

     var endpoint = "rooturl"+"json/"+formattedDate+".json";
      return $http({
        method: 'get',
        url: endpoint 
      });
    };

}

Then in the controller

 app.controller("tableController", function($scope,$routeParams,$rootScope,testService{
        $scope.tableKPI = {};
        $scope.reloadData = function(){
            var formattedDate = dateFormat($scope.selectedDate,"yyyy-mm-dd");

            testService.loadDailyDataFromJSON (formattedDate)
            .then(function (response) {
                $scope.tableKPI = response.data[$plantName];
            },
            function(error) {
                $scope.tableKPI = {};
                console.log("No data for KPI for "+formattedDate);
            });
        };


    }

If formattedDate is not null and you have used the correct rooturl, then this will work flawlessly

Answer №2

When utilizing the $http service, there is no need for $timeout or $scope.$apply. The functionality is already integrated into the $http service.

It's important to ensure that your controller is being used correctly.

Here is an example using your code:

http://jsfiddle.net/jgyombzg/5/

After clicking Reload, you will see the updated data.

[UPDATED]

Based on the recent question update, it seems that the issue may involve the use of ng-bind-html. Visit the fiddle again to observe 2 instances of ng-repeat.

  • In the first case, I simply utilized ng-bind
  • In the second case, I employed ng-bind-html

The second case appears empty upon inspection.

Could you attempt the same? If the result remains unchanged, consider exploring $sce for assistance.

Answer №3

To optimize your code, consider encapsulating loadDailyDataFromJSON within an Angular service and injecting it into your controller for seamless integration. In my own application, I have adopted this approach successfully without the need for additional apply functions.

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

What is the process for configuring a headless implementation of three.js on a node server, similar to the babylon.js-NulEngine setup?

My current project involves the development of a multiplayer three.js fps game, with client-side prediction in the browser. For the server-side implementation, I am utilizing Node.js Express.js and Socket.io for handling authoritative functions such as col ...

Implementing React and Material UI - Customizing Navigation Buttons/Links according to Routes

The following code snippet represents the main entry point of a React app, app.js, which includes the router endpoints. Below the app.js code, you will find the code for a Nav component, which serves as the navigation menu. I am looking to structure this ...

Vue.js Applications tend to encounter Expected Errors originating from JavaScript

I've been diving into learning Vue.js using Visual Studio 2017. Currently, my goal is to create applications with multiple buttons that trigger the display of a message upon being clicked. However, when I attempt to run this code, I encounter the foll ...

The creation of an indexedDB database and the addition of content encountered an error while trying to perform a 'transaction' on the IDBDatabase

I am relatively new to using IndexedDB and have successfully created a database. However, I am encountering an error when trying to add content to it. The specific error message reads: Uncaught NotFoundError: Failed to execute 'transaction' on ...

Strange behavior noticed in the app.get() method of Node.js Express

Seeking clarification regarding the behavior of app.get() in Express. It appears that the function is not triggered when the path includes .html at the end. In the code snippet provided, the console logs "test" if attempting to access /random/example, bu ...

What could be causing the React state (array) to be empty within a callback function? Why is it failing to utilize the latest value from the external

I'm facing a challenge that has me stumped. I am attempting to add values to an existing array, but for some reason, the 'state' variable is always empty inside the onmessage callback function. I can't seem to figure out why this is hap ...

Storing HTML, JavaScript, and CSS files using HTML5 local storage: A comprehensive guide!

Could you provide guidance on how to store HTML, JavaScript, and CSS files in HTML5 local storage? I am looking to optimize the speed of my web application! Thank you! ...

Unable to retrieve DateTime.Now as a string within a Razor view

I am trying to retrieve the current time in a Razor View and utilize it in JavaScript, as demonstrated below: @{ string fileName = "Score_List_" + DateTime.Now.ToShortDateString(); } <script> // assigning C# variable to JavaScript variabl ...

What is the best way to reuse the SELECT form multiple times?

Currently, I have an HTML page with a table containing 6 columns and around 70 rows. In column 3, I have a SELECT drop-down list in all rows with the same options. While I am familiar with C# and Java, where I can create a class and reuse it, I am fairly n ...

Tips for saving variable state using closure

I am working on a function that needs to be called multiple times, and this function will add elements to my HTML: class MyClass { addElements(elements) { const parentElement = $("#parent").find("#other-element"); for (let element of elements) ...

Halting a function within a specific namespace

Is there a way to prevent certain characters from being entered during a keypress event for inputs when using a namespace in JavaScript? I noticed that even if the function returns false when the character is detected, the character still gets entered. How ...

Make sure that the TextBox OnTextChanged event in ASP.NET triggers a "setTimeout" function before the OnClick event is fired

Imagine the following situation: <asp:TextBox ID="txt" runat="server" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox> <asp:Button ID="btn" runat="server" OnClick="btn_Click" CausesValidation="false" UseSubmitBehavior="fal ...

Ways to access the specified variable in JavaScript

How can I get to the header of a variable? For example, in the Redux Framework WordPress plugin, there is a variable [redux.args.opt_name]. How do I find the define line for this variable? Another Question: What does the use of two single quotes in the &a ...

Develop a real-time streaming service using AngularJS

I am looking to develop a website that pulls information from multiple APIs and presents it in a user-friendly format. Since I wanted to experiment with AngularJS, I opted to use it for this particular project. However, I am struggling with figuring out h ...

Obtain the HTML of a Vue component and transmit it using an ajax POST request

I need to send an email with an HTML body using only ajax since I don't have access to the server code. Fortunately, the server has an API for sending emails. Currently, I have a dynamically rendered component called invoiceEmail. sendEmail () { ...

Having trouble getting NPM environment variables to function properly on a Windows system?

I have a confusion in my package.json file where I am attempting to compile less code using versioning. Here is an example of what I am trying to achieve: "scripts" { ... "build:css": "lessc --source-map css/index.less build/$npm_package_name.$npm_package ...

Angular JS Error - $injector:modulerr: Module Not Found

Attempting to preview an angular application on a local server using npm, bower, and grunt. The code being used is identical to what a colleague is successfully running from a cloned repository. However, while they can view the full app without issues, I e ...

Next.js - NextAuth consistently delivers a successful status code every time

In my Next.js project, I am utilizing NextAuth. The issue I'm encountering is that NextAuth consistently returns a 200 status code and updates the session to authenticated, even when the username or password doesn't match. I've attempted thr ...

What is the best way to ensure a textarea remains expanded when the parent element is in focus?

I have successfully implemented a textarea box that expands upon click and retracts when it loses focus. However, I am facing an issue where if the textbox is already in expanded form, I want it to stay expanded if the user clicks anywhere within the cont ...

Utilizing Angular to Display Attachments from Domino Data Service

When retrieving a Domino Document using the /api/data/documents/unid/ syntax, I noticed that the attachment comes back encoded in base64 like this: "contentType": "application/octet-stream; name=\"Spitzbuben.docx\"", I am now looking for the be ...