首页 > 解决方案 > 收到第二个控制器未注册的错误

问题描述

嗨,我正在尝试从头开始编写一个 Angular 应用程序。(新手)不断收到第二个控制器未注册的错误。为什么?

这是我的三个文件,由于某种原因,它一直说“名为“secondController”的控制器未注册。”

索引.html

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./angular.js"></script>
    <script src="./secondModule.js"></script>
    <script src="./app.js"></script>
  </head>
<body>
    <div ng-controller="appController">
       <p>App text : {{myAppText}}</p>

       <p>secondControllerModule: {{ secondControllerText }}</p>
    </div>

    <div ng-controller="secondController">
        Second Module : {{secondControllerText}}
    </div>
</body>
</html>

应用程序.js

 angular.module("myApp", [])
.controller("appController",["$scope", function($scope){
    $scope.myAppText = "Hello, I am appController text"

}])

secondModule.js

angular.module("myApp", [])
.controller("secondController",["$scope", function($scope){
    $scope.secondControllerText = "Hello, I am seasdfsdfasdfacond   Controller Text"
}])

标签: javascriptangularjsangular

解决方案


首先,我想澄清一下这是不正确的:

 <div ng-controller="appController">
           <p>App text : {{myAppText}}</p>

           <p>secondControllerModule: {{ secondControllerText }}</p>// Defined in the wrong ng-controller, 
so move it to the correct one.
        </div>

您收到该错误的原因是您在 js 文件中定义了两次应用程序模块。这很简单,你需要做的就是在你的secondModule.js中去掉第二个参数

angular.module("myApp")// Needs to be like this

.controller("secondController",["$scope", function($scope){
    $scope.secondControllerText = "Hello, I am seasdfsdfasdfacond   Controller Text"
}])

然后在你的app.js 文件中

angular.module("myApp", [])

.controller("appController",["$scope", function($scope){
    $scope.myAppText = "Hello, I am appController text"

}])

然后在您的 HTML 文件中,您需要修复脚本的顺序

  <script src="./angular.js"></script>
<script src="./app.js"></script> // App module must be first because the module is defined here
  <script src="./secondModule.js"></script>

推荐阅读