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.

Community
  • 1
  • 1
Frenz
  • 687
  • 1
  • 10
  • 22
  • 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. – floribon Apr 14 '15 at 01:55

3 Answers3

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');
        }
    });
Community
  • 1
  • 1
technicallyjosh
  • 3,511
  • 15
  • 17
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')
}
Tom Craft
  • 161
  • 4
0

Use:

  1. angular.injector().get('conditionalDep');
  2. You can inject $injector once to your file and call $injector.get('dep');
Yan Foto
  • 10,850
  • 6
  • 57
  • 88
Smrutiranjan Sahu
  • 6,911
  • 2
  • 15
  • 12