理解angular.js中的依赖注入

时间:2015-10-19 11:48:16

标签: angularjs

我刚刚使用angular.js浏览了在线重新编码的代码,并且遇到了以下示例:

<!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>

现在有以下部分:

 var app = angular.module('demoapp', ['openlayers-directive']);

我不太确定,上面一行,我读到了依赖注入 HERE 。但我不太确定上述行的目的是什么?它到底在做什么?

我已经找到了一些代码如下的在线示例:

// Define a new module for our app. The array holds the names of dependencies if any.
var app = angular.module("instantSearch", []);

(见评论),好的,但我仍然没有得到['openlayers-directive'],正在做什么?

2 个答案:

答案 0 :(得分:1)

它声明了一个名为'demoapp'的模块,该模块依赖于名为'openlayers-directive'的模块。这基本上意味着模块'openlayers-directive'中定义的所有角度组件(指令,服务,过滤器,控制器,常量等)都可以在角度应用程序中使用。

阅读the documentation

答案 1 :(得分:1)

openlayers-directive是一个角度模块。在创建演示应用程序模块时,您将包含对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();
    }
});
相关问题