Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs - runtime dependency injection?

Tags:

angularjs

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)

like image 415
Roy Truelove Avatar asked Dec 05 '12 13:12

Roy Truelove


People also ask

Does AngularJS support dependency injection?

Dependency Injection is pervasive throughout AngularJS. You can use it when defining components or when providing run and config blocks for a module.

How does dependency injection work in AngularJS?

Dependency injection (DI) is a paradigm. The way it works in Angular is through a hierarchy of injectors. A class receives its resources without having to create or know about them. Injectors receive instruction and instantiate a service depending on which one was requested.

How do I inject a module in AngularJS?

Injecting a value into an AngularJS controller function is done simply by adding a parameter with the same name as the value (the first parameter passed to the value() function when the value is defined). Here is an example: var myModule = angular. module("myModule", []); myModule.

What is the use of @injectable in Angular?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.


1 Answers

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
])
like image 91
matys84pl Avatar answered Oct 22 '22 12:10

matys84pl