Search code examples
javascriptjsonangularjsangularjs-serviceangularjs-http

angularjs TypeError: undefined is not a function factory


I'm in the middle of playing around with angularjs. I'm trying to simply pull data from a json file. When I run my code the file shows up in the network, but the data doesn't show up on the page and I get the following error in my console:

TypeError: undefined is not a function at Ob (lib/angular-1-2/angular.min.js:14:6)

The code I'm using is as follows:

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;
    });
}

example of the json file

{
  "Reports": {
    "Productivity": [
      {
        "name": "Productivity Summary",
        "value": "Productivity"
      },
      {
        "name": "Time Summary",
        "value": "TimeSummary"
      }
    ]
  }
}

Any help or advice is greatly appreciated.

Thanks


Solution

  • Ensure that both factory and controller is in same app. I did some refactor in factory so that it will get more reusable. Small changes if factory. Now getReports will return a promise. We can call our function when promise gets resolved.

    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;
        });
    });
    

    Hopefully this will help you, Thanks.