Hi Im试图从头开始编写一个有角度的应用程序。 (它的新功能)不断收到未注册secondController的错误。为什么?

问题描述 投票:0回答:1

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

index.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>

app.js




.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"
}])

angularjs
1个回答
0
投票

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

 <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"
}])

然后在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>

0
投票

我认为根据您的代码,您应该将三个文件1.在module.js文件中声明angular模块

var app = angular.module("myApp", []);
  1. 添加第一个控制器appController.js

    app.controller(“ appController”,[“ $ scope”,function($ scope){

    $$ scope.myAppText =“你好,我是appController文本”;

    }]);

  2. 添加第二个控制器文件secondController.js

    app.controller(“ secondController”,[“ $ scope”,function($ scope){$ scope.secondControllerText =“你好,我是seasdfsdfasdfacond控制器文本”;}]);

现在将它们置于此层次结构中-添加Angular JS的引用然后1module.js2appController.js3 secondController.js

© www.soinside.com 2019 - 2024. All rights reserved.