2

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!

2
  • where is the factory located??in the same js file where ur controler located???if not have add that scrip to index Commented May 6, 2017 at 11:21
  • Yes, the factory and the controller files are in the same folder Commented May 6, 2017 at 11:22

1 Answer 1

3

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 
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I forgot to read the docs thoroughly and missed that part.
You are welcome. glad to help you. please accept the answer. thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.