How to set the value of scope variable flag when all the API is complete?

Viewed 164

I have 5 widgets on my dashboard and I am making a separate call to get the data for each of those widgets.

I have a structure like below :

<div>
   <div id="widget1">
      --Widget 1 data
   </div>     
   <div id="widget2">
      --Widget 2 data
   </div>     
   <div id="widget3">
      --Widget 3 data
   </div>
   <div id="widget4">
      --Widget 4 data
   </div>
   <div id="widget5">
      --Widget 5 data
   </div>
</div>

On the angular front, I have scope variables for each of the widget which is updated based on API start and end:

$scope.dataLoadedForWidget1 = true; 
$scope.dataLoadedForWidget2 = true; 
$scope.dataLoadedForWidget3 = true; 
$scope.dataLoadedForWidget4 = true; 
$scope.dataLoadedForWidget5 = true; 

$scope.showEntireDiv = true; 

I have a directive that works on the True/False value to grey out the entire div.

<div isloaded="showEntireDiv">

But my question is since I have individual API, where do I set the value of $scope.showEntireDiv ?

How do I make sure to set the value of $scope.showEntireDiv only after the API call is complete?

Updated:

$scope.getEmployees = function () { //callback function 1
                myService.getEmployeeData().success(function (data) {
                $scope.employees= data.response;
                }).finally(function () {
                });
            };
1 Answers

You can map all the requests into a promise array and use $q.all() to display the content after all the promises resolve.

Simplified version using ng-show and ng-repeat:

angular.module('myApp',[])
.controller('myCtrl',['$http','$q', function($http, $q){
  const getUser = (id) =>{
     return $http.get(`https://jsonplaceholder.typicode.com/users/${id}`).then(res=>res.data)
  }
  // create array of request promises
  const reqPromises = [1,3,5].map(getUser)
  
  $q.all(reqPromises).then(users=>{     
    this.users = users;
    // allow users to show after all requests resolve
    this.allLoaded = true;    
  });
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as $ctrl">
  <h3 ng-hide="$ctrl.allLoaded">Loading...</h3>
  <div ng-show="$ctrl.allLoaded">
      <h3>Users List</h3>
     <div ng-repeat="user in $ctrl.users">Name: {{user.name}}, ID: {{user.id}}</div>
  </div>
</div>

Related