AngularJS - 未定义的控制器

时间:2014-12-19 17:22:07

标签: angularjs

我刚开始使用Angularjs教程,但是从第一课开始练习失败了。它是关于创建2个模块:第一个是应用程序的bootstraper,第二个是包含2个控制器。

这是代码:

app.js

'use strict';

angular.module('myApp', ['myApp.controllers'])
    .run(function ($rootScope) {
        $rootScope.title = 'Famouse books';
        $rootScope.name = 'Root Scope';
});

controllers.js

angular.module('myApp.controllers', []).controller('SiteController', function ($scope) {
    $scope.publisher = 'Site point';
    $scope.type = 'Web development';
    $scope.name = 'Scope for SiteController';
});

angular.module('myApp.controllers', []).controller('BookController', function ($scope) {
    $scope.books = ['Jump Start HTML 5', 'Jump Start CSS', 'Jump Start Responsive Web Design'];
    $scope.name = 'Scope for BookController';
});

的index.html

<!DOCTYPE html>
<html ng-app="myApp">
    <head>
        <title ng-bind="title"></title>
    </head>

    <body ng-controller="SiteController">
        <span>{{publisher}} excels in {{type}} books</span>
        <div ng-controller="BookController">
            <h3>Some of the popular books from {{publisher}}</h3>
            <ul>
                <li ng-repeat="book in books">{{book}}</li>
            </ul>
        </div>

        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
        <script src="scripts/app/controllers.js"></script>
        <script src="scripts/app/app.js"></script>
    </body>
</html>

我收到以下错误:

Bad Argument: Argument 'SiteController' is not a function, got undefined

1 个答案:

答案 0 :(得分:2)

您在第二句中添加了额外的,[]。这会创建一个新模块,因此会覆盖第一个具有&#34; SiteController&#34;已定义 - 您要添加到现有模块:

angular.module('myApp.controllers', []).controller('SiteController', function ($scope) {
    $scope.publisher = 'Site point';
    $scope.type = 'Web development';
    $scope.name = 'Scope for SiteController';
});

// you added extra ,[]
angular.module('myApp.controllers').controller('BookController', function ($scope) {
    $scope.books = ['Jump Start HTML 5', 'Jump Start CSS', 'Jump Start Responsive Web Design'];
    $scope.name = 'Scope for BookController';
});

调用angular.module('myApp.controllers', [])表示:创建模块。

调用angular.module('myApp.controllers')表示:获取模块。