错误:[$ controller:ctrlreg]控制器名称为' ToDoCtrl'没有注册

时间:2017-11-17 20:40:43

标签: javascript angularjs

我有一个使用AngularJS 1.6.6的页面:

<!DOCTYPE html>
<html ng-app lang="en">
  <head>
    <title>AngularJS Test Page</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="angular.js"></script>
    <script src="app.js"></script>
    <link rel="stylesheet" href="bootstrap.css"/>
    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>
  </head>
  <body ng-controller="ToDoCtrl">
    <div class="page-header">
      <h1>{{todo.user}}'s To-Do List</h1>
    </div>

    <!-- Rest omitted for brevity -->
  </body>
</html>

app.js实际上只不过是以下内容:

var model = {
  user: 'Adam',
  items: [{ action: 'Buy Flowers', done: false },
          { action: 'Get Shoes', done: false },
          { action: 'Collect Tickets', done: true },
          { action: 'Call Joe', done: false }]
};

var todoApp = angular.module('todoApp', []);

angular.module('todoApp').controller('ToDoCtrl', function ($scope) {
  $scope.todo = model;
});

没有失败我在控制台上收到以下错误:

Error: [$controller:ctrlreg] The controller with the name 'ToDoCtrl' is not registered.

...尽管很明显已经注册了控制器。我的AngularJS之旅不是一个好的开始。如果您想要完整代码,可以在此处获取:

https://github.com/readyready15728/infernal-angularjs

请不要请小提琴等;我显然不能为AngularJS设置一个。

1 个答案:

答案 0 :(得分:0)

首先,我建议您阅读angular-styleguide

如果你有一个设计模式,你不会得到这样的错误。所以你可以使用你的代码:

<!DOCTYPE html>
<html ng-app="app" lang="en">
  <head>
    <title>AngularJS Test Page</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="bootstrap.css"/>
  </head>
  <body ng-controller="TodoController">
    <div class="page-header">
      <h1>{{vm.todo.user}}'s To-Do List</h1>
    </div>
    <script src="angular.js"></script>
    <script src="app.module.js"></script>
    <script src="todo.controller.js"></script>

    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>
    <!-- Rest omitted for brevity -->
  </body>
</html>

app.module.js

(function() {
    'use strict';

    angular
        .module('app', []);
})();

todo.controller.js

(function() {
    'use strict';
    angular
        .module('app')
        .controller('TodoController', TodoController);

    function TodoController($scope) { 
        var vm = this;
        vm.todo = {
                      user: 'Adam',
                      items: [{ action: 'Buy Flowers', done: false },
                              { action: 'Get Shoes', done: false },
                              { action: 'Collect Tickets', done: true },
                              { action: 'Call Joe', done: false }]};
    }

})();