Undefined is not a function error when using factory method in angularJS
Asked Answered
H

1

5

I'm having problems finding the solution to TypeError: undefined is not a function in my code. I have the following app.js:

var app =  angular.module('test', ['ngRoute', 'test.services', 'test.directives', 'test.controllers']);
app.config(function ($routeProvider, $httpProvider, $locationProvider) {

  $locationProvider.html5Mode(true);

  $routeProvider.
    when('/q/:q', {
      templateUrl: '/templates/productlist.html',
      controller: 'ProductCtrl'
    }).
    otherwise({
      redirectTo: '/q'
    });

});

Then I have a controller

var controllers = angular.module('test.controllers', []);
controllers.controller('ProductCtrl', ['$scope', '$routeParams', 'ProductFactory',
  function ($scope, ProductFactory, $routeParams) {

    $scope.query = $routeParams.q;
    $scope.products = ProductFactory.query({query: $scope.query});
  }]);

And a factory

var services = angular.module('test.services', ['ngResource']);
var baseUrl = 'http://localhost\\:8080';
services.factory('ProductFactory', function ($resource) {
    return $resource(baseUrl + '/test/smart/:query', {}, {
        query: { method: 'GET', isArray: true }
    })
});

This code results on load in the above mentioned TypeError on the line $scope.products = ProductFactory.query({query: $scope.query}); in my controller. Further, when debugging my code I see that $routeParams.q is null or undefined. What I want is that in my controller the $scope.products variable becomes an array with the result of the query.

What am I doing wrong?

Hyo answered 9/6, 2014 at 16:38 Comment(0)
G
10

Please try with correct function arguments,

controllers.controller('ProductCtrl', ['$scope', '$routeParams', 'ProductFactory',
  function ($scope /*ProductFactory*/, $routeParams, ProductFactory) {

    $scope.query = $routeParams.q;
    $scope.products = ProductFactory.query({query: $scope.query});
  }]);
Guffey answered 9/6, 2014 at 16:41 Comment(2)
Yes, it works, thanks a lot! However, I don't understand why the order of the arguments is important?Hyo
@PieterDB: That's the whole point of inlne array notation in DI (arguments' name is irrelevant, only the position is). Take a look at the docs.Songful

© 2022 - 2024 — McMap. All rights reserved.