1

I'm trying to separate my angular code into factories, so my controllers don't become unmaintainable. Specifically, in my factory, I will house code that will be shared across multiple controllers.

The problem is, I cannot seem to inject a factory into my controller no matter what I do.

Here's my factory

angular.module('my-app')
    .factory('Game', function() {
        var colors = ['#FF0000', '#660000', '#FF3300', '#FF9900', '#003300',
                      '#000033', '#660033', '#FF0033', '#383838'];
    });

Here's my controller

angular.module('my-app')
    .controller('gamesController', ['$scope', '$interval', 'Game', 
    function($scope, $interval, Game) {

And here's my loading order

<script src='scripts/app.js'></script>
<script src='scripts/services/game.js'></script>
<script src='scripts/controllers/navController.js'></script>
<script src='scripts/controllers/gamesController.js'></script>

I get undefined provider and I cannot figure out where the problem is.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
  • That's because your factory doesn't have any return value. Try `return { colors: ['#FF0000', '#660000', '#FF3300', '#FF9900', '#003300','#000033', '#660033', '#FF0033', '#383838'];}` – Oliver Feb 03 '16 at 06:06
  • Factories have to have a return statement? I had no idea about that. Will test this out – Richard Hamilton Feb 03 '16 at 06:14

1 Answers1

1

Angular Factory must have a return result.

Syntax: module.factory( 'factoryName', function );

Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

your factory should be like this:

angular.module('my-app')
    .factory('Game', function() {
        return { colors : ['#FF0000', '#660000', '#FF3300', '#FF9900', '#003300',
                      '#000033', '#660033', '#FF0033', '#383838']
               }
    });

if you want to know more details, please visit AngularJS: Service vs provider vs factory

Community
  • 1
  • 1
Python Basketball
  • 2,320
  • 3
  • 24
  • 47