我正在玩 angularjs。我正在尝试简单地从 json 文件中提取数据。当我运行代码时,文件显示在网络中,但数据未显示在页面上,并且我在控制台中收到以下错误:
TypeError: undefined is not a function at Ob (lib/angular-1-2/angular.min.js:14:6)
我使用的代码如下:
var Services = angular.module('Services', ['ngResource']);
Services.factory('reportFactory', function($http){
console.log(REPORT_LIST_URL);
return{
getReports: function(callback){
$http.get(REPORT_LIST_URL).success(callback);
}
}
});
function ReportsCtrl($scope, $http, reportFactory) {
$scope.reportsList = [];
console.log($scope.reportsList);
console.log("Get report list from json file");
console.log("before the factory");
reportFactory.getReports(function(data){
$scope.reportsList = data;
});
}
json 文件示例
{
"Reports": {
"Productivity": [
{
"name": "Productivity Summary",
"value": "Productivity"
},
{
"name": "Time Summary",
"value": "TimeSummary"
}
]
}
}
非常感谢任何帮助或建议。
谢谢
最佳答案
确保工厂和 Controller 位于同一个应用程序中。 我在工厂做了一些重构,以便它更加可重用。 如果工厂有小改动。现在 getReports 将返回一个 promise 。当 Promise 得到解决时,我们可以调用我们的函数。
var Services = angular.module('Services', ['ngResource']);
Services.factory('reportFactory', function($http){
console.log(REPORT_LIST_URL);
return{
getReports: function(){
return $http.get(REPORT_LIST_URL); //returning promise
}
}
});
Services.controller('ReportsCtrl',function($scope, $http, reportFactory) {
$scope.reportsList = [];
console.log($scope.reportsList);
console.log("Get report list from json file");
console.log("before the factory");
reportFactory.getReports().then(
//success callback
function(data){
$scope.reportsList = data;
},
//error callback
function(data){
$scope.reportsList = data;
});
});
希望这对您有帮助,谢谢。
关于javascript - angularjs 类型错误 : undefined is not a function factory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27952049/