如何访问在不同的 .js 文件中定义的 Angular 模块?
背景:
我有点开始使用 angular js 编程(在 ASPNET MVC 应用程序中)入门指南。
为了清楚起见,我在一个名为 AspnetMvcAngular.js
的文件中创建了一个 Angular 模块。
var AspnetMvcAngularJs = angular.module('AspnetMvcAngularJs', []);
然后,我在另一个文件 (Scripts/Controllers/HomeController.js) 中定义了 Angular Controller 代码
AspnetMvcAngularJs.controller('HomeController', ['$scope', function ($scope) {
$scope.greeting = '你好!';
}]);
当应用程序运行时,它似乎无法识别 AspnetMvcAngularJs
。
关于我在这里做错了什么的任何指示?
编辑: 虽然以下答案非常好,但我注意到了一些至关重要的事情。
访问文件的顺序很重要
例如我在 ASP.NET-MVC 中使用了 bundles
,顺序应该如下所示:
bundles.Add(new ScriptBundle("~/bundles/definitions").
包括(“~/Scripts/AspnetMvcAngularJs.js”)。
IncludeDirectory("~/Scripts/Controllers", "*.js"));
这首先定义了包含 angular 模块
的 *.js
文件,然后包含其他 *.js
Controller 文件。
我犯的错误是先调用 Controller 文件。所以运行时抛出了一个错误,指出没有这样的模块可用。
最佳答案
您可以使用相同的 angular.module
语法访问已定义的模块,但无需指定模块的依赖项。在这种情况下,您将取回定义的模块,然后您可以使用它从中创建 Controller 或其他 Angular 组件。
angular.module('AspnetMvcAngularJs').controller('HomeController',['$scope', function ($scope) {
$scope.greeting = 'Hola!';
}]);)
关于javascript - 访问在不同的 .js 文件中定义的 Angular 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34590229/