broersa broersa - 5 months ago 202
AngularJS Question

Can ng-show directive be used with a delay

I have a spinner this is shown with

ng-show="loading>0"


Is there a way I can display this spinner with a delay (say 1 second)?

I can't use a timeout because with multiple requests de loading counter will get out of sync.

What I need is a delay on the
ng-show
via css transition or similar

Answer

Here's a simpler approach that worked for my needs. Depending on what your action is, you would tie function setDelay() to the element. For example, in my case I tied setDelay() to a select input.

Trigger HTML:

<select class="first-option"
    ng-change="setDelay()" 
    ng-options="o.label for o in download.options" 
    ng-model="optionModel" required>
</select>

In your controller, add a simple function setDelay that will change the flag $scope.delay:

$scope.setDelay = function(){
    $scope.delay = true;
    $timeout(function(){
        $scope.delay = false;
    }, 200);
};

Then, you can simply use $scope.delay as a flag in ng-show:

<div class="loading-div" ng-show="delay">
    <img src="loading_spinner.gif">
</div>

And show content after done loading:

<div ng-show="!delay">
    Content is loaded.
</div>

Now, every time the user selects a new value in the dropdown menu, it will trigger$scope.delay to be set totrue causing the spinner to show, and when it reaches 200, it will be set to false causing the spinner to hide.

Comments