Roy Truelove
Roy Truelove

Reputation: 22476

angularjs - runtime dependency injection?

Simple one I hope..

Here's a plunker for reference.

I know how to specify a dependency at compile-time (see MainCtrlInjected controller). But how do I pull down a dependency at runtime, giving the name of that dependency? (see MainCtrlInjectedRuntime controller)

Upvotes: 14

Views: 5619

Answers (2)

matys84pl
matys84pl

Reputation: 8334

You can use $injector to get your value at runtime:

Check my forked plunker: http://plnkr.co/edit/iVblEU?p=preview

Code:

app.controller('MainCtrlInjectedRuntime', [
  '$scope',
  '$injector'
  ($scope, $injector) ->

   nameValHandle = 'nameVal'

   # !!! This is how you inject at runtime
   name = $injector.get(nameValHandle)

   $scope.name = name
])

Upvotes: 18

pgreen2
pgreen2

Reputation: 3651

I am just getting into angularjs, but I believe the appropriate way to handle this situation would be to inject a service into MainCtrlInjectedRuntime. The injected service would have your somehowGetNameFromValue method.

Upvotes: 0

Related Questions