A week later, playing with the angular, I realized one very important thing. All examples of angles have the DI configuration I was looking for. Configuration is the module definition itself .
All I had to do was define a separate module from the class definitions . Here the fiddle of my question is solved - http://jsfiddle.net/5ZDe6/7/
/** * app module configuration */ angular.module('app', ['debug'], function($provide) { var dataLoaderFactory = function(Notifier) { return new my.model.DataLoader(Notifier); } // if you want to change notifier just change this injection to AlertNotifier dataLoaderFactory.$inject = ['LogNotifier']; // Specify factory with service ID DataLoader for class my.model.DataLoader $provide.factory('DataLoader', dataLoaderFactory); }) .controller('AppCtrl', my.controller.ItemCtrl); // you can even specify AppCtrl implementation (eg CachedCtrl) my.controller.ItemCtrl.$inject = ['$scope','DataLoader'] my.controller.CachedCtrl.$inject = ['$scope'] /** * debug module configuration */ angular.module('debug', [], function($provide) { $provide.factory('LogNotifier', function($window) { return new my.debug.LogNotifier($window); }); $provide.factory('AlertNotifier', function($window) { return new my.debug.AlertNotifier($window); }); });
And there are class definitions separate from the DI configuration.
/** * Controller class definition */ my = window.my || {}; my.controller = my.controller || {}; my.controller.ItemCtrl = function($scope, loader) { $scope.items = loader.loadAllItems(); }; my.controller.CachedCtrl = function($scope) { $scope.items = [ { name: 'Cached ctrl value 1'}, { name: 'Cached ctrl value 2'} ] } /** * Model class definition */ my.model = my.model || {}; my.model.DataLoader = function(notifier) { this.notifier = notifier; this.loadAllItems = function() { this.notifier.messageMe('Loading items'); // let asume there is ajax call and promise object return return [ {name: 'Item1'}, {name: 'Item2'} ]; }; }; /** * Some debug classes definition */ my.debug = my.debug || {} my.debug.LogNotifier = function($window) { this.$window = $window; this.messageMe = function(message) { this.$window.console.log(message); } }; my.debug.AlertNotifier = function($window) { this.$window = $window; this.messageMe = function(message) { this.$window.alert(message); } }
I believe this is the cleanest way to achieve my requirements. Unfortunately, if you really want to do this, you need to write a little more code .
Franc
Frank source share