Tuesday, February 3, 2015

Angular module dependency injection

Angular provides the module functions to do the service injection. In this way, we can build our own service functions and inject into the controller to load it.

We can set up the module first, then call the app.js to set up the both module together, this is the example shows in the angular tutorial site.
https://docs.angularjs.org/tutorial/step_11

Here is the example for this way, there is a controller and it depends on the dataService to load the data. Each angular.module call is in its own js file.

angular.module('app', ['services', 'controllers']);

angular.module('services', [])
        .factory('expenseDataService', ['$http', expenseDataService]);

angular.module('controllers', [])
        .controller('expenseController', ['expenseDataService', expenseController]);

Also there is a simplified version. But you need to put app.js at first in the html page. In this way, all the dependency are created in the app module directly.
angular.module('app', []);

angular.module('app')
        .factory('expenseDataService', ['$http', expenseDataService]);

angular.module('app')
        .controller('expenseController', ['expenseDataService', expenseController]);

The full file is attached as a zip file.expense_app.zip

No comments: