Changing the model does not automatically update the visibility of ng-show

I have a fragment of my view that simply displays a loading indicator.

Html:

<span class="app-loading-container">
    <span class="app-loading-animation" ng-show="loading"></span>
</span>

When I initially load the page, the span is visible. However, when I call my refresh method, the loading variable changes but the span does not show. Is there something I missed to trigger the span to display?

Controller:

app.controller('SavedSearchesCtrl', ['$scope', '$filter', '$window', 'lookupService', 'savedSearchesService', 
    function($scope, $filter, $window, lookupService, savedSearchesService) {


    $scope.loading = true;
    $scope.items = [];
    $scope.alerts = [];



    function getSavedSearches() {
        savedSearchesService.getSavedSearches()
            .success(function(data) {
                $scope.items = data;
                $scope.search();
            })
            .error(function(error) {
                $scope.alerts.push({ type: 'error', msg: 'Unable to load saved searches data: ' + error.message });
            });
            $scope.loading = false;
    }

    $scope.refreshClick = function () {
        $scope.loading = true;
        savedSearchesService.refreshSavedSearches()
            .success(function(data) {
                $scope.items = data;
                $scope.search();
                $scope.alerts.push({ type: 'success', msg: 'Successfully refreshed saved searches data.'}); 
            })
            .error(function(error) {
                $scope.alerts.push({ type: 'error', msg: 'Unable to refresh saved searches data: ' + error.message });
            });
            $scope.loading = false;
    };

    $scope.deleteClick = function(id) {
        if (confirm("Delete this search? There's no undo...")) {
            savedSearchesService.deleteSavedSearch(id)
                .success(function () {
                    for (var i = 0; i < $scope.items.length; i++) {
                        var savedSearch = $scope.items[i];
                        if (savedSearch.SavedSearchKey === id) {
                            $scope.items.splice(i, 1);
                            $scope.search();
                            $scope.alerts.push({ msg: "Deleted saved search! Refreshing list." });
                            break;
                        }
                    }
                })
                .error(function (error) {
                    $scope.alerts.push({ type: 'error', msg: 'Unable to delete saved search: ' + error.message });     
                });
        }
    };

    getSavedSearches();
}]);

I omitted some parts of the controller in this post, so it might not work if pasted directly into your IDE.

Thank you, Stephen

Answer №1

When dealing with asynchronous HTTP requests, it's important to handle the loading state properly. If you set $scope.loading = true; at the beginning of your function and then immediately set it back to false, it doesn't accurately reflect the status of the request.

$scope.refreshClick = function () {
    $scope.loading = true;
    // perform asynchronous task here
    // Upon success or error, change loading status accordingly
    $scope.loading = false; // This should be inside success or error callbacks
};

Instead of toggling the loading state instantly, it's better practice to update it within the success and error callbacks of the asynchronous operation. This ensures that the loading state is set correctly based on the outcome of the request.

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

"Unlocking the Power of Colormap in JavaScript: A Comprehensive

I am in need of incorporating a colormap into my JavaScript page. My server side is powered by Flask, written in Python. To render colormaps on the client side, I have a JavaScript file that requires the colormap module (installed using "npm install colorm ...

What could be causing me to receive an undefined output when trying to access an array stored within an object

let newData = await tripModel.find( { tripId: ID }, {salesOrder:1, no: "$deliveryDetails.invoiceNo", _id: 0 } ); let nullInvoices = []; console.log("vvvvvvv", newData[0].salesOrder); for (let i = 0; i < newData[0].no.length; i++) ...

Is there a way to verify the presence of data returned by an API?

I am trying to implement a system in my Index.vue where I need to check if my API request returns any data from the fetchData function. Once the data is fetched, I want to return either a boolean value or something else to my Index.vue. Additionally, I wou ...

The absence of a defined camera function in Cordova is causing the issue

I recently added camera functionality to my ionic-angular app and encountered an error stating "Camera is not defined." This issue arises when I run the command ionic serve, but it doesn't occur when using ionic browser. The same error occurs when dep ...

What is the best way to utilize "require" dynamically in JavaScript?

Within the "sample.js" file, there is a JavaScript function structured as follows: var mapDict = { '100': 'test_100.js', '200': 'test_200_API.js', '300': 'test_300_API.js' } function mapAPI() { ...

What could be the reason for the lack of rerendering in this child component?

Currently, I'm delving into ReactJS and attempting to grasp how child component rendering functions. To illustrate, consider the following example: var externalCounterVar = 10 class Counter extends React.Component { constructor(props){ super(pr ...

Navigate using Ui-Router or else utilize ng-admin

Currently, I am facing an issue in my angular application. I have integrated ng-admin to create a simple admin panel and also included Authentication features. My goal is to redirect the user to a login state when there is no active session. Upon integrat ...

How can we trigger a function once the API requests within a for loop have completed?

Within this for loop, a maximum of 'time' iterations are specified. With each iteration, a GET call is made to retrieve data that must be added to the obj object. I am seeking a method to determine when all 3 GETS have been completed along with ...

Issue with rendering Html Element on FireFox compared to Chrome

Having some trouble with an individual component (a simple dropzone) while testing on Firefox. It seems to work fine on Chrome, and the CSS looks good. Css .container { position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); wi ...

Update input box value using Javascript

Here is the code for a <script> tag on a webpage that includes an input box within the body of an HTML document- <script type="text/javascript" language="JavaScript"> window.onload = function addSearchText() { document.getElementB ...

Utilizing asynchronous programming for scenarios where two requests need to be sent, with the response from the first request being required for the second request

I have an async function that looks like this: exports.myFunction = async (req, res, next) => { if (some condition) { next() } try { const results = await axios.get(`https://a-domain.com/url/path`); const info = results.data; c ...

Prompt for confirmation in ASP.NET code-behind with conditions

I've searched around for a solution to this problem. Below is a representation of my pseudocode: bool hasData = ItemHasData(itemid); Confirm = "false"; // hidden variable if (hasData) { //Code to call confirm(message) returns "true" or "false" ...

AngularJS modal directives trigger a reset of $scope variables

I am developing a custom AngularJS application that needs to handle and store all the checkbox selections made by the user in a simple array of IDs. The functionality includes displaying a modal when the open button is clicked, allowing the user to perform ...

`Generating an ever-changing masonry layout on a website using live data`

I'm currently working on a new web project and I want to incorporate a masonry view for the images on the homepage. The plan is to host this project on Azure, using blob storage for all the images. My idea is to organize the images for the masonry vi ...

The radial gradient in d3.js does not properly affect paths

My goal is to create a radial gradient on my path element, but for some reason the radial gradient does not apply correctly. Can anyone help me troubleshoot this issue? Below is my updated code: // Define the canvas / graph dimensions var margin = {top: ...

Having issues with ASP.NET MVC AJAX PartialView not loading Telerik UI components

I am facing an issue with a PartialView that I update using AJAX. The HTML elements load correctly when updating the Div with AJAX, but the Telerik chart is not loading. The datasource in the chart does not call the Action method: .DataSource(ds => ds. ...

Retrieving JSON information from asynchronous JavaScript and XML (AJAX)

I am struggling with making a URL that contains JSON Data work properly. The issue lies in the data field - I am unsure of what to input here as it is currently undefined. My goal is to store an array of the JSON data received from the ajax request. What ...

Issue with Angular 6 where data is not binding to the UI on initialization

I am struggling with binding dynamic data to the UI and Data tables on my website. Despite trying various methods, I have not been able to achieve success. Currently, I am using the smart admin latest theme for development. When I make a call to the API, ...

Oops! There seems to be an error with the <path> attribute. It looks like we were expecting a number, but received something different: "

I'm currently working on creating a basic line graph using d3.js and integrating it into a React component. However, I'm encountering this error: Error: <path> attribute d: Expected number, "MNaN,36.393574100…" Unfortunately, the similar ...

What is the process for assigning a function and its arguments as a callback in programming?

Here is a code snippet for your consideration: $scope.delete=function(){ foo('x',3); }; How can we improve the clarity of this code snippet when the callback function contains only one line that calls another function? It's important ...