Search code examples
angularjsangularjs-factory

AngularJS - Factory - TypeError: Cannot read property 'getSpec' of undefined


I am starting with AngularJS and i am having some issues when trying to use a factory from a controller.

I have the following factory

angular.module('testingApp')
  .factory('factoryService', function ($http) {
    // Service logic
    var getSpec = function(p) {
      return $http.get('http://someurl//?p=' + p);
    };
    return {
      getSpec: getSpec  
    };
  });

and then i try to consume it from the controller as follows

angular.module('testingApp')
  .controller('ServiceincientsCtrl',[ function (factoryService,$scope) {
   console.log('Starting Service Incident Controller');
    factoryService.getSpec('AAA').then(function(response){
        $scope.result = response.data;
    }, function(error){
        console.log('opsssss' + error);
    });

  }]);

But when i try to run it i receive the following message

TypeError: Cannot read property 'getSpec' of undefined

I don't know what i am missing,It should be a newbbie error, I googled it and i tried many examples with the same result.

Any ideas of what i am doing wrong?

Thanks!


Solution

  • Looks like you are not using the dependancy array notation properly. Please refer the below code. Please add 'factoryService' & '$scope' as array items.

    .controller('ServiceincientsCtrl', ['factoryService', '$scope', function(factoryService, $scope) {
        console.log('Starting Service Incident Controller');
        factoryService.getSpec('AAA').then(function(response) {
            $scope.result = response.data;
        }, function(error) {
            console.log('opsssss' + error);
        });
    
    }]);
    

    Angular documentaion on dependancy injection.