在 Angular js 的不同文件中使用多个模块

Working with multiple modules in different files in Angular js

本文关键字:模块 文件 js Angular      更新时间:2023-09-26

你好,请原谅我的英语。

我的问题是这样的:我是 Angular js 的初学者(目前正在学习 1.4 版),我想将我的应用程序分为两个模块,如下所示:

应用.js

(function(){
var app = angular.module('store', ['store-products', 'ngAnimate', 'ui.bootstrap']);

    app.controller('StoreController', function(){
        ...
        });
    app.controller('ReviewController', function(){
        ...
        };
        this.rateOnClick = function(){
            ...
        };
        this.addReview = function(product){
            ...
        };
        });

    .
    .
    .
})();

产品.js

(function(){
    var app = angular.module('store-products', []);
    app.directive('productTitle', function(){
            ...
        });
    app.directive('productPanels', function(){
            ...
        });
})();

索引.html

<html>
  <head>
    <title>My Angular App!</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-animate.js"></script>
    <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.2.4.js"></script>
    <link href="styles.css" rel="stylesheet">
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <script src="app.js"></script>
    <script src"products.js"></script>
...
</html>

我的所有文件都在同一个文件夹中.app.js是主模块,所以据我了解,包含很好,但我仍然收到错误:

Uncaught Error: [$injector:modulerr] Failed to instantiate module store due to:
Error: [$injector:modulerr] Failed to instantiate module store-products due to:
Error: [$injector:nomod] Module 'store-products' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

有人想不通为什么会这样吗?

哈哈,刚刚想通,问题是这行:

<script src"products.js"></script>

像这样修复:

<script src="products.js"></script>

您需要在应用脚本之前包含产品脚本。

不要在应用中包含商店产品.js代码,因为在此 [ ] 中我们添加了指令,并且没有指令名称"商店产品"