Rodrigo Sasaki
Rodrigo Sasaki

Reputation: 7236

how to invoke a method in the scope using $timeout

I'm attempting to use $timeout to invoke one function that I have, but I don't know how to invoke a function that is in the $scope. Let me exemplify

I have this:

$scope.play = function(){    
    // function implementation
    if(condition()){
        $timeout(play, 1000);
    }
}

it doesn't recognize the play function, I have also tried this

$timeout($scope.play, 1000);

and it also doesn't work. I had to work around it like this:

var play = function(){
    $scope.playInner();
}

$scope.playInner = function(){    
    // function implementation
    if(condition()){
        $timeout(play, 1000);
    }
}

But I'm sure there's a better way to do this, does anyone know how I can do that?

Upvotes: 0

Views: 39

Answers (1)

Alex Choroshin
Alex Choroshin

Reputation: 6187

as JB Nizet suggested, $timeout($scope.play, 1000) should work fine.

Example:

function ctrl($scope,$timeout){
    $scope.data=0;
    $scope.play=function(){
        $scope.data++;
        $timeout($scope.play,1000);
    }    

}

Live example: http://jsfiddle.net/choroshin/wF8SZ/

Upvotes: 2

Related Questions