angularjs - runtime dependency injection?
Asked Answered
K

2

14

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)

Kathrinekathryn answered 5/12, 2012 at 13:55 Comment(0)
U
18

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
])
Upturned answered 5/12, 2012 at 14:33 Comment(1)
I see the injector can be used for injecting known objects, can the injector add new dependencies to a module? as in, when i dynamically preload a widget, can i add it to the app, so the app can show it?Jakob
T
0

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.

Tribunal answered 5/12, 2012 at 14:0 Comment(1)
You're right for dependency names that are known at compile time, but sometimes at runtime this comes in handy. What I'm using it for is, in a directive, I'm setting an attribute to the name of a 'value' dependency that helps configure the directive. In my directive I resolve the dependency dynamically.Kathrinekathryn

© 2022 - 2024 — McMap. All rights reserved.