Nagy Ervin
Nagy Ervin

Reputation: 701

AngularJS asynchronous function call

How to call a function asynchronously inside an Angular controller? I'v read about promises, but this in not a http call so i can't use that. Is there any solution to resolve these kind of problems? I would like to display a spiner/loader until the called function finishing it's job.

//Controller JS

   $scope.myFunctionCallOnClick = function()
   {
            if($scope.type=='TYPE1')
            {

               $scope.showSpiner();
              //This function has called syncronously, and i can't display my spiner
                Utils.doStuff(words,$scope);
                $scope.hideSpiner();
            }
            else
            {
                Utils.doStuff2(words,$scope);
            }
    }

//Utils.js - this is my helper factory

angular.module('app').factory('Utils', function() {
    var factory = {}; 
    ..
    .. 

    factory.doStuff = function()
    {
        var iteration = 10000000;
        whilte(iteration > 0)
        {
          console.log(iteration);
        }

    }
      ..
      ..
       return factory;
});

Upvotes: 0

Views: 104

Answers (2)

Prashant
Prashant

Reputation: 8040

Use $timeout service to let the browser do some of its work (show your spinner in this case), and call doStuff from within the $timeout callback.

$scope.myFunctionCallOnClick = function () {
    if ($scope.type == 'TYPE1') {

        $scope.showSpiner();

        $timeout(function () {
            Utils.doStuff(words, $scope);

            $scope.hideSpiner();
        });

    }
    else {
        Utils.doStuff2(words, $scope);
    }
}

Upvotes: 1

harishr
harishr

Reputation: 18055

you can use $timeout to call a function asynchronously

$timeout(function(){

      /// function logic    

}, 0);

similarly you can even use.. $evalAsync

read more about them here

Upvotes: 0

Related Questions