javascript - 收到第二个控制器未注册的错误
问题描述
嗨,我正在尝试从头开始编写一个 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"
}])
解决方案
首先,我想澄清一下这是不正确的:
<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>
推荐阅读
- razor - 标准 ASP.Net Core 标签助手不是紫色和粗体
- javascript - 如何使用 jQuery Validate 验证 bootstrap-datetimepicker
- python - Python 3 上的 Werkzeug 引发“< 在 str 和 int 的实例之间不支持”
- c# - RadioButtonFor 始终将 true 传递给 MVC 控制器
- wordpress - WC:如何通过 billing_phone 或 billing_email 搜索客户
- python - Python 3:生成进程子类
- intellij-idea - Ant - 脚本中哪里出现了错误?
- python - 字典理解,项目根据属性划分为列表作为键。
- javascript - 添加到列表
- angular - 如何在 Angular 6 单元测试中依赖注入接口