Let's say you have a
var app = angular.module('Mod1',[])
and now you need to inject something else to that module, but you can't change that line, you only have access to the app
variable.
So this won't 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 do:
injector = angular.injector(['mod2'])
$myService = injector.get('$myService')
Although I'm wondering if there's more elegant solution
It depends on when is your code actually run. 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 your extra modules after the app.js is loaded but within the same javascript execution sequence. Timeouts and async loading failed for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With