Angular JS executing function $timer within $scope

2019-07-26 05:32发布

Why is that when using $timeout in Angular JS that is inside function like the following, works fine.

var mytimeout = $timeout(function(){
    console.log("MyTimeout Executed");
},2000);
mytimeout.then(
    function() {
        console.log( "mytimeout resolved!", Date.now() );
    },
    function() {
        console.log( "mytimeout rejected!", Date.now() );
    }
);

but when I use $timer with a function inside $scope it does not work, like this:

$scope.myFunction = function(){
   console.log("MyTimeout Executed");
}; 

var mytimeout = $timeout($scope.myFunction(),2000);
mytimeout.then(
    function() {
        console.log( "mytimeout resolved!", Date.now() );
    },
    function() {
        console.log( "mytimeout rejected!", Date.now() );
    }
);

and recieve this error:

TypeError: undefined is not a function
    at http://0.0.0.0:3000/assets/angular.js?body=1:14015:28
    at completeOutstandingRequest (http://0.0.0.0:3000/assets/angular.js?body=1:4301:10)
    at http://0.0.0.0:3000/assets/angular.js?body=1:4602:7 angular.js?body=1:9779
(anonymous function) angular.js?body=1:9779
(anonymous function) angular.js?body=1:7217
(anonymous function) angular.js?body=1:14018
completeOutstandingRequest angular.js?body=1:4301
(anonymous function) angular.js?body=1:4602

1条回答
闹够了就滚
2楼-- · 2019-07-26 05:52
var mytimeout = $timeout($scope.myFunction(),2000);

This is your problem. Remove the () from the myFunction(). You need to pass a function reference, not call the function and take the result (which in this case would be undefined) and then pass that to $timeout.

查看更多
登录 后发表回答