首页 > 解决方案 > 模块在 angularjs 中不可用

问题描述

索引.html

<!DOCTYPE html>
<html ng-app="intervieweeApp">
<head>
    <meta charset="utf-8" />
    <title>Interviewee Evaluation</title>

    <script src="Scripts/jquery-3.3.1.js"></script>
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/bootstrap.js"></script>
    <script src="Scripts/angular-route.js"></script>
    <script src="Scripts/angular-messages.js"></script>

    <script src="app.js"></script>
    <script src="app.module.js"></script>
    <script src="app.config.js"></script>

    <script src="home-view/home-view.component.js"></script>
    <script src="home-view/home-view.module.js"></script>
</head>
<body>
    <p>does it work?</p>
    <a href="#!home">go to home!</a>
</body>
</html>

应用程序.js

var intervieweeApp = angular.module('intervieweeApp', []);

app.module.js

var intervieweeApp = angular.module('intervieweeApp', [
    'ngRoute',
    'ngMessages',
    'homeView'
]);

app.config.js

angular.
  module('intervieweeApp').
  config(['$routeProvider',
    function config($routeProvider) {
      $routeProvider.
        when('/home', {
          template: '<home-view></home-view>'
        }).
        otherwise('/home');
    }
  ]);
     

主页视图/主页视图.module.js

angular.module('homeView', []);

主页视图/主页视图.component.js

angular.
    module('homeView').
    component('homeView', {
        templateUrl: 'home-view/home-view.template.html',
        controller: ['$http',
            function PhoneListController($http) {
                console.log(15);
            }
        ]
    });

主页视图/主页视图.template.html

 <p> at home </p>

错误

模块“homeView”不可用!您要么拼错了模块名称,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。 https://errors.angularjs.org/1.7.5/$injector/nomod?p0=homeView

当我加载 index.html 时,我得到了这个错误。我究竟做错了什么?谢谢

标签: angularjs

解决方案


看看工作中的 DEMO

script由于带有标签的 js 文件导入顺序,您遇到了问题

创建模块时的最佳实践是使用IIFE。这有助于您不必考虑js在 index.html 中导入文件的顺序

app.module.ts

(function(){
  angular.module('intervieweeApp', [
    'ngRoute',
    'homeView'
  ]);
})()

主页-view.module.ts

(function(){
  angular.module('homeView', []);
})()

大多数开源 js 插件都使用相同的 IIFE 概念,因此它是一种标准做法


推荐阅读