Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional dependencies in AngularJS

I'm trying to implement a controller in AngularJS which is used across multiple pages. It makes use of some services. Some of them are loaded on all pages, some - not. I mean it is defined in different files, and these files are loaded independently. But if I do not load these services on all pages I got error:

Error: Unknown provider: firstOtionalServiceProvider <- firstOtionalService 

So, I need to load scripts on all pages. Can I declare dependency as optional in Angular? E.g:

myApp.controller('MyController', ['$scope', 'firstRequiredService', 'secondRequiredService', 'optional:firstOptionalService', 'optional:secondOptionalService', function($scope, firstRequiredService, secondRequiredService, firstOptionalService, secondOptionalSerivce){      // No need to check, as firstRequiredService must not be null     firstRequiredService.alwaysDefined();      // If the dependency is not resolved i want Angular to set null as argument and check     if (firstOptionalService) {         firstOptionalService.mayBeUndefinedSoCheckNull();     }  }]); 
like image 721
molaccha Avatar asked Aug 30 '13 21:08

molaccha


People also ask

What is optional dependency in angular?

The optional dependency is a parameter decorator to be used on constructor parameters, which marks the parameter as being an optional dependency. Due to this, the DI framework provides null if the dependency is not found.

What is dependencies in AngularJS?

Dependency Injection in AngularJS can be defines as the software design pattern which defines the way the software components are dependent on each other. AngularJS provides a set of components that can be injected in the form of dependencies such as factory, value, constant, service, and provider. factory.

What is the use of @optional in angular?

Angular has an @Optional decorator, which when applied to a constructor argument instructs the Angular injector to inject null if the dependency is not found.

What is ngInject in AngularJS?

A tool called ng-annotate uses it as a flag : if a function starts with 'ngInject'; , it will be processed by ng-annotate. Basically, ng-annotate will transform angular.module("MyMod").controller("MyCtrl", function($scope, $timeout) { "ngInject"; ... }); to. angular.


1 Answers

Apparently not using automatic injection. However, you can inject the injector and check for the service:

myApp.controller('MyController', [     '$scope', '$injector', 'firstRequiredService', 'secondRequiredService',      function ($scope, $injector, firstRequiredService, secondRequiredService) {         if ($injector.has('firstOptionalService')) {             var firstOptionalService = $injector.get('firstOptionalService');         }     } ]); 
like image 54
Derek Stobbe Avatar answered Sep 19 '22 03:09

Derek Stobbe