Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally inject angular module dependency

Tags:

angularjs

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.

like image 448
Frenz Avatar asked Apr 14 '15 01:04

Frenz


People also ask

What is NullInjector?

The next parent injector in the hierarchy is the NullInjector() , which is the top of the tree.

How will you configure module injector?

We configure these injectors with providers by adding the configuration to either the providers property on the NgModule , Component and Directive decorators or to the viewProviders property on the Component decorator.

Which components can be injected as a dependency in Angular 7?

26) Which of the following components can be injected as a dependency in AngularJS? Answer: D is the correct answer. The "Application Module" can be injected as a dependency in AngularJS.

What is null injector in Angular?

The Null Injector does not contain any providers. Its job is to throw No provider for Service error. But if we decorate the dependency with @Optional decorator, then it will return null instead of throwing an error.


1 Answers

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');
        }
    });
like image 150
technicallyjosh Avatar answered Nov 06 '22 11:11

technicallyjosh