【问题标题】:Angular JS executing function $timer within $scope receives TypeErrorAngular JS 在 $scope 内执行函数 $timer 收到 TypeError
【发布时间】:2014-07-13 21:18:21
【问题描述】:

为什么在 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

【问题讨论】:

    标签: javascript angularjs timeout angularjs-scope


    【解决方案1】:
    var mytimeout = $timeout($scope.myFunction(),2000);
    

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

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 2021-03-28
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多