Injection module when you only have access to the module variable

Let's say you have

var app = angular.module('Mod1',[]) 

and now you need to add something else to this module, but you cannot change this line, you only have access to the app variable.

So this will not work, right?

 var mod2 = angular.module('mod2',[]).factory('$myService', function(){ return { do: function(){alert('doing'); } }) app.directive('foo',[$myService]) // $myService here is undefined 

Of course, you can always:

 injector = angular.injector(['mod2']) $myService = injector.get('$myService') 

Although I wonder if there is a more elegant solution

+4
angularjs
Jun 24 '13 at 20:31 on
source share
1 answer

It depends on when your code is actually running. I tried this plunker and it worked.

app.js

 var app = angular.module('plunker', []); 

myModule.js

 var myModule = angular.module('myModule', []); myModule.service('MyService', function() { return {test: 'MyService'}; }); app.requires.push('myModule'); app.controller('MainCtrl', ['$scope','MyService', function($scope, MyService) { $scope.name = MyService.test; }]); 

index.html

 <head> <script src="app.js"></script> <script src="myModule.js"></script> </head> 

You need to add additional modules after loading app.js, but within the same javascript execution sequence. Timeouts and asynchronous loading did not help me.

+5
Jun 24 '13 at 22:09
source share



All Articles