"Showing a loading view in AngularJS while waiting for JSON data to

Apologies for any language errors. I am facing an issue with AngularJS. When making an HTTP POST request, I receive data from MySQL in JSON format.

app.controller('DeviceActivityCtrl', function ($scope, $rootScope, $location, $http, Data,$stateParams,DeviceActivityResult) {

    //$scope.foodDistribution=null;

    if (DeviceActivityResult.status == "success") {
        $scope.deviceActivityLog = DeviceActivityResult;
        $scope.authError = 'Correct';
        alert(DeviceActivityResult.data[0].steps);
    }
    else {
        $scope.authError = 'notsuccess';
    }


});

The problem arises when the view (HTML) is loaded before the HTTP request is completed, causing the HTML to fail to load as the data is not yet ready. How can I delay the loading of the view (HTML) until the JSON data retrieval process is complete? Thank you for your assistance.

<div class="inline">
                <div ui-jq="easyPieChart" ui-options="{
                  percent: ({{deviceActivityLog.data[0].activity_time}}/340)*100,
                  lineWidth: 10,
                  trackColor: '{{app.color.light}}',
                  barColor: '{{app.color.success}}',
                  scaleColor: '{{app.color.light}}',
                  size: 188,
                  lineCap: 'butt'
                }">
                    <div>
                        <span class="h2 m-l-sm step">{{(deviceActivityLog.data[0].activity_time/340)*100|number:0}}</span>%
                        <div class="text text-sm"></div>
                    </div>
                </div>
            </div>

----------------state---------------

.state('report.food', {
                url: '/{userid:[0-9]{1,4}}',
                templateUrl: 'tpl/report_food.html',
                controller: 'DeviceActivityCtrl',
                resolve: {
                    deps: ['$ocLazyLoad',
                        function ($ocLazyLoad) {
                            return $ocLazyLoad.load('ui.grid').then(
                                function () {
                                    return $ocLazyLoad.load('js/app/report/reportFood.js','UiGridDemoCtrl.resolve');
                                }
                            );
                        },
                    ],
                    DeviceActivityResult: function(Data, $stateParams) {
                        return Data.post('deviceActivity',
                            {userid: $stateParams.userid}
                        );
                    }
                }
            })

Answer №1

If you are utilizing ui-router, it is recommended to resolve the state data prior to transitioning into it. Here's a sample implementation on how you can achieve this:

.state('yourState', {
    ...
    controller: 'DeviceActivityCtrl',
    resolve: {
        DeviceActivityResult: function(Data, $stateParams) {
            return Data.post('deviceActivity',
                {userid:$stateParams.userid}
              );
        }
    }
})


.controller('DeviceActivityCtrl', function ($scope, $rootScope, $location, $http, DeviceActivityResult) {
    //   Data.toast(DeviceActivityResult);
    if (DeviceActivityResult.status == "success") {
        $scope.deviceActivityLog = DeviceActivityResult;
        $scope.authError = 'Correct';
    }
    else {
        $scope.authError = 'notsuccess';
    }
});

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

Trouble arises when attempting to delete rows from my database with the use of HTML, PHP, and

I am developing an application where I have implemented this table: <?php require_once 'Connect2db3.php'; ?> <form> <fieldset> <article class="rondehoeken"> <header> <div class="streep1"></div& ...

Having trouble with Vue.js not returning HTML elements from methods properly?

I have been attempting to retrieve html elements from a method, and I thought of using v-html for this purpose (not sure if there is a better approach). However, I seem to have encountered an issue with backtick templates and string interpolation. An error ...

Angular 6 is showcasing dates in a quirky manner

In my Angular app, users can enter comments. The comments are displayed automatically with the date they were added. However, there is an odd behavior that I've noticed: When a user enters a comment, the time displayed is incorrect. (Check the ...

How to effectively manage multiple stylesheet links in React Native Expo development

Hello, my name is Antika. I recently embarked on a coding journey and have been focusing on learning HTML/CSS/JS along with the basics of React. As a beginner developer, my current project involves creating a Study planner app for myself using React Native ...

When an image is loaded, the getImageData function may return some zero values

I am currently working on a task that involves loading a PNG image and checking to see if it is fully opaque, meaning the alpha channel has near 100% coverage across the entire image. To achieve this, I am using a canvas and 2D Context to extract pixel dat ...

Tips for comparing props in the ComponentDidUpdate method when dealing with a complex data structure that is connected to Redux

I have been experimenting with the new lifecycles of React v16. It works perfectly fine when comparing single keys. However, when dealing with large data structures like Arrays of objects, performing deep comparison can be quite expensive. My specific sce ...

Having trouble retrieving response content in Mithril

I've been experimenting with making a request to a NodeJS API using the Mithril framework in my client application. I attempted to fetch data by following their example code: var Model = { getAll: function() { return m.request({method: "G ...

Transfer the information from dropped files in a div to a separate page

document.getElementById('drag_drop').ondrop = function(event) { event.preventDefault(); var form_data = new FormData(); var drop_files = event.dataTransfer.files; for(var count = 0; count < drop_files.length; count++) ...

Using JavaScript variables within an @if statement in Laravel within the innerHTML segment

How can I incorporate a JavaScript variable 'x' into an @if statement in Laravel? I have tried placing it both inside and outside of the @if statement. When placed outside, it works perfectly fine, but I really need to perform an action based on ...

In C#, how can the HTMLAgilityPack be utilized to extract a value from within a script tag?

I'm currently working with HTMLAgilityPack and I need to extract a value from a script tag. Here is the code: <div id="frmSeller" method="post" name="frmSeller"> <div class="clear"></div> <script type="text/javascript" language=" ...

What is the best way to implement a header and footer with AngularJS?

When working on my projects, I usually use the jQuery "load" method to insert the header and footer into all pages. The code below demonstrates this. Now I am wondering how I can achieve the same result using AngularJS. $("header").load("includes/heade ...

Loading jQuery on an ajax request

The loader is working with the code now, but it is not replacing and calling the URL. The ajax url call should be placed within searchable. <button onclick="myFunction()">LOAD</button><br /><br /> <div class="spinner bar hide" ...

What is the best way to save and retrieve a File object using local storage?

I've developed an HTML5/javscript application that utilizes the following code snippet to capture a camera image: <input type="file" accept="image/*;capture=camera" onchange="gotPhoto(this)"> As my application needs to function offline, I&apos ...

Steps for saving a JSON file output from a Docker container using a Python script

Being a newcomer to docker, I am currently working on a python script that takes multiple input csv files and generates a json output. The DockerFile I am using is as follows: FROM python:3.9 WORKDIR /usr/workdir COPY requirements.txt ./ RUN pip instal ...

Tips on sharing JSON data with another view controller

Hey everyone, I have received some data from the server: { error = 0; "error_msg" = "Successfully Login"; success = 1; user = { DriverID = 35; DriverName = "Home Nath"; "com_id" = 2; }; } Now, I want to transfer the data of the Dr ...

Using Struts2 to fetch data through AJAX and dynamically update a div element

Looking for advice on how to trigger an action class using JavaScript when a value is selected from a drop-down menu. The goal is to fetch data from a database and then update a table within a specific div without refreshing the entire page. The drop-down ...

What is the best way to incorporate "?param=X" into a route in Node.js?

Within my nodejs and "express" project, I have implemented the following code snippet: app.get("/:page?", function (req, res) { var pg = req.params.page; This code is designed to work with URLs such as localhost:123 or localhost:123/3. However, I am s ...

Guide to accessing the content within an h1 tag with JavaScript

I currently have a setup with 3 pages: 2 of them are WordPress pages while the other page is a custom page template featuring a form. The first two pages were created using the wp-job manager plugin. The first page includes a dropdown menu with a list of a ...

Using jQuery to dynamically include option groups and options in a select box

Generate option groups and options dynamically using data retrieved via AJAX. <select name="catsndogs"> <optgroup label="Cats"> <option>Tiger</option> <option>Leopard</option> <option>Ly ...

Iterate over an array of objects to showcase the property values within an HTML tag using JavaScript

I am a beginner in JavaScript and I am currently working on an exercise. My goal is to iterate through an array of objects within another object, map the index values from one object to the id values in another object, and based on that, perform a certain ...