gpt4 book ai didi

angularjs - 模块如何访问另一个模块,即使它没有依赖关系

转载 作者:行者123 更新时间:2023-12-01 11:36:28 24 4
gpt4 key购买 nike

我对模块如何以 Angular 加载感到有点困惑。以下面的代码为例:

var app = angular.module("app", [ "app.widgets", "app.core"]);


var core = angular.module("app.core", []);
core.factory("foo", function(){
return {
ping: function(){
return "pong";
}
}
});

var widgets = angular.module("app.widgets", []);
widgets.controller("WidgetController", function($scope, foo){
$scope.items = [1,2,3,foo.ping()];
});

<body ng-app="app">
<ul ng-controller="WidgetController">
<li ng-repeat="item in items">
{{item}}
</li>
</ul>
</body>

我对我的“app.widgets”模块如何访问“app.core”模块感到困惑,即使它没有被声明为依赖项。

它似乎正在获取依赖项,因为“app.widgets”和“app.core”都在第三个模块中声明——这非常方便。但这对我来说似乎不是很直观。

所以我想我的问题是“如果两个模块在第三个模块中声明,它们是否会相互‘了解’?”。那是记录在案的行为吗?

最佳答案

您已将两个模块即 [ "app.widgets", "app.core"] 包含到您的应用程序模块中,然后您正在使用 WidgetController应用程序。尽管您没有对 app.widgets 模块做出任何显式依赖,但您仍然可以从应用模块内的模块 app.core 访问工厂 foo,因为您的应用模块依赖于应用核心。如果你尝试,

<body ng-app="widgets ">
<ul ng-controller="WidgetController">
<li ng-repeat="item in items">
{{item}}
</li>
</ul>
</body>

这行不通,因为在您的 ng-app="widgets" 中没有定义工厂 foo。因此,为了便于理解,将 app 模块视为两个模块的容器 [ "app.widgets", "app.core"] 在其中您可以访问所有 Controller 、工厂等,就像它们一样是应用模块本身的一部分。

关于angularjs - 模块如何访问另一个模块,即使它没有依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26630202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com