Conditionally inject angular module dependency
Asked Answered
M

3

10

I'm new to angular and have the following code.

angular.module('MyApp')
    .controller('loginController', ['$scope', '$http', 'conditionalDependency',
        function ($scope, $http, conditionalDependency{
}

I would like to have conditionalDependency loaded conditionally. Something like this

if(true)
{
//add conditionalDependency
}

How can this be done. I've seen this post . However, my requirement is that I have the dependency specified in function

Thanks in advance.

Monosyllable answered 14/4, 2015 at 1:52 Comment(1)
Is this for performances/bandwidth reasons or for an application/structural point of view? Short answer: you cannot do that natively but there are some interesting articles about it on the internet.Fizzle
G
17

Not quite clear as to why you would have to have it in a named function like in your example but...

If you need conditional dependencies, I would suggest taking a look at the following:

Conditional injection of a service in AngularJS

I've used this method in a couple niche scenarios and it works quite well.

EXAMPLE:

angular.module('myApp').controller('loginController', 
    ['$injector', '$scope', '$http',
    function($injector, $scope, $http) {
        var service;

        if (something) {
            service = $injector.get('myService');
        }
    });
Gerianne answered 14/4, 2015 at 2:33 Comment(0)
R
1

You can use it even without injecting injector in your controller

if(something){
   var injector = angular.element(document).injector();
   var myService  = injector.get('myService')
}
Reiko answered 3/5, 2015 at 23:32 Comment(0)
E
0

Use:

  1. angular.injector().get('conditionalDep');
  2. You can inject $injector once to your file and call $injector.get('dep');
Elmaelmajian answered 14/4, 2015 at 2:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.