源代码:
<html ng-app="countryApp"> <head> <meta charset="utf-8"> <title>Angular.js Example</title> <script src="angular/angular.js"></script> <script> var countryApp = angular.module('countryApp', []); countryApp.controller('CountryCtrl', function ($scope, $http){ var response = $http.get('angular/countries.json') response.success(function(data) { $scope.countries = data; }); }); </script> </head> <body ng-controller="CountryCtrl"> <table> <tr> <th>Country</th> <th>Population</th> </tr> <tr ng-repeat="country in countries"> <td>{{country.name}}</td> <td>{{country.population}}</td> </tr> </table> </body> </html>
这段 Angular.js 代码构建了一个简单的国家信息展示应用。它包含了 Angular.js 库的基础知识,如模块创建、控制器定义以及如何使用 $http
服务获取数据并展示到视图中。现在我们逐行详细解读这段代码,以便全面理解每一个组成部分的功能和语法。
HTML 部分
1. 基础 HTML 设置
<html ng-app=`countryApp`> <head> <meta charset=`utf-8`> <title>Angular.js Example</title> <script src=`angular/angular.js`></script>
- <html ng-app=countryApp>: 这行代码使用 ng-app 指令定义了 Angular.js 的应用模块名 countryApp。这告诉 Angular.js,在这个 <html> 元素及其子元素中启动并自动引导该模块。
- <meta charset=utf-8>: 设置网页字符集为 UTF-8,保证国际化字符的正确显示。
<script src=
angular/angular.js>
: 引入 Angular.js 库文件,使网页支持 Angular.js 功能。
2. Angular.js 脚本设置
<script> var countryApp = angular.module(`countryApp`, []); countryApp.controller(`CountryCtrl`, function ($scope, $http){ var response = $http.get(`angular/countries.json`) response.success(function(data) { $scope.countries = data; }); }); </script>
- var countryApp = angular.module(countryApp, []);: 创建名为 countryApp 的 Angular.js 模块。数组 [] 用于注入依赖,此处留空表示当前模块不依赖其他模块。
- countryApp.controller(CountryCtrl, function ($scope, $http){...});: 定义一个名为 CountryCtrl 的控制器。控制器是 MVC(Model-View-Controller)架构中的 C,用于处理数据和业务逻辑
- $scope: 是一个对象,用于将数据从控制器传递到视图。
- $http: 是 Angular.js 的服务,用于处理 HTTP 请求。
- $http.get(angular/countries.json): 发送一个 GET 请求获取位于 angular/countries.json 的数据。
- response.success(function(data) {...}): 当请求成功时,将返回的数据 data 赋值给 $scope.countries,用于在视图中显示。
视图部分
<body ng-controller=`CountryCtrl`> <table> <tr> <th>Country</th> <th>Population</th> </tr> <tr ng-repeat=`country in countries`> <td>{{country.name}}</td> <td>{{country.population}}</td> </tr> </table> </body> </html>
- <body ng-controller=CountryCtrl>: ng-controller 指令指定 CountryCtrl 控制器应用于 <body> 标签。这意味着所有在 <body> 内部的数据绑定都将通过 CountryCtrl 控制器来管理。
- <tr ng-repeat=country in countries>: ng-repeat 指令用于遍历 countries 数组。对于 countries 数组中的每一个元素,都将创建一个表格行 <tr>。这是 Angular.js 的一种常见方式,用以动态生成列表或表格数据。
- {{country.name}} 和 {{country.population}}: 这里使用插值表达式显示每个国家的名称和人口。这种双大括号标记法是 Angular.js 中绑定数据到 HTML 的简单方法。
以上就是这段代码的详细解读。通过这个示例,我们可以看到 Angular.js 在单页应用程序(SPA)开发中如何实现数据的获取、绑定和动态更新。通过 $http
服务与后端数据交互,并通过控制器和视图的紧密协作,高效地将数据展示给用户。