首页 > 解决方案 > 模块化应用程序后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");
        }
});

标签: angularjs

解决方案


您在每个 .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";
});

推荐阅读