Reacting
Reacting

Reputation: 6123

AngularJS - how to show an alert when the length of an array is zero and hide the default behavior?

I am working with angular and I am showing a little loading circle which disappears once the content is loaded. that circle is just a CSS class that I am calling from my html only the 1st time that the page load, I am doing it this way:

actually the circle has to classes: .circle and .loader within circle ...

<div ng-hide="lineItems.length" class="circle">
 <div class="loader"></div>
</div>

as you can see below there is a promise with an if which says that if linesItems.length is zero then show myModal. everything is working properly but the loading circle still shows up, what I need to do is completely remove that .circle and .loader once the condition inside the if is reached.

.then(function(lines) {
  $scope.lineItems = lines;
  if ($scope.lineItems.length === 0) {
   myModal.show();
   console.log('I AMN EMPTY');
  }else {
   loaderAlert.hide();
  }
 }

someone says that I have to use an $scope variable but I do not have an idea of how to do it, I am new to Angular, is there any other way?

Upvotes: 1

Views: 313

Answers (1)

SoluableNonagon
SoluableNonagon

Reputation: 11755

When you start your promise, set a flag to state you are currently loading. Then when loading finishes, set the flag to false. Use this with ng-class or ng-if to make the appearance of the circle conditional.

function doStuff(){
    $scope.loadingIsHappening = true;
    myService.getStuff().then(function(){

       // your processing here

    }).finally(function(){
        $scope.loadingIsHappening = false;
    });
}

HTML:

 <!-- ng-if removes from DOM, while ng-hide modifies CSS display to none-->
<div ng-if="loadingIsHappening == true" class="circle">
    <div class="loader"></div>
</div>

Upvotes: 1

Related Questions