$ scope中的角JS执行函数$ timer接收到TypeError [英] Angular JS executing function $timer within $scope receives TypeError

查看:83
本文介绍了$ scope中的角JS执行函数$ timer接收到TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在Angular JS中使用$timeout时,内部函数如下所示,效果很好.

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

但是当我将$timer$scope内部的函数一起使用时,它将无法正常工作,像这样:

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

并收到此错误:

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

推荐答案

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

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

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.

这篇关于$ scope中的角JS执行函数$ timer接收到TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆