Krishna Karki
Krishna Karki

Reputation: 797

How to load view before ajax completes on Angular Js?

I m building an ios app using Ionic framework which is in Angular Js. In my app following my routing example

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

Here i m loading a template friends.html and its controller is friendsCtrl. In friendsCtrl i have an ajax function which calls api and gets list of the friend in json format. The problem i m having is my template doesn't load in the view until ajax is completed. Sometime when there is big data on api it take very long. So i want to show empty view until ajax is completed. I saw many questions and answers about completing ajax before view rendering but in my case i want to render view before ajax complete. How to do this please suggest me.

Thanks

Upvotes: 1

Views: 220

Answers (1)

Justice O.
Justice O.

Reputation: 1313

You can use a the deferred object ($q) to achieve this, see https://docs.angularjs.org/api/ng/service/$q

Alternatively, you can force the loading to happen at a later time by wrapping it around a timeout function ($timeout) - see 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");
        });

Upvotes: 1

Related Questions