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.

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. Commented Apr 14, 2015 at 1:55

3 Answers 3

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

Comments

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')
}

Comments

0

Use:

  1. angular.injector().get('conditionalDep');
  2. You can inject $injector once to your file and call $injector.get('dep');

Comments

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.