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

When state updates in React, the component will rerender without affecting its style

There seems to be a minor oversight on my part. The issue arises in the parent component where I maintain a state of selected items, which are added from the child component. The background color of the child component changes when an item is selected. Ad ...

Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component: <div class="form-group"> <label>{{l("RoomType")}}</label> <p-dropdown [disabled] = "!roomTypes.length" [options]= ...

Executing a function while adjusting a range slider

Having an <input type="range"> element on my website presents a particular challenge. To handle changes in this element, I am using the following function: $("#selector").bind("change", function() { //perform desire ...

What is the proper way to implement ng-click in a link call within a directive?

http://plnkr.co/edit/Ry8gkozAaudhlmdPPQie?p=preview In the plunkr example provided, I am experimenting with creating a directive that can display different templates based on the presence of attributes on the directive element. <my-dir></my-dir& ...

Having trouble getting CSS3 Keyframes to function properly?

Check out the following code snippet: .startanimation { height: 100px; width: 100px; background: yellow; -webkit-animation: animate 1s infinite; } @-webkit-keyframes animate { 100% { width: 300px; height: 300px; } ...

Encountering Datepicker Issue in Your Angularjs App?

I am currently working on a web application using Angular JS and I encountered an error when trying to incorporate a date picker. The error message displayed is "elem.datepicker is not a function" To implement the datepicker, I found reference code in thi ...

What could be the reason for my failing express test?

I'm in the process of configuring a server using Node/Express and I want to write ES6 code, so I've incorporated babel into my setup. Currently, the server is operational, and I can successfully make the necessary requests. However, I am facing ...

Is there a way I can ensure the values are loaded when the page loads, rather than displaying NaN?

I've recently created a car rental calculator for a client, and it's almost complete. Everything is working smoothly, from the calculations to the conditions. However, I'm facing an issue where the price isn't calculated on page load. I ...

Implementing the cryptocoins-icons npm package in your AngularJS application for enhanced icons

Currently in the process of creating a custom website using a template called blur-admin, which can be found at https://github.com/akveo/blur-admin Being new to npm, I decided to incorporate a npm package called cryptocoins-icons into my project. Followin ...

The concept of Puppeteer involves defining the browser and page in a synchronous manner

In the beginning of the Puppeteer tutorial, it is instructed to follow this code snippet: const puppeteer = require('puppeteer'); (async () => { await page.goto('https://example.com'); const browser = await puppeteer.launch ...

Using React and Material-UI: Implementing button functionality to call another class using hooks in the main App component

Just starting out with React/MUI and currently working on different components for a website, so the UI is not a priority at the moment. Encountering an issue when trying to create a button that links to the Sign Up page (similarly for Sign In): Error: ...

Transforming the date from JavaScript to the Swift JSON timeIntervalSinceReferenceDate structure

If I have a JavaScript date, what is the best way to convert it to match the format used in Swift JSON encoding? For example, how can I obtain a value of 620102769.132999 for a date like 2020-08-26 02:46:09? ...

Mongoose sparks a confrontation following the preservation of a single document in the database

I'm struggling to understand what minor mistake I'm making in this code. I have simplified the user schema to just one property, which is name. Initially, when I post the first entry to the database, it gets saved without any issues. However, whe ...

What criteria should I consider when selecting a JavaScript dependency framework?

When it comes to installing dependencies, how do I determine whether to use NPM or Bower? For example, what distinguishes npm install requirejs --save-dev from bower install requirejs --save-dev? Is there a recommended method, or any guidelines for makin ...

How to Determine If a String Represents an HTML Tag Using jQuery

Checking if a string is an HTML tag can be tricky. I've tried various methods found on Google, but none have been successful so far: var v = $(string).html() ? 1 : 0; --or---------------------------------------------- var htmlExpr = new RegExp("/^( ...

What is the way to utilize a scope variable within an ng-repeat filter?

I'm feeling a bit lost trying to navigate through this task with AngularJS. As a newbie to the framework, I'm struggling to find out how to achieve what I need. I have a group of users that I am looping through by using ng-repeat, but I can' ...

One simple click to auto-fill the form

I have encountered a problem that has been discussed before, but my lack of coding knowledge is making it difficult for me to find a suitable solution that matches the code on my website. The issue at hand is as follows: I need my form to populate car mak ...

Fetching a Wikipedia page using AJAX or the fetch() method

I am currently attempting to dynamically retrieve a Wikipedia webpage within the browser in order to utilize XSLTProcessor for further processing of the XHTML content. Unfortunately, my efforts have been unsuccessful as Wikipedia is not sending the necess ...

Incorporating a YouTube or Vimeo video while maintaining the proper aspect ratio

On my video page, I embed Vimeo videos dynamically with only the video ID. This causes issues with the aspect ratio as black bars appear on the sides due to the lack of width and height settings. The dynamic video ID is implemented like this: <iframe ...

Utilizing Docker to Deploy Nginx with Angular JS for Serving Static CSS, Images, and JS Files with Dynamic URL Paths

Our transition to Docker Containers is in progress for our legacy deployment. Each service will now run in separate containers, including Postgres, Redis, JobProcessor, LogProcessor, Nginx with Consul template, Consul, Registrator, Rabbitmq, and the Platfo ...