Arthur  Kishinets Arthur Kishinets - 6 months ago 18
AngularJS Question

Factory is not a function in my controller

I am trying to write a factory and use it in one of my controllers, but it gives me an error:


TypeError: wordsToTrain is not a function


I made my controller and factory very simple but still don`t get why is this happening:

angular.module('bananaApp')
.controller('TrainingCtrl', [ '$scope', 'wordsToTrain', function ($scope, wordsToTrain) {
wordsToTrain();
}]);

angular.module('bananaApp')
.factory('wordsToTrain', function () {
return 3;
});

Answer

You are trying to instantiate a value. Your factory doesn't return a function it returns a value instead.

angular.module('bananaApp')
  .controller('TrainingCtrl', [ '$scope', 'wordsToTrain', function ($scope, wordsToTrain) {
    console.log(wordsToTrain) //this would give you 3 not a function;
  }]);

angular.module('bananaApp')
  .factory('wordsToTrain', function () {
    return  3;
  });

// to return a function

angular.module('bananaApp')
  .controller('TrainingCtrl', [ '$scope', 'wordsToTrain', function ($scope, wordsToTrain) {
    console.log(wordsToTrain()) // this would give you 3 as well but this is a function;
  }]);

angular.module('bananaApp')
  .factory('wordsToTrain', function () {
    return function() {
       return 3;
  });
Comments