4

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

iLemming
  • 34,477
  • 60
  • 195
  • 309
  • related http://stackoverflow.com/questions/10924503/angularjs-inject-module-after-app-initialization – Liviu T. Jun 24 '13 at 22:18

1 Answers1

8

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.

Liviu T.
  • 23,584
  • 10
  • 62
  • 58