angularjs - 模块化应用程序后Angular js控制器不起作用
问题描述
我是 angularjs 的新手,并按照 w3schools 的教程创建了我的第一个简单的 Angularjs 应用程序,它运行良好。在阅读了官方的 angularjs 教程后,我决定模块化我的应用程序,但现在它无法正常工作。目前我收到错误
“名为‘redController’的控制器未注册。”
我想使用它的控制器在组件“红色”中显示一条消息。我尝试更改代码的许多部分只是为了得到新的错误,似乎我搞砸了模块化:|
我正在使用 v1.6.9
这是我的目录结构
app/
scripts/
angular.min.js
angular-route.js
blue/
blue.template.html
red/
red.template.html
red.module.js
red.component.js
app.config.js
app.module.js
index.html
和源文件:
app.config.js
angular
.module("myApp", [ 'red','ngRoute' ])
.config(function($routeProvider) {
$routeProvider
.when("/red", {
templateUrl : "red/red.template.html",
controller: "redController"
})
.when("/blue", {
templateUrl : "blue/blue.template.html"
});
});
app.module.js
angular.module('myApp', [
'red',
'ngRoute'
]);
索引.html
<!DOCTYPE html>
<html>
<script src="scripts/angular.min.js"></script>
<script src="scripts/angular-route.js"></script>
<script src="app.module.js"></script>
<script src="app.config.js"></script>
<script src="red/red.module.js"></script>
<script src="red/red.component.js"></script>
<body ng-app="myApp">
<a href="#!red">Red</a>
<a href="#!blue">Blue</a>
<div ng-view></div>
<p>Click on the links to navigate "</p>
</body>
</html>
red.template.html
<h1>red</h1>
<p>{{msg}}</p>hell
red.module.js
angular.module('red', [ 'ngRoute' ]);
red.component.js
angular.module('red').component('red',{
templateUrl: 'red/red.template.html',
controller: function redController() {
this.msg = "this is red";
console.log("Hi");
}
});
解决方案
您在每个 .js 文件中一次又一次地删除模块,仅在一个 .js 文件中声明并在其余字段中使用它。
改变你的red.module.js
身份,
angular.module('red', []);
你的 app.config.js 应该是,
angular
.module("myApp")
.config(function($routeProvider) {
$routeProvider
.when("/red", {
templateUrl : "red/red.template.html",
controller: "redController"
})
.when("/blue", {
templateUrl : "blue/blue.template.html"
});
});
并更改顺序如下,
<script src="red/red.module.js"></script>
<script src="app.module.js"></script>
<script src="app.config.js"></script>
<script src="red/red.component.js"></script>
更改 red.component.js 如下
angular.module('red')
.component('red',{
templateUrl:
'red/red.template.html',
})
.controller("redController",function($scope)
{
$scope.msg ="This is red";
});
推荐阅读
- python - 当我尝试在 Windows 7 上安装 libxml2 时如何修复我的错误
- c# - 让一个方法处理两种类型的列表
- sql - 如何在 Oracle 中检查 1 对 1 关系(在一张表中)
- d3.js - D3.js - 有向无环图:如何重新排列节点和边以避免边相交
- scala - 如何将 dynamo db 表中的数据读入数据框?
- jmeter - 有没有办法在 Jmeter 的 HTTP POST 请求的正文中上传图像文件?
- wordpress - 我应该使用 WordPress 作为移动应用程序的后端吗
- arrays - 如何在反应中的对象中渲染数组内的对象?
- angular - ionic 4 AngularFireAuthGuard 问题 - 不像 github 上描述的那样工作
- powershell - 静态的 PowerShell 对象