60 分钟内的 Angular - 这段代码有什么问题

Angular in 60ish minutes - What's wrong with this code?

本文关键字:代码 问题 什么 段代码 分钟 Angular      更新时间:2023-09-26

我已经开始学习 Angular,并在 60 分钟内学习 Angular 作为第一步。在第 48 页上,有一个如下所示的示例代码,它是在页面中显示customers属性内容的simple controller

<!DOCTYPE html>
<html ng-app="">
<head>
	<title></title>
</head>
<body>
	
	<div class="container" ng-controller="SimpleController">
		<h3>Adding a simple controller</h3>
		<ul>
			<li ng-repeat="cust in customers">
				{{cust.name}} - {{cust.city}}
			</li>
		</ul>
	</div>
	<script>
		function SimpleController($scope) {
			$scope.customers = [
				{name: 'John Doe', city: 'New York'},
				{name: 'Jane Doe', city: 'Miami'},
				{name: 'Moan Doe', city: 'Montreal'}
			];
		}
	</script>
	<script src="/usr/local/angular-1.3.16/angular.js"></script>
</body>
</html>

预期输出为:

添加简单控制器

  • 约翰·多伊 - 纽约
  • 简·多伊 - 迈阿密
  • 呻吟 - 蒙特利尔

但是我看不到项目符号项目。我已经拔头发有一段时间了。以为我会在秃顶之前问问社区。有人可以告诉我这段代码有什么问题吗?

使用 1.3.16 版,您不能再只声明全局控制器函数。相反,定义一个模块和一个控制器:

angular.module('app', []).controller('SimpleController', function ($scope) {
            $scope.customers = [
                {name: 'John Doe', city: 'New York'},
                {name: 'Jane Doe', city: 'Miami'},
                {name: 'Moan Doe', city: 'Montreal'}
            ];
        });

在 html 中,添加具有正确模块名称的ng-app

<body ng-app="app">

修复代码的两个项目。

  1. 我一直在摆弄,认为标签的顺序确实很重要。对angular.js<script>标记引用应首先出现在包含控制器方法的<script>标记之前。

  2. 正如@user3906922建议的那样,全局控制器函数在角度 1.3.16 中没有帮助。我定义了一个模块和控制器,它工作了。