Question

I cannot get access to methods in my Angular Factory? I get "TypeError: Object # has no method 'method1'" error. My angular app looks like this...

myApp.js

var myApp = angular.module('myAngApp', [])

myApp.config(function ($routeProvider, $httpProvider) {

$routeProvider
    .when('/list',
      {
        controller: 'ListController',
        templateUrl: 'partials/list.html'
      })
     .when('/reports/:reportId',
      {
        controller: 'DetailController',
        templateUrl: 'partials/report.html'
     })
})

factory.js

myApp.factory('factory1', function(){

    var factory = {}; 

    factory.method1 = function() {
            console.log('method1');
        }

    factory.method2 = function() {
            console.log('method2');
        }

    return factory;

});

ListController.js

function ListController($scope, $location, $http, $route, $rootScope, factory1) {
  factory1.method1();
}

ListController.$inject = ['$scope', '$location', '$http', '$route', '$rootScope', 'factory1'];
Was it helpful?

Solution

try this...

myApp.controller('ListController', [
  '$scope',
  '$location',
  '$http',
  '$route',
  '$rootScope',
  'factory1',
  function ($scope, $location, $http, $route, $rootScope, factory1) {
    factory1.method1();
  }]);

instead of your current function ListController and the $inject statement

jsfiddle http://jsfiddle.net/NuCZz/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top