2013-04-29 109 views
2

我正在尝试使用Angularjs的简单http应用程序。 我的代码是AngularJS undefined不是函数

var studentApp = angular.module('studentApp',['ui.bootstrap']); 
studentApp.factory('studentSession', function($http){ 
    return { 
     getSessions: function() { 
      return $http.post('/services', { 
       type : 'getSource', 
       ID : 'TP001' 
      }); 
     } 
    } 
}); 

studentApp.controller('studentMenu',function($scope, studentSession){ 
    studentSession.getSessions().success($scope.handleSuccess); 
    $scope.handleSuccess = function(data, status) { 
     console.log(data); 
    }; 
}); 

在尝试上面的代码运行,我得到的错误Undefined is not a function铬。通过stackoverflow搜索推荐的解决方案是为功能提供范围。即使在对函数进行作用域后,错误仍然存​​在。

错误的角度文件的可疑问题,因为如果我移动控制器内的getSession代码,代码工作正常。但错误仍然存​​在于角度版本1.0.6和1.1.4(未压缩和缩小版本)。

该错误在Firefox中变化。其fn is not a function与未压缩的angularjs和b is not a function与缩小angularjs。

有关如何解决此问题的任何建议?

+1

没有ü尝试在成功使用匿名的回调函数 – 2013-04-29 06:25:29

+0

哇。那完美的作品。那么角度问题还是我的定义问题? – 2013-04-29 06:38:35

+4

当你将'$ scope.handleSuccess'传递给'.success()'时,'$ scope.handleSuccess'是未定义的。只需将处理程序放在控制器中其余代码的上方即可。 – Bart 2013-04-29 07:39:20

回答

1

冲电气因此基于注释的下面的代码工作

var studentApp = angular.module('studentApp',['ui.bootstrap']); 
studentApp.factory('studentSession', function($http){ 
    return { 
     getSessions: function() { 
      return $http.post('/services', { 
       type : 'getSource', 
       ID : 'TP001' 
      }); 
     } 
    } 
}); 

studentApp.controller('studentMenu',function($scope, studentSession){ 
    //------Code Change--------- 
    //Moved before function call. 
    $scope.handleSuccess = function(data, status) { 
     console.log(data); 
    }; 
    studentSession.getSessions().success($scope.handleSuccess); 
});