2013-04-29 112 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); 
});