0

I have a page where a user enters initial data, after that he clicks Calculate. And on click there should appear a gif-image with a loading spinner while the calculations are being made. As soon as the result is ready, the gif-image should disappear and the result should be displayed on the page. Here's the code I'm using:

$scope.loading=false; //initially the img is invisible    
$scope.calc=function(){
      $scope.loading=true;//make the img visible
      var result=MyService.calc(input_data); //processing data
      $scope.result=result;
      $scope.loading=false;//hide the img
}

And the HTML image is defined like so:

<div class="span1">
  <div ng-if="loading"><img ng-src="img/ajax-loader.gif"></div>
</div>

It's an expected order of things to happen. But in reality it works as follows: after clicking Calculate the image doesn't appear, and after some time during which calculations were made the image is shown and escaped.

The calculations are made in a service.

What's the problem? I already tried to make a $q.defer() in the service which resolves with result. And then in the controller display result inside the promise.then function. But it doesn't work.

Glen Selle
  • 3,966
  • 4
  • 37
  • 59

1 Answers1

1

Use $timeout for this. The model does not get updated in the middle of execution

JavaScript

$scope.calc=function(){
      $scope.loading=true;//make the img visible

      $timeout(function(){
          var result=MyService.calc(input_data); //processing data
          $scope.result=result;
          $scope.loading=false;//hide the img
      });
}

($timeout must be dependency-injected just like $scope)

Arg0n
  • 8,283
  • 2
  • 21
  • 38
  • I did as Arg0n advised. Now the order of things is right except that now the gif is showing without animation. It seems as its animation is stopped while service is doing work. What to do? P.S. The gif by itself is alright – Merim Aliaskarova Nov 25 '15 at 16:14
  • See this (or similar): http://stackoverflow.com/questions/191413/why-does-my-spinner-gif-stop-while-jquery-ajax-call-is-running – Arg0n Nov 25 '15 at 16:39
  • I cope with frozen animation like that: I replaced gif-animation with css animating. Thanks for quick reply. – Merim Aliaskarova Nov 25 '15 at 16:44
  • @MerimAliaskarova FYI, please don't post a new issue in the same question. If you have a new issue, ask a new question or edit your original question if it still pertains to the same issue. And if Arg0n's answer addressed the issue, please mark his answer by clicking the checkmark next to his answer so it goes green. Thanks! – Glen Selle Nov 25 '15 at 17:25