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)

2 Answers 2

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
])
Sign up to request clarification or add additional context in comments.

1 Comment

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?
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.