cmgchess
cmgchess

Reputation: 10247

Angular.js unable to change scope variable value just after a different function call

I'm trying to implement a Refresh button for fetching latest search results from an external index. When I click on the Refresh button the icon is supposed to spin. My plan was to have a scope variable for deciding if the icon should spin or not. For that I'm using a variable called $scope.refreshing

My view

<button class="refresh-button" ng-click="refresh()">
    <i class="fa fa-refresh ng-scope" ng-class="{'fa-spin': refreshing.state}" aria-hidden="true"></i>
         Refresh
</button>

My controller

      $scope.refreshing ={state: false};
      $scope.refresh = function(){
        $scope.refreshing.state = true;
        $scope.search();
        $scope.refreshing.state = false;
      }

The $scope.search() sends an HTTP request to a server and displays the new results. But I'm having the problem such that the $scope.refreshing variable change doesn't happen sequentially such that it becomes false only after calling the search function due to the asynchronous nature. Because of that the icon doesn't spin.

Actual
enter image description here
Expected
enter image description here

Would it be possible to perform this without doing any changes to the search() function.

Upvotes: 0

Views: 95519

Answers (1)

Kinglish
Kinglish

Reputation: 23654

This is most likely because angular isn't refreshing the digest quickly enough. You can give it a 'nudge' with $timeout (and there are other methods as well). Something like

  $scope.refreshing ={state: false};
  $scope.refresh = function(){
    $scope.refreshing.state = true;
    $timeout( function() {
       $scope.search();
       $scope.refreshing.state = false;
    }, 100)
  }

Of course, you'll need to include $timeout as a dependency in your controller/directive whatever.

Upvotes: 1

Related Questions