ps0604
ps0604

Reputation: 1081

How to use $timeout effectively in Angular?

I have the following code that doesn't work:

 $scope.function_A();
 $scope.function_B();

and this DOES work:

 $scope.function_A();
 $timeout(function(){
     $scope.function_B();
 }),100;

This is due to the fact that function_B refers to a directive that hasn't been created yet by Angular. I believe that's why using $timeout fixes the problem.

My issue is: how to be sure that the 100 millisecond timeout is correct and will always work? Is it better to somehow detect that function_A finished instead of using $timeout?

Upvotes: 0

Views: 69

Answers (2)

pkowalcze
pkowalcze

Reputation: 61

You can use Promises.

If you require function A to finish it's work, before calling function B, it is a good idea to make it return a promise. Some angular services have methods that already return a Promise, e.g. $http.get. By using $q you can prepare your own promises. For example:

$scope.function_A = function() {
  //function code
  return $q.when();
}

$scope.function_A().then(function() {
  $scope.function_B();
});

Read more about $q and Promises here

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41445

Use the callback mechanism

$scope.function_A(callback){
  // your implementation
  callback() // add it at the end
}

Now call function_B inside function_A

$scope.function_A(function(){
  $scope.function_B();
});

Upvotes: 1

Related Questions