2

我正在玩 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"
      }
    ]
  }
}

非常感谢任何帮助或建议。

谢谢

4

1 回答 1

2

确保工厂和控制器都在同一个应用程序中。我在工厂进行了一些重构,以使其更加可重用。出厂时的小改动。现在 getReports 将返回一个承诺。当 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;
    });
});

希望这会对你有所帮助,谢谢。

于 2015-01-14T20:48:18.587 回答