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(); } }]);
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.
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.
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.
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.
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'); } } ]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With