Angularjs 理解angular.js中的依赖注入
我刚刚使用angular.js浏览了一个在线reppositoty的代码,遇到了以下示例:Angularjs 理解angular.js中的依赖注入,angularjs,Angularjs,我刚刚使用angular.js浏览了一个在线reppositoty的代码,遇到了以下示例: <!DOCTYPE html> <html ng-app="demoapp"> <head> <script src="js/ol.js"></script> <script src="js/angular.min.js"></script> <script s
<!DOCTYPE html>
<html ng-app="demoapp">
<head>
<script src="js/ol.js"></script>
<script src="js/angular.min.js"></script>
<script src="js/angular-sanitize.min.js"></script>
<script src="js/angular-openlayers-directive.js"></script>
<link rel="stylesheet" href="css/ol.css" />
<link rel="stylesheet" href="css/angular-openlayers-directive.css" />
<script>
var app = angular.module('demoapp', ['openlayers-directive']);
</script>
</head>
<body>
<openlayers lat="39.92" lon="116.38" zoom="10" height="400" custom-layers="true">
<ol-marker lat="39.92" lon="116.38" message="Here is Beijing. Dreamful place.">
</ol-marker>
</openlayers>
<h1>Adding a layer with markers with no javascript example</h1>
</body>
</html>
我不太清楚,在上面这一行,我读到了关于依赖注入的内容。但我不太清楚这句话的目的是什么?它到底在干什么
我浏览了一些在线示例,它们的代码如下所示:
// Define a new module for our app. The array holds the names of dependencies if any.
var app = angular.module("instantSearch", []);
(见注释),好吧,但我还是不明白
['openlayers-directive']
在做什么 它声明一个名为“demoapp”的模块,该模块依赖于名为“openlayers指令”的模块。这基本上意味着模块“openlayers指令”中定义的所有角度组件(指令、服务、过滤器、控制器、常量等)都可以在角度应用程序中使用
读取。openlayers指令是一个角度模块。在创建演示应用程序模块时,包括对openlayers模块的引用 因此,如果您想在演示应用程序模块中使用其他模块,您也可以将它们包含在此处,在此处您将首次声明您的模块 例如:
var app = angular.module('demoapp', ['openlayers-directive', 'anotherModule', 'yetAnotherModule']);
在您的代码中,您可以通过简单地将这些模块作为参数包含进来,从而传入来自这些模块的任何服务
因此,如果您有demoController,您可以从其中一个包含的模块传入服务并使用它
比如说
angular.module('demoApp').controller('demoContoller', function($scope, anotherModuleService)
{
$scope.someFunctionFiredFromController = function()
{
//I have access to this service because the module it
//belongs to was referenced by the demoApp module, and the
//service was injected into the controller
anotherModuleService.doSomethingRelevant();
}
});
['openlayers-directive']
正在注入另一个模块(从外观上看是一个指令),可能位于js/angular openlayers directive.js
@Avalanche no.这不是依赖注入,openlayers指令也不是指令:它是一个模块。
angular.module('demoApp').controller('demoContoller', function($scope, anotherModuleService)
{
$scope.someFunctionFiredFromController = function()
{
//I have access to this service because the module it
//belongs to was referenced by the demoApp module, and the
//service was injected into the controller
anotherModuleService.doSomethingRelevant();
}
});