我试图在跨多个页面使用的AngularJS中实现一个控制器。它利用了一些服务。其中一些已加载到所有页面上,有些则未加载。我的意思是它是在不同的文件中定义的,并且这些文件是独立加载的。但是,如果我没有在所有页面上加载这些服务,则会出现错误:
Error: Unknown provider: firstOtionalServiceProvider <- firstOtionalService
因此,我需要在所有页面上加载脚本。我可以在Angular中将依赖项声明为可选吗?例如:
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(); } }]);
不,Angular还不支持现成的可选依赖项。您最好将所有依赖项放入一个模块中,并将其作为一个Javascript文件加载。如果需要另一组依赖项,请考虑在另一个JS中创建另一个模块,并将所有公共依赖项放到公共JS中。
但是,您描述的行为可以通过$injectorservice实现。您只需将$injector所有依赖项注入到控制器中,然后手动将其从依赖项中拉出,以检查它们是否存在。而已:
$injector
index.html:
<!DOCTYPE html> <html data-ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script> <script src="app.js"></script> <script src="1.js"></script> <script src="2.js"></script> <title>1</title> </head> <body data-ng-controller="DemoController"> </body> </html>
app.js:
var myApp = angular.module('myApp', []); myApp.service('commonService', function(){ this.action = function(){ console.log('Common service is loaded'); } }); myApp.controller('DemoController', ['$scope', '$injector', function($scope, $injector){ var common; var first; var second; try{ common = $injector.get('commonService'); console.log('Injector has common service!'); }catch(e){ console.log('Injector does not have common service!'); } try{ first = $injector.get('firstService'); console.log('Injector has first service!'); }catch(e){ console.log('Injector does not have first service!'); } try{ second = $injector.get('secondService'); console.log('Injector has second service!'); }catch(e){ console.log('Injector does not have second service!'); } if(common){ common.action(); } if(first){ first.action(); } if(second){ second.action(); } }]);
1.js:
myApp.service('firstService', function(){ this.action = function(){ console.log('First service is loaded'); } });
2.js:
myApp.service('secondService', function(){ this.action = function(){ console.log('Second service is loaded'); } });
看到它活在这pl!尝试使用<script>标签并注意控制台输出。
<script>
PS而且,正如@Problematic所说,您可以$injector.has()从AngularJS 1.1.5开始使用。
$injector.has()