Sajjan Sarkar February 2016

angularjs: Unable to Inject one module into another

Overview:

I have a module which contains a set of classes (models). I would like to inject this into another module which will use those classes. Please let me know what I'd doing wrong.

Error:

enter image description here

Code:

<body>
    <div ng-app="TestApp">
        <div ng-controller="Controller"></div>

    </div>

</body>
<script src="https://code.angularjs.org/1.2.8/angular.min.js"></script>
<script>
    // Module with classes, I would like to inject this into the next module
    var classes = angular.module('Models', []);
    classes.factory('Car', function() {
        return {
            honk : function() {
                alert('beep beep!');
            }
        }

    });
    // Main Module.
    var ClientEditApp = angular.module("TestApp", [ "Models" ]);
    // Adding a controller
    ClientEditApp.controller('Controller', [ '$scope', 'Models', function($scope, Models) {
        var c = new Models.Car();
        c.honk();
    } ]);
</script>
</html>

Answers


Aseem Gautam February 2016

1 - Models is factory module. We don't inject modules. Inject 'Car'. A module can have many factories, so we inject only the required as and when needed.
2 - Factory cannot be instantiated with new. Need to be used directly. Eg Car.honk()

Updated Code

<script>
    // Module with classes, I would like to inject this into the next module
    var classes = angular.module('Models', []);
    classes.factory('Car', function() {
        return {
            honk : function() {
                alert('beep beep!');
            }
        }

    });
    // Main Module.
    var ClientEditApp = angular.module("TestApp", [ "Models" ]);
    // Adding a controller
    ClientEditApp.controller('Controller', [ '$scope', 'Car', function($scope, Car) {        
        Car.honk();
    } ]);
</script>

Post Status

Asked in February 2016
Viewed 2,037 times
Voted 8
Answered 1 times

Search




Leave an answer