【发布时间】:2015-09-29 12:37:02
【问题描述】:
我只是想了解 AngularJS 的基础知识。我尝试编写一个简单的 MVC 应用程序,但控制器似乎无法正常工作。该文件可以找到刚刚找到的角度库,我已经通过排除“ng-controller”进行了测试。
<!DOCTYPE html>
<html ng-app>
<head>
<script src='js/lib/angular.js'></script>
<script>
// controller
function MyFirstCtrl($scope) {
// model
var employees = ['Christopher Grant', 'Monica Grant', 'Christopher
Grant', 'Jennifer Grant'];
$scope.ourEmployees = employees;
}
</script>
</head>
<body ng-controller='MyFirstCtrl'>
<!-- view -->
<h2>Number of employees: {{ourEmployees.length}}</h2>
</body>
</html>
编辑: 错误日志显示如下:
Uncaught SyntaxError: Unexpected token ILLEGAL , line 9
Uncaught SyntaxError: Unexpected token { , line 19
Error: [ng:areq] Argument 'MyFirstCtrl' is not a function, got undefined
EDIT2:我将代码更改为:
<!DOCTYPE html>
<html ng-app='MVCExample'>
<head>
<script src='js/lib/angular.js'></script>
<script>
var app = angular.module('MVCExample', []);
// controller
app.controller("MyFirstCtrl", function($scope) {
// model
var employees = ['Christopher Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant'];
$scope.ourEmployees = employees;
});
</script>
</head>
<body ng-controller='MyFirstCtrl'>
<!-- view -->
<h2>Number of employees: {{ourEmployees.length}}</h2>
</body>
</html>
事实证明,我拥有的 'employees' 数组是非法的,因为我将一个字符串条目分成两行。以上工作。我正在使用的初学者书一定是过时的,这是不幸的。
【问题讨论】:
-
你能告诉我你使用的是哪个 Angular js 版本吗?
-
错误控制台说什么?确保
Christopher和Grant之间没有实际的换行符。 -
在 Angular js 1.3 + 版本中你不能声明全局控制器。
-
所以第一个错误是我在第一条评论中谈到的换行符
-
@vish 请阅读 cmets。他使用的是 1.4+ 而 1.3+ 不允许全局控制器,所以你的评论是无关紧要的
标签: angularjs model-view-controller ng-controller