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

2

5

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!

Vassalize answered 9/10, 2014 at 15:0 Comment(0)
P
11

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.

Politesse answered 9/10, 2014 at 15:8 Comment(0)
V
3

First of all, you didn't declare your controller properly. It should look like this:

.controller('ServiceincientsCtrl',['$scope', 'factoryService', function($scope, factoryService) {

I personally use Services as I find them more readable.

Here's what your factory would look like as a Service:

myApp.service('factoryService', function ($http) {

    this.getSpec = function(p) {
        return $http.get('http://someurl//?p=' + p);
    }

});

This would work with your current controller.

Volcanology answered 9/10, 2014 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.