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

My factory is undefined in my controller and I can not understand why. I created a simple example to illustrate.

Here I create the application:

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

In this dummy example, I would like to build a factory that does something simple, show a warning window. I will show two ways to do this (one works and the other 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
        };
  });

Note that the return type factory 1 is a function, and the return type factory 2 is an object with a property (which has a type function).

Now let's see how I would like to use both of these factories in the controller:

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

. NewFactory1("1");, NewFactory2.showMessage("2");, NewFactory2 undefined (TypeError: showMessage undefined).

? , NewFactory2, , , (.. ). , Angular 1.2.1.

+4
1

factory 2 (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
    };
});
+5

All Articles