Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 338
PieterDB Avatar asked Jun 09 '14 16:06

PieterDB


1 Answers

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});
  }]);
like image 81
msapkal Avatar answered Nov 14 '22 22:11

msapkal