不,Angular 还不支持开箱即用的可选依赖项。您最好将所有依赖项放入一个模块并将其作为一个 Javascript 文件加载。如果您需要另一组依赖项 - 考虑在另一个 JS 中创建另一个模块并将所有常见的依赖项放到 common JS 中。
但是,您描述的行为可以通过$injector
service来实现。您只需将所有依赖项注入$injector
控制器而不是所有依赖项,然后手动从中提取依赖项,检查它们是否存在。而已:
索引.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>
应用程序.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');
}
});
看到它住在这个笨拙的地方!尝试使用<script>
标签并注意控制台输出。
PS 而且,正如@Problematic 所说,您可以$injector.has()
从AngularJS 1.1.5 开始使用。