Angular JS在$ scope内执行函数$ timer接收TypeError

时间:2014-05-24 16:44:31

标签: javascript angularjs timeout angularjs-scope

为什么在Angular JS中使用$timeout时,如下所示在函数内部工作正常。

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

但是当$timer使用$scope内的函数时,它不起作用,如下所示:

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

并收到此错误:

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 个答案:

答案 0 :(得分:7)

var mytimeout = $timeout($scope.myFunction(),2000);

这是你的问题。从()中删除myFunction()。您需要传递函数引用,而不是调用函数并获取结果(在本例中为undefined),然后将 传递给$ timeout。