Richard Hamilton
Richard Hamilton

Reputation: 26444

Angular - Trouble injecting a factory into a controller

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.

Upvotes: 1

Views: 95

Answers (1)

Python Basketball
Python Basketball

Reputation: 2370

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

Upvotes: 1

Related Questions