angularjsfactoryangularjs-factory

AngularJS : Why is my factory always undefined in my controller?


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.


Solution

  • 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
        };
    });