为什么我的Angular控制器未定义?

ged*_*edq 3 javascript angularjs

我一直在关注一个教程,教科书向我保证这是有效的,但它是轰炸

错误:[ng:areq]参数'SimpleController'不是函数,未定义

为什么?我已经弄明白了,上下都有,我看不出问题.为什么会SimpleController出现未定义的?

<html ng-app>
<head>
    <title>
    </title>
</head>
<body>
    <input type="text" ng-model="blah" />

    <div ng-controller="SimpleController">
        <h3>looping a data set</h3>
        <ul>
            <li ng-repeat="cust in customers | filter:blah | orderBy:'city'">
                {{cust.name | uppercase}} - {{cust.city | lowercase}}
            </li>
        </ul>
    </div>

    <script src="angular.js"></script>
    <script>
        function SimpleController($scope)
        {
            $scope.customers = [
                {name: 'John Smith', city: 'Phoenix'},
                {name: 'Jane Smith', city: 'Pittsburgh'},
                {name: 'John Doe', city: 'New York'},
                {name: 'Jane Doe', city: 'Los Angeles'}
            ];
        }
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

run*_*arm 13

我的猜测是你使用的angular.js版本是1.3.0-beta.15更新版本.

有一个重大变化,1.3.0-beta.15因此:默认情况下,angular将不再查找控制器window.详见3f2232b5:

With the exception of simple demos, it is not helpful to use globals
for controller constructors. This adds a new method to `$controllerProvider`
to re-enable the old behavior, but disables this feature by default.

BREAKING CHANGE:
`$controller` will no longer look for controllers on `window`.
The old behavior of looking on `window` for controllers was originally intended
for use in examples, demos, and toy apps. We found that allowing global controller
functions encouraged poor practices, so we resolved to disable this behavior by
default.

To migrate, register your controllers with modules rather than exposing them
as globals:
Run Code Online (Sandbox Code Playgroud)

因此,您的代码应该正常工作,就像教科书确保angular.js版本早于 1.3.0-beta.15.


agc*_*nti 6

您需要创建一个应用程序并将其注册到该应用程序,如下所示:

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

myApp.controller('SimpleController', ['$scope', function($scope) {
  $scope.customers = [
            {name: 'John Smith', city: 'Phoenix'},
            {name: 'Jane Smith', city: 'Pittsburgh'},
            {name: 'John Doe', city: 'New York'},
            {name: 'Jane Doe', city: 'Los Angeles'}
        ];
}]);
Run Code Online (Sandbox Code Playgroud)

在你的HTML中:

<html ng-app="myApp">
Run Code Online (Sandbox Code Playgroud)

在plunker中的完整示例:http://plnkr.co/edit/tBwjJU3tc6tVc599RVFR?p = preview