4

My factory is undefined in my controller and I cannot figure out why. I have created a simple example to illustrate.

Here I create the app:

var ruleApp = angular
    .module( "ruleApp", [ 
        "ngRoute",  
        "ruleApp.NewFactory1",
        "ruleApp.NewFactory2",
    ] );

In this dummy example I'd like to build a factory that does something simple, show an alert box. I'll show two methods of doing this (one works, one does not).

Factory 1:

angular
    .module('ruleApp.NewFactory1', [])
    .factory('NewFactory1', function() {
        return function(msg) {
            alert(msg);
        };
  });

Factory 2:

angular
    .module('ruleApp.NewFactory2', [])
    .factory('NewFactory2', function() {
        var showMessageFunction = function(msg) {
            alert(msg);
        };
        return 
        {
            showMessage: showMessageFunction
        };
  });

Notice the return type of factory 1 is a function and the return type of factory 2 is an object with a property (which is of type function).

Now look at how I'd like to use both of these factories in my controller:

 ruleApp.controller( "RuleController", function( $scope, NewFactory1, NewFactory2 ) {
    NewFactory1("1");
    NewFactory2.showMessage("2");
});

This is where the problem gets exposed. During execution, I am prompted with the alert box for NewFactory1("1");, but it fails during execution of NewFactory2.showMessage("2"); because NewFactory2 is undefined (TypeError: Cannot call method 'showMessage' of undefined).

Can you help me spot the issue? I want to be able to use factories like NewFactory2 because I want the factories to be able to do more than just one thing (i.e. have more than one single function). By the way, I'm using Angular version 1.2.1.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Trevor
  • 124
  • 1
  • 3
  • 12

1 Answers1

5

factory 2 should be (demo)

angular
.module('ruleApp.NewFactory2', [])
.factory('NewFactory2', function() {
    var showMessageFunction = function(msg) {
        alert(msg);
    };
    return {    // <--------- do not go on a new line after return
        showMessage: showMessageFunction
    };
});
Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
klode
  • 10,821
  • 5
  • 34
  • 49
  • This worked. The issue was the white space. Lesson learned, pay very close attention to white space in angular. – Trevor Nov 26 '13 at 20:59
  • 3
    That's not angular. That's javascript. See http://stackoverflow.com/questions/3641519/why-does-a-results-vary-based-on-curly-brace-placement – dnc253 Nov 26 '13 at 21:04
  • Oh my glob! The whitespace was seriously the issue. Now that I think about it, it makes complete sense. One should then be careful when using certain IDEs (like Visual Studio) that can be configured to use the new-line-style scoping in stead of [Egyptian Brackets](http://blog.codinghorror.com/new-programming-jargon/). – that0th3rGuy Jun 12 '14 at 10:56