0

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;
});

2 Answers 2

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.