`How can I display a view before an ajax request finishes in AngularJS?`

I am currently developing an iOS app using the Ionic framework with AngularJS. In my app, I have implemented the following routing example:

.state('app.friends', {
                        url: '/friends',
                        cache: false,
                        requireLogin: true,
                        views: {
                            'menuContent': {
                                templateUrl: 'templates/friends.html',
                                controller: 'friendsCtrl'
                            }
                        }
                    })

When loading the template friends.html, its corresponding controller is friendsCtrl. Within friendsCtrl, there is an Ajax function that calls an API to retrieve a list of friends in JSON format. The issue I am facing is that the template does not load in the view until the Ajax call is completed. Sometimes, especially with large data on the API, this process can take a long time. Therefore, I would like to display an empty view until the Ajax call is finished. While there are solutions available for completing the Ajax call before rendering the view, I specifically need guidance on how to render the view before the Ajax call completes. Any suggestions on how to achieve this would be greatly appreciated.

Thank you

Answer №1

To accomplish this, you have a couple of options. One way is to utilize the deferred object ($q) as shown in https://docs.angularjs.org/api/ng/service/$q

Another approach is to delay the loading process by using a timeout function ($timeout) - refer to https://docs.angularjs.org/api/ng/service/$timeout

EDIT

someFunc () {
    $scope.somevar = {};
    $http.get('url').then(
        function(response){
            $scope.someVar = response.data;
        });
    return $scope.somevar;      // returns {}
}

======================================

    someFunc () {
        var deferred = $q.defer();
        $http.get('url').then(
            function(response){
                $scope.someVar = response.data;
                deferred.resolve();
            });
        return deferred.promise;    // return a promise to set someVar
    }

    var $scope.somevar = {};
    someFunc().then(
        function() {
            console.log("somevar is set");
        });

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 preventing the value from changing in auth.guard?

I am encountering an issue with the variable loggined, which I modify using the logTog() method. When I call this method, a request is made to a service where the current result is passed to auth.guard. However, in the console, it displays "undefined". Can ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

Beginning your journey with Mock server and Grunt

Although I have gone through the documentation available at , I am still struggling to get the mockserver up and running despite spending hours on following the instructions provided in the guide. Could someone please outline the precise steps or identify ...

Leverage TypeScript Enum along with PropTypes to declare the properties of a React component

Upon having the Component and utilizing a TypeScript Interface for defining its props: interface Props { headerType: DROPDOWN_MENU_TYPE, //DROPDOWN_MENU_TYPE is enum headerContent: SVGClass isReverse: boolean; }; const MyComp: React.FunctionC ...

What is the best way to conceal the dt tag when the dd tag contains no value

Is there a way to hide the "Subject" if the "subject_title" field is empty? <dt class="col-sm-6 text-dark" >Subject</dt> <dd class="col-sm-6">{{$course_dtl->subject_title }}</dd> For example, I would li ...

Recognize when the DOM undergoes modifications

After taking Matt's suggestion, I have made changes to the .ready() call. In my workflow, I utilize jQuery to set up certain configurations like this: $(function () { $('.myThing').each(function() { ... configuring happens he ...

When utilizing $resource, Protractor experiences a timeout while trying to synchronize with the page

Currently, I am testing Protractor with a small AngularJS application. Here is the test scenario: describe('Testing Protractor', function() { var draftList; it('should count the number of drafts', function() { browser.get(&ap ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

Guide to sorting by two parameters in Angular

Is it possible to sort an angular table by two parameters? See the example below: 1-2 1-3 1-1 2-9 2-6 2-1 The desired output should be: 1-1 1-2 1-3 2-1 2-6 2-9 this.sortedData.sortingDataAccessor = (item, property) => { if (item[property]) { re ...

What is the best way to incorporate next and previous buttons into a jQuery slider using JavaScript?

I recently watched a tutorial on YouTube about creating a slider using jQuery (check it out here). The tutorial didn't include Previous and Next Buttons. I'm curious how to add Previous and Next Buttons to the Jquery Slider. Below is the code ...

javascript to retrieve data by reducing

Here is the code snippet I am working with: var points = 4; var yModifier = []; for (var i = 0; i <= points; i++) { yModifier.push([]); }; yModifier.forEach( (a, j) => { var start = j; var end = start + points; fo ...

Is there a way to organize this array based on the group score?

0: {id: 2575, groepName: "ezeez-1", groupScore: 50, Players: Array(0)} 1: {id: 2574, groepName: "ezeez-2", groupScore: 25, Players: Array(0)} 2: {id: 2576, groepName: "ezeez-3", groupScore: 10, Players: Array(0)} 3: {id: 2577, ...

Accessing UI elements from another class is a common task for developers

In a scenario where ViewController holds elements such as UIPickerView and two UITextFields. PickerViewController features implementations for UIPickerViewDelegate and UIPickerViewDataSource, including methods like didSelectRow and titleForRow. The issue ...

Ways to Retrieve the cell's imageView in the didSelectRowAtindexPath: Method

Having trouble implementing core animation for an UIImageView within a table view cell. Unsure of how to access the cell or the UIImageView. Currently developing in Swift 5. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> ...

iOS UITableView editable mode icons in the form of checkmarks and circles in SVG format

I am looking to customize the selected cell in a certain table using the edit mode, but the built-in options are limited. I typically use the built-in edit mode for other tables in my app and would like to incorporate the same checkmark and empty circle ic ...

Is Ajax failing to trigger?

I am experimenting with the jquery validator plugin and attempting to integrate AJAX for the first time. Below is the HTML code I currently have: <div class="grid_12" id="info"> </div> <div class="grid_12"> ...

“How can controllers from multiple modules be integrated into the markup using angular syntax?”

Here's this particular question on SO that suggests the possibility of utilizing controllers from different modules by defining specific tag attributes like: <div ng-controller="submodule1.controller1">{{ whatever1 }}</div> <div ng-con ...

Error: The function `this.xhr_.upload.addEventListener` is not supported in Firebase Storage

Having some trouble with file uploads. Small files work fine, but when it comes to larger ones I keep getting this error: this.xhr_.upload.addEventListener is not a function. I'm currently using vue.js along with the firebase 6.1.0 npm package. Th ...

Tips on adding a close button for a Modal View Form Sheet

Despite searching for similar questions, I have not been successful in adding an "X" button to the corner of a Form Sheet Modal View. You can see a perfect example of what I am trying to achieve in the screenshot HERE. I attempted to implement a UIButton ...

Send the response from Facebook to the flash callback on the external interface

I attempted to transfer the response from a Facebook API request obtained through the FB JS-SDK to my flash application using external interface. However, I am having trouble identifying the type of response as it displays [object object] when printed in t ...