尝试包含ng-controller时出错

时间:2015-12-09 01:11:22

标签: angularjs

我正在关注angular.js教程,当我尝试包含' ng-controller'时,我会遇到错误。在html标签中就像这样。

<html lang="en" ng-app ng-controller="AppCtrl">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Angular Js test</title>
    <link rel="stylesheet" href="static/css/bootstrap.min.css">
    <script src="static/js/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8" async defer></script>
    <script src="static/js/bootstrap.min.js" type="text/javascript" charset="utf-8" async defer></script>
    <script src="static/js/angular.min.js" type="text/javascript" charset="utf-8" async defer></script>
    <script src="app/controller.js" type="text/javascript" charset="utf-8" async defer></script>
</head>
<body>

<input type="text" ng-model="name">

<h1>{{name || 'World'}}</h1>

</body>
</html>

教程说要将它作为第二个属性添加到html标签中,但在Chrome浏览器中使用它时会出现以下错误

Error: [ng:areq] http://errors.angularjs.org/1.5.0-beta.2/ng/areq?p0=AppCtrl&p1=not%20a%20function%2C%20got%20undefined
    at Error (native)
    at http://test.dev/static/js/angular.min.js:6:423
    at rb (http://test.dev/static/js/angular.min.js:22:108)
    at Ra (http://test.dev/static/js/angular.min.js:22:195)
    at http://test.dev/static/js/angular.min.js:83:268
    at B (http://test.dev/static/js/angular.min.js:61:474)
    at w (http://test.dev/static/js/angular.min.js:62:403)
    at g (http://test.dev/static/js/angular.min.js:56:183)
    at http://test.dev/static/js/angular.min.js:55:329
    at http://test.dev/static/js/angular.min.js:20:103(anonymous function) @ angular.min.js:111(anonymous function) @ angular.min.js:84m.$apply @ angular.min.js:137(anonymous function) @ angular.min.js:20e @ angular.min.js:40c @ angular.min.js:19yc @ angular.min.js:20ae @ angular.min.js:19(anonymous function) @ angular.min.js:298j @ jquery-1.11.3.min.js:2k.fireWith @ jquery-1.11.3.min.js:2m.extend.ready @ jquery-1.11.3.min.js:2J @ jquery-1.11.3.min.js:2

我的控制器如下

function AppCtrl ($scope) {
    $scope.name = "World";
}

1 个答案:

答案 0 :(得分:2)

创建app.js文件

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

app.controller('AppCtrl', function($scope) {
    $scope.name = "World";
});

在index.html文件中加载app.js文件

<script src="app.js" type="text/javascript" charset="utf-8" async defer></script>
在index.html文件中

将以下内容添加到您的html标记

<html lang="en" ng-app="AppName" ng-controller="AppCtrl">

<h1>{{ name }}</h1>