Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

injecting module when you have access only to a module variable

Tags:

angularjs

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

like image 639
iLemming Avatar asked Feb 16 '23 03:02

iLemming


1 Answers

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.

like image 55
Liviu T. Avatar answered May 12 '23 00:05

Liviu T.