angularjs TypeError:undefined不是函数工厂

时间:2015-01-14 20:43:18

标签: javascript json angularjs angularjs-service angularjs-http

我正在玩angularjs。我试图简单地从json文件中提取数据。当我运行我的代码时,文件显示在网络中,但数据没有显示在页面上,我在控制台中收到以下错误:

  

TypeError:undefined不是Ob的函数   (LIB /角-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"
      }
    ]
  }
}

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

由于

1 个答案:

答案 0 :(得分: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;
    });
});

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

相关问题