Angular JS executing function $timer within $scope receives TypeError

喜夏-厌秋 提交于 2019-12-11 11:22:12

问题


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:


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.



来源:https://stackoverflow.com/questions/23847430/angular-js-executing-function-timer-within-scope-receives-typeerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!