Zyx Sun
Zyx Sun

Reputation: 439

Cannot call Factory in Controller (angularjs)

I am staring to learn angularjs (please be kind).

I am trying to call generatePollCode method in the factory using the createCtrl but I got the message below:

Error: [$injector:undef] http://errors.angularjs.org/1.6.4/$injector/undef?p0=pollFactory...

Here's my code:

App initialization:

var app = angular.module("pollApp", ['ngRoute', 'ngAnimate']);

Factory:

app.factory("pollFactory", function($http){

var factory = {};

factory.generatePollCode = function(){
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ ){
        text = text + possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return text;
  };

});

Controller:

 app.controller('createCtrl', function($http, $scope, $timeout, focus, pollFactory){
  $scope.submitPoll = function (){
      var x =pollFactory.generatePollCode();
      console.log(x);
  }
});

Thanks for anyone that can help me!

Upvotes: 2

Views: 388

Answers (1)

Hadi
Hadi

Reputation: 17289

It should be like this. you forgot return factory object

app.factory("pollFactory", function($http){
 var factory = {};
 factory.generatePollCode = function(){
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for( var i=0; i < 5; i++ ){
     text = text + possible.charAt(Math.floor(Math.random() * 
     possible.length));
   }
    return text;
 };
 return factory 
});

Upvotes: 3

Related Questions