Search code examples
javascripthtmlangularjsprogress

Appropriate way to add progress circle in AngularJS


I am using AngularJS. I have a function in my controller that gets .json file from the server, working with data and store it in $scope.
So basically this function needs biggest amount of time when the page is loading.

So I have something like this, my page has loaded but but my table (that populates with ng-repeat) has not. It takes few seconds to load the table. And while the table is loading I want to add progress circle like that:

enter image description here

What is appropriate way to do it in AngularJS?

Here is a controller demo:

 var serverData = $http.get('data/topCarObj.json');
 function sortCars(){
    angular.forEach($scope.tabArray, function(tab){
        serverData.success(function(data){
            angular.forEach(data, function(key){
                ....
                return myCarList;
            });
        });
     });
}

Solution

  • In Controller:

    $scope.getData = function() {    // wrap a data getting code in a function
            $scope.loading = true;     // define a variable that indicate the loading status   // true here
            $http.get('path_to_json').success(function (data) {   // get the data 
                $scope.loading = false;     // loading is finished so loading = false
            })
            .error(function (data, status) {
                 $scope.loading = false;    // loading = false when there is a error
            });
    }
    
    $scope.getData();         // call the function to get data
    

    In View:

    <img src="loading.gif" ng-show="loading" /> // show the loading.gif when `$scope.loading` variable is `true`