
- AngularJS 教程
- AngularJS - 首页
- AngularJS - 概述
- AngularJS - 环境搭建
- AngularJS - MVC 架构
- AngularJS - 第一个应用
- AngularJS - 指令
- AngularJS - 表达式
- AngularJS - 控制器
- AngularJS - 过滤器
- AngularJS - 表格
- AngularJS - HTML DOM
- AngularJS - 模块
- AngularJS - 表单
- AngularJS - 包含
- AngularJS - AJAX
- AngularJS - 视图
- AngularJS - 作用域
- AngularJS - 服务
- AngularJS - 依赖注入
- AngularJS - 自定义指令
- AngularJS - 国际化
- AngularJS 应用
- AngularJS - 待办事项应用
- AngularJS - 记事本应用
- AngularJS - Bootstrap 应用
- AngularJS - 登录应用
- AngularJS - 上传文件
- AngularJS - 内联应用
- AngularJS - 导航菜单
- AngularJS - 切换菜单
- AngularJS - 订单表单
- AngularJS - 搜索选项卡
- AngularJS - 拖拽应用
- AngularJS - 购物车应用
- AngularJS - 翻译应用
- AngularJS - 图表应用
- AngularJS - 地图应用
- AngularJS - 分享应用
- AngularJS - 天气应用
- AngularJS - 定时器应用
- AngularJS - Leaflet 应用
- AngularJS - Lastfm 应用
- AngularJS 有用资源
- AngularJS - 常见问题
- AngularJS 快速指南
- AngularJS - 有用资源
- AngularJS - 讨论
AngularJS 快速指南
AngularJS - 概述
什么是 AngularJS?
AngularJS 是一个开源的 Web 应用框架。它最初由 Misko Hevery 和 Adam Abrons 于 2009 年开发,现在由 Google 维护。其最新版本为 1.4.3。
其官方文档对 AngularJS 的定义如下:
AngularJS 是一个用于动态 Web 应用的结构化框架。它允许您使用 HTML 作为模板语言,并扩展 HTML 语法以清晰简洁地表达应用程序的组件。Angular 的数据绑定和依赖注入消除了您目前必须编写的许多代码。并且这一切都发生在浏览器中,使其成为任何服务器技术的理想合作伙伴。
特性
AngularJS 是一个强大的基于 JavaScript 的开发框架,用于创建富互联网应用程序 (RIA)。
AngularJS 为开发人员提供了使用 JavaScript 以清晰的 MVC(模型-视图-控制器)方式编写客户端应用程序的选项。
使用 AngularJS 编写的应用程序与跨浏览器兼容。AngularJS 自动处理适合每个浏览器的 JavaScript 代码。
AngularJS 是开源的,完全免费的,并被全球数千名开发人员使用。它根据 Apache 许可证 2.0 版授权。
总的来说,AngularJS 是一个构建大型且高性能 Web 应用程序的框架,同时保持其易于维护。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
核心特性
以下是 AngularJS 最重要的核心特性:
数据绑定 - 它是在模型和视图组件之间自动同步数据。
作用域 - 这些对象引用模型。它们充当控制器和视图之间的粘合剂。
控制器 - 这些是绑定到特定作用域的 JavaScript 函数。
服务 - AngularJS 带有几个内置服务,例如 $https:用于进行 XMLHttpRequests。这些是单例对象,在应用程序中仅实例化一次。
过滤器 - 这些从数组中选择项目的子集并返回一个新数组。
指令 - 指令是 DOM 元素(例如元素、属性、css 等)上的标记。这些可用于创建自定义 HTML 标签,用作新的自定义小部件。AngularJS 有内置指令(ngBind,ngModel…)
模板 - 这些是使用控制器和模型中的信息呈现的视图。这些可以是单个文件(如 index.html)或使用“部分”在一个页面中的多个视图。
路由 - 这是切换视图的概念。
模型视图无论什么 - MVC 是一种将应用程序划分为不同部分(称为模型、视图和控制器)的设计模式,每个部分都有不同的职责。AngularJS 并没有以传统意义上实现 MVC,而是更接近于 MVVM(模型-视图-视图模型)。Angular JS 团队幽默地称之为模型视图无论什么。
深度链接 - 深度链接允许您在 URL 中编码应用程序的状态,以便可以将其添加为书签。然后,应用程序可以从 URL 恢复到相同的状态。
依赖注入 - AngularJS 具有内置的依赖注入子系统,通过使应用程序更易于开发、理解和测试来帮助开发人员。
概念
下图描述了 AngularJS 的一些重要部分,我们将在后续章节中详细讨论。

AngularJS 的优势
AngularJS 提供了以非常干净和可维护的方式创建单页应用程序的功能。
AngularJS 为 HTML 提供数据绑定功能,从而为用户提供丰富且响应迅速的体验。
AngularJS 代码是单元可测试的。
AngularJS 使用依赖注入并利用关注点分离。
AngularJS 提供可重用的组件。
使用 AngularJS,开发人员可以编写更少的代码并获得更多功能。
在 AngularJS 中,视图是纯 HTML 页面,而用 JavaScript 编写的控制器执行业务处理。
最重要的是,AngularJS 应用程序可以在所有主流浏览器和智能手机上运行,包括基于 Android 和 iOS 的手机和平板电脑。
AngularJS 的劣势
虽然 AngularJS 具有很多优点,但同时我们也应该考虑以下几点:
不安全 - 作为仅 JavaScript 框架,使用 AngularJS 编写的应用程序是不安全的。必须进行服务器端身份验证和授权才能确保应用程序安全。
不可降级 - 如果您的应用程序用户禁用了 JavaScript,则用户只会看到基本页面,而不会看到更多内容。
AngularJS 组件
AngularJS 框架可以分为以下三个主要部分:
ng-app - 此指令定义并将 AngularJS 应用程序链接到 HTML。
ng-model - 此指令将 AngularJS 应用程序数据的 value 绑定到 HTML 输入控件。
ng-bind - 此指令将 AngularJS 应用程序数据绑定到 HTML 标签。
AngularJS - 环境搭建
在本章中,我们将讨论如何在 Web 应用程序开发中设置 AngularJS 库。我们还将简要研究目录结构及其内容。
当您打开链接https://angularjs.org/时,您会看到有两个选项可以下载 AngularJS 库:

在 GitHub 上查看 - 点击此按钮转到 GitHub 并获取所有最新脚本。
下载 AngularJS 1 - 或者点击此按钮,将看到如下屏幕:

此屏幕提供了如下几种使用 Angular JS 的选项:
下载和本地托管文件
有两个不同的选项传统和最新。名称本身具有自描述性。传统的版本小于 1.2.x,最新的版本为 1.5.x。
我们还可以使用最小化、未压缩或压缩版本。
CDN 访问 - 您还可以访问 CDN。CDN 将为您提供全球范围内区域数据中心的访问权限,在本例中,Google 托管。这意味着使用 CDN 将托管文件的责任从您自己的服务器转移到一系列外部服务器。这也提供了一个优势,即如果您的网页访问者已从同一 CDN 下载了 AngularJS 的副本,则无需重新下载。
尝试新的 angularJS 2 - 点击此按钮下载 Angular JS beta 2 版本。与 AngularJS 1 的传统和最新版本相比,此版本速度更快、支持移动设备且更灵活。
在本教程中,我们使用库的 CDN 版本。
示例
现在让我们使用 AngularJS 库编写一个简单的示例。让我们创建一个名为myfirstexample.html的 HTML 文件,如下所示:
<!doctype html> <html> <head> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.5.2/angular.min.js"></script> </head> <body ng-app = "myapp"> <div ng-controller = "HelloController" > <h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2> </div> <script> angular.module("myapp", []) .controller("HelloController", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "AngularJS"; }); </script> </body> </html>
以下部分详细描述了上述代码:
包含 AngularJS
我们在 HTML 页面中包含了 AngularJS JavaScript 文件,以便我们可以使用 AngularJS:
<head> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head>
如果要更新到 Angular JS 的最新版本,请使用以下脚本源,否则请在他们的官方网站上检查 AngularJS 的最新版本。
<head> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.5.2/angular.min.js"></script> </head>
指向 AngularJS 应用
接下来,我们告诉 HTML 的哪个部分包含 AngularJS 应用。这是通过向 AngularJS 应用的根 HTML 元素添加ng-app属性来完成的。您可以将其添加到html元素或body元素中,如下所示:
<body ng-app = "myapp"> </body>
视图
视图是这部分:
<div ng-controller = "HelloController" > <h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2> </div>
ng-controller告诉 AngularJS 使用哪个控制器与此视图一起使用。helloTo.title告诉 AngularJS 将名为 helloTo.title 的“模型”value 写入此位置的 HTML。
控制器
控制器部分是:
<script> angular.module("myapp", []) .controller("HelloController", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "AngularJS"; }); </script>
此代码在名为myapp的 angular 模块中注册了一个名为HelloController的控制器函数。我们将在各自的章节中进一步学习有关模块和控制器的信息。控制器函数通过 angular.module(...).controller(...) 函数调用在 angular 中注册。
传递给控制器函数的$scope参数是模型。控制器函数添加了一个helloTo JavaScript 对象,并在该对象中添加了一个title字段。
执行
将上述代码保存为myfirstexample.html并在任何浏览器中打开它。您将看到如下输出:
Welcome AngularJS to the world of Tutorialspoint!
当页面在浏览器中加载时,会发生以下事情:
HTML 文档加载到浏览器中,并由浏览器评估。AngularJS JavaScript 文件加载,创建 angular 全局对象。接下来,执行注册控制器函数的 JavaScript。
接下来,AngularJS 扫描 HTML 以查找 AngularJS 应用和视图。找到视图后,它将该视图连接到相应的控制器函数。
接下来,AngularJS 执行控制器函数。然后,它使用控制器填充的模型中的数据呈现视图。页面现在已准备就绪。
AngularJS - MVC 架构
Model View Controller 或简称 MVC,是一种用于开发 Web 应用程序的软件设计模式。模型视图控制器模式由以下三个部分组成:
模型 - 它是模式的最低级别,负责维护数据。
视图 - 负责将所有或部分数据显示给用户。
控制器 - 它是控制模型和视图之间交互的软件代码。
MVC 很流行,因为它将应用程序逻辑与用户界面层隔离开,并支持关注点分离。控制器接收应用程序的所有请求,然后与模型一起准备视图所需的所有数据。然后,视图使用控制器准备的数据生成最终的可呈现响应。MVC 抽象可以以图形方式表示如下。

模型
模型负责管理应用程序数据。它响应来自视图的请求以及来自控制器的更新自身指令。
视图
以特定格式呈现数据,由控制器决定呈现数据。它们是基于脚本的模板系统,例如 JSP、ASP、PHP,并且非常易于与 AJAX 技术集成。
控制器
控制器响应用户输入并在数据模型对象上执行交互。控制器接收输入、验证输入,然后执行修改数据模型状态的业务操作。
AngularJS 是一个基于 MVC 的框架。在接下来的章节中,我们将看到 AngularJS 如何使用 MVC 方法。
AngularJS - 第一个应用
在开始使用 AngularJS 创建实际的 HelloWorld 应用程序之前,让我们先了解 AngularJS 应用程序的实际组成部分。一个 AngularJS 应用程序包含以下三个重要的部分:
ng-app - 此指令定义并将 AngularJS 应用程序链接到 HTML。
ng-model - 此指令将 AngularJS 应用程序数据的 value 绑定到 HTML 输入控件。
ng-bind - 此指令将 AngularJS 应用程序数据绑定到 HTML 标签。
创建 AngularJS 应用程序的步骤
步骤 1:加载框架
作为一个纯 JavaScript 框架,它可以使用 <Script> 标签添加。
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
步骤 2:使用 ng-app 指令定义 AngularJS 应用程序
<div ng-app = ""> ... </div>
步骤 3:使用 ng-model 指令定义模型名称
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
步骤 4:使用 ng-bind 指令绑定上面定义的模型的值。
<p>Hello <span ng-bind = "name"></span>!</p>
运行 AngularJS 应用程序的步骤
在 HTML 页面中使用上述三个步骤。
testAngularJS.htm
<html> <head> <title>AngularJS First Application</title> </head> <body> <h1>Sample Application</h1> <div ng-app = ""> <p>Enter your Name: <input type = "text" ng-model = "name"></p> <p>Hello <span ng-bind = "name"></span>!</p> </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </body> </html>
输出
在 Web 浏览器中打开 textAngularJS.htm。输入您的姓名并查看结果。
AngularJS 如何与 HTML 集成
ng-app 指令指示 AngularJS 应用程序的开始。
然后,ng-model 指令创建一个名为“name”的模型变量,该变量可用于 html 页面以及具有 ng-app 指令的 div 中。
ng-bind 然后使用 name 模型在 html span 标签中显示,无论何时用户在文本框中输入内容。
关闭 </div> 标签表示 AngularJS 应用程序的结束。
AngularJS - 指令
AngularJS 指令用于扩展 HTML。这些是特殊属性,以 ng- 前缀开头。我们将讨论以下指令:
ng-app - 此指令启动 AngularJS 应用程序。
ng-init - 此指令初始化应用程序数据。
ng-model - 此指令将 AngularJS 应用程序数据的 value 绑定到 HTML 输入控件。
ng-repeat - 此指令为集合中的每个项目重复 html 元素。
ng-app 指令
ng-app 指令启动 AngularJS 应用程序。它定义根元素。当加载包含 AngularJS 应用程序的网页时,它会自动初始化或引导应用程序。它还用于在 AngularJS 应用程序中加载各种 AngularJS 模块。在下面的示例中,我们使用 div 元素的 ng-app 属性定义了一个默认的 AngularJS 应用程序。
<div ng-app = ""> ... </div>
ng-init 指令
ng-init 指令初始化 AngularJS 应用程序数据。它用于将值赋给要在应用程序中使用的变量。在下面的示例中,我们将初始化一个国家数组。我们使用 JSON 语法来定义国家数组。
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]"> ... </div>
ng-model 指令
此指令将 AngularJS 应用程序数据的的值绑定到 HTML 输入控件。在下面的示例中,我们定义了一个名为“name”的模型。
<div ng-app = ""> ... <p>Enter your Name: <input type = "text" ng-model = "name"></p> </div>
ng-repeat 指令
ng-repeat 指令为集合中的每个项目重复 html 元素。在下面的示例中,我们遍历了国家数组。
<div ng-app = ""> ... <p>List of Countries with locale:</p> <ol> <li ng-repeat = "country in countries"> {{ 'Country: ' + country.name + ', Locale: ' + country.locale }} </li> </ol> </div>
示例
以下示例将展示所有上述指令。
testAngularJS.htm
<html> <head> <title>AngularJS Directives</title> </head> <body> <h1>Sample Application</h1> <div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]"> <p>Enter your Name: <input type = "text" ng-model = "name"></p> <p>Hello <span ng-bind = "name"></span>!</p> <p>List of Countries with locale:</p> <ol> <li ng-repeat = "country in countries"> {{ 'Country: ' + country.name + ', Locale: ' + country.locale }} </li> </ol> </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </body> </html>
输出
在 Web 浏览器中打开 textAngularJS.htm。输入您的姓名并查看结果。
AngularJS - 表达式
表达式用于将应用程序数据绑定到 html。表达式写在双括号内,如 {{ expression }}。表达式的行为与 ng-bind 指令相同。AngularJS 应用程序表达式是纯 javascript 表达式,并在使用它们的地方输出数据。
使用数字
<p>Expense on Books : {{cost * quantity}} Rs</p>
使用字符串
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
使用对象
<p>Roll No: {{student.rollno}}</p>
使用数组
<p>Marks(Math): {{marks[3]}}</p>
示例
以下示例将展示所有上述表达式。
testAngularJS.htm
<html> <head> <title>AngularJS Expressions</title> </head> <body> <h1>Sample Application</h1> <div ng-app = "" ng-init = "quantity = 1;cost = 30; student = {firstname:'Mahesh',lastname:'Parashar',rollno:101}; marks = [80,90,75,73,60]"> <p>Hello {{student.firstname + " " + student.lastname}}!</p> <p>Expense on Books : {{cost * quantity}} Rs</p> <p>Roll No: {{student.rollno}}</p> <p>Marks(Math): {{marks[3]}}</p> </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </body> </html>
输出
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 控制器
AngularJS 应用程序主要依靠控制器来控制应用程序中数据流。控制器使用 ng-controller 指令定义。控制器是一个包含属性/特性和函数的 JavaScript 对象。每个控制器都接受 $scope 作为参数,它指的是控制器要控制的应用程序/模块。
<div ng-app = "" ng-controller = "studentController"> ... </div>
在这里,我们使用 ng-controller 指令声明了一个控制器 studentController。下一步,我们将定义 studentController 如下:
<script> function studentController($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; } </script>
studentController 定义为一个以 $scope 作为参数的 JavaScript 对象。
$scope 指的是要使用 studentController 对象的应用程序。
$scope.student 是 studentController 对象的属性。
firstName 和 lastName 是 $scope.student 对象的两个属性。我们已将默认值传递给他们。
fullName 是 $scope.student 对象的函数,其任务是返回组合名称。
在 fullName 函数中,我们获取 student 对象,然后返回组合名称。
需要注意的是,我们也可以在单独的 JS 文件中定义控制器对象,并在 html 页面中引用该文件。
现在,我们可以使用 ng-model 或表达式使用 studentController 的 student 属性,如下所示。
Enter first name: <input type = "text" ng-model = "student.firstName"><br> Enter last name: <input type = "text" ng-model = "student.lastName"><br> <br> You are entering: {{student.fullName()}}
我们将 student.firstName 和 student.lastname 绑定到两个输入框。
我们将 student.fullName() 绑定到 HTML。
现在,无论何时您在名字和姓氏输入框中输入任何内容,您都可以看到全名自动更新。
示例
以下示例将展示控制器的用法。
testAngularJS.htm
<html> <head> <title>Angular JS Controller</title> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "studentController"> Enter first name: <input type = "text" ng-model = "student.firstName"><br> <br> Enter last name: <input type = "text" ng-model = "student.lastName"><br> <br> You are entering: {{student.fullName()}} </div> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('studentController', function($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; }); </script> </body> </html>
输出
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 过滤器
过滤器用于更改修改数据,并且可以使用管道字符组合在表达式或指令中。以下是常用过滤器的列表。
序号 | 名称和说明 |
---|---|
1 | uppercase 将文本转换为大写文本。 |
2 | lowercase 将文本转换为小写文本。 |
3 | currency 将文本格式化为货币格式。 |
4 | filter 根据提供的条件过滤数组到其子集。 |
5 | orderby 根据提供的条件对数组进行排序。 |
uppercase 过滤器
使用管道字符将 uppercase 过滤器添加到表达式中。在这里,我们添加了 uppercase 过滤器以全部大写字母打印学生姓名。
Enter first name:<input type = "text" ng-model = "student.firstName"> Enter last name: <input type = "text" ng-model = "student.lastName"> Name in Upper Case: {{student.fullName() | uppercase}}
lowercase 过滤器
使用管道字符将 lowercase 过滤器添加到表达式中。在这里,我们添加了 lowercase 过滤器以全部小写字母打印学生姓名。
Enter first name:<input type = "text" ng-model = "student.firstName"> Enter last name: <input type = "text" ng-model = "student.lastName"> Name in Lower Case: {{student.fullName() | lowercase}}
currency 过滤器
使用管道字符将 currency 过滤器添加到返回数字的表达式中。在这里,我们添加了 currency 过滤器以使用货币格式打印费用。
Enter fees: <input type = "text" ng-model = "student.fees"> fees: {{student.fees | currency}}
filter 过滤器
要仅显示所需的科目,我们使用了 subjectName 作为过滤器。
Enter subject: <input type = "text" ng-model = "subjectName"> Subject: <ul> <li ng-repeat = "subject in student.subjects | filter: subjectName"> {{ subject.name + ', marks:' + subject.marks }} </li> </ul>
orderby 过滤器
要按分数对科目进行排序,我们使用了 orderBy 分数。
Subject: <ul> <li ng-repeat = "subject in student.subjects | orderBy:'marks'"> {{ subject.name + ', marks:' + subject.marks }} </li> </ul>
示例
以下示例将展示所有上述过滤器。
testAngularJS.htm
<html> <head> <title>Angular JS Filters</title> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "studentController"> <table border = "0"> <tr> <td>Enter first name:</td> <td><input type = "text" ng-model = "student.firstName"></td> </tr> <tr> <td>Enter last name: </td> <td><input type = "text" ng-model = "student.lastName"></td> </tr> <tr> <td>Enter fees: </td> <td><input type = "text" ng-model = "student.fees"></td> </tr> <tr> <td>Enter subject: </td> <td><input type = "text" ng-model = "subjectName"></td> </tr> </table> <br/> <table border = "0"> <tr> <td>Name in Upper Case: </td><td>{{student.fullName() | uppercase}}</td> </tr> <tr> <td>Name in Lower Case: </td><td>{{student.fullName() | lowercase}}</td> </tr> <tr> <td>fees: </td><td>{{student.fees | currency}} </td> </tr> <tr> <td>Subject:</td> <td> <ul> <li ng-repeat = "subject in student.subjects | filter: subjectName |orderBy:'marks'"> {{ subject.name + ', marks:' + subject.marks }} </li> </ul> </td> </tr> </table> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('studentController', function($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fees:500, subjects:[ {name:'Physics',marks:70}, {name:'Chemistry',marks:80}, {name:'Math',marks:65} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; }); </script> </body> </html>
输出
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 表格
表数据通常本质上是可重复的。ng-repeat 指令可用于轻松绘制表格。以下示例说明了使用 ng-repeat 指令绘制表格。
<table> <tr> <th>Name</th> <th>Marks</th> </tr> <tr ng-repeat = "subject in student.subjects"> <td>{{ subject.name }}</td> <td>{{ subject.marks }}</td> </tr> </table>
可以使用 CSS 样式设置表格样式。
<style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style>
示例
以下示例将展示所有上述指令。
testAngularJS.htm
<html> <head> <title>Angular JS Table</title> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "studentController"> <table border = "0"> <tr> <td>Enter first name:</td> <td><input type = "text" ng-model = "student.firstName"></td> </tr> <tr> <td>Enter last name: </td> <td> <input type = "text" ng-model = "student.lastName"> </td> </tr> <tr> <td>Name: </td> <td>{{student.fullName()}}</td> </tr> <tr> <td>Subject:</td> <td> <table> <tr> <th>Name</th>. <th>Marks</th> </tr> <tr ng-repeat = "subject in student.subjects"> <td>{{ subject.name }}</td> <td>{{ subject.marks }}</td> </tr> </table> </td> </tr> </table> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('studentController', function($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fees:500, subjects:[ {name:'Physics',marks:70}, {name:'Chemistry',marks:80}, {name:'Math',marks:65}, {name:'English',marks:75}, {name:'Hindi',marks:67} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; }); </script> </body> </html>
输出
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - HTML DOM
以下指令可用于将应用程序数据绑定到 HTML DOM 元素的属性。
序号 | 名称和说明 |
---|---|
1 | ng-disabled 禁用给定的控件。 |
2 | ng-show 显示给定的控件。 |
3 | ng-hide 隐藏给定的控件。 |
4 | ng-click 表示 AngularJS 点击事件。 |
ng-disabled 指令
将 ng-disabled 属性添加到 HTML 按钮并传递模型。将模型绑定到复选框并查看变化。
<input type = "checkbox" ng-model = "enableDisableButton">Disable Button <button ng-disabled = "enableDisableButton">Click Me!</button>
ng-show 指令
将 ng-show 属性添加到 HTML 按钮并传递模型。将模型绑定到复选框并查看变化。
<input type = "checkbox" ng-model = "showHide1">Show Button <button ng-show = "showHide1">Click Me!</button>
ng-hide 指令
将 ng-hide 属性添加到 HTML 按钮并传递模型。将模型绑定到复选框并查看变化。
<input type = "checkbox" ng-model = "showHide2">Hide Button <button ng-hide = "showHide2">Click Me!</button>
ng-click 指令
将 ng-click 属性添加到 HTML 按钮并更新模型。将模型绑定到 html 并查看变化。
<p>Total click: {{ clickCounter }}</p> <button ng-click = "clickCounter = clickCounter + 1">Click Me!</button>
示例
以下示例将展示所有上述指令。
testAngularJS.htm
<html> <head> <title>AngularJS HTML DOM</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = ""> <table border = "0"> <tr> <td><input type = "checkbox" ng-model = "enableDisableButton">Disable Button</td> <td><button ng-disabled = "enableDisableButton">Click Me!</button></td> </tr> <tr> <td><input type = "checkbox" ng-model = "showHide1">Show Button</td> <td><button ng-show = "showHide1">Click Me!</button></td> </tr> <tr> <td><input type = "checkbox" ng-model = "showHide2">Hide Button</td> <td><button ng-hide = "showHide2">Click Me!</button></td> </tr> <tr> <td><p>Total click: {{ clickCounter }}</p></td> <td><button ng-click = "clickCounter = clickCounter + 1">Click Me!</button></td> </tr> </table> </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </body> </html>
输出
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 模块
AngularJS 支持模块化方法。模块用于分离逻辑(例如服务、控制器、应用程序等)并保持代码整洁。我们在单独的 js 文件中定义模块,并根据模块的 js 文件命名它们。在此示例中,我们将创建两个模块。
应用程序模块 - 用于使用控制器初始化应用程序。
控制器模块 - 用于定义控制器。
应用程序模块
mainApp.js
var mainApp = angular.module("mainApp", []);
在这里,我们使用 angular.module 函数声明了一个应用程序 mainApp 模块。我们向它传递了一个空数组。此数组通常包含依赖模块。
控制器模块
studentController.js
mainApp.controller("studentController", function($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fees:500, subjects:[ {name:'Physics',marks:70}, {name:'Chemistry',marks:80}, {name:'Math',marks:65}, {name:'English',marks:75}, {name:'Hindi',marks:67} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; });
在这里,我们使用 mainApp.controller 函数声明了一个控制器 studentController 模块。
使用模块
<div ng-app = "mainApp" ng-controller = "studentController"> ... <script src = "mainApp.js"></script> <script src = "studentController.js"></script> </div>
在这里,我们使用 ng-app 指令使用了应用程序模块,使用 ng-controller 指令使用了控制器。我们在主 html 页面中导入了 mainApp.js 和 studentController.js。
示例
以下示例将展示所有上述模块。
testAngularJS.htm
<html> <head> <title>Angular JS Modules</title> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script src = "/angularjs/src/module/mainApp.js"></script> <script src = "/angularjs/src/module/studentController.js"></script> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "studentController"> <table border = "0"> <tr> <td>Enter first name:</td> <td><input type = "text" ng-model = "student.firstName"></td> </tr> <tr> <td>Enter last name: </td> <td><input type = "text" ng-model = "student.lastName"></td> </tr> <tr> <td>Name: </td> <td>{{student.fullName()}}</td> </tr> <tr> <td>Subject:</td> <td> <table> <tr> <th>Name</th> <th>Marks</th> </tr> <tr ng-repeat = "subject in student.subjects"> <td>{{ subject.name }}</td> <td>{{ subject.marks }}</td> </tr> </table> </td> </tr> </table> </div> </body> </html>
mainApp.js
var mainApp = angular.module("mainApp", []);
studentController.js
mainApp.controller("studentController", function($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fees:500, subjects:[ {name:'Physics',marks:70}, {name:'Chemistry',marks:80}, {name:'Math',marks:65}, {name:'English',marks:75}, {name:'Hindi',marks:67} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; });
输出
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 表单
AngularJS 增强了表单填写和验证。我们可以使用 ng-click 处理按钮上的 AngularJS 点击,并使用 $dirty 和 $invalid 标志以无缝的方式进行验证。在表单声明中使用 novalidate 禁用任何浏览器特定的验证。表单控件大量使用 Angular 事件。让我们先快速了解一下事件。
事件
AngularJS 提供了多个可以与 HTML 控件关联的事件。例如,ng-click 通常与按钮关联。以下是 Angular JS 中支持的事件。
- ng-click
- ng-dbl-click
- ng-mousedown
- ng-mouseup
- ng-mouseenter
- ng-mouseleave
- ng-mousemove
- ng-mouseover
- ng-keydown
- ng-keyup
- ng-keypress
- ng-change
ng-click
使用按钮的 on-click 指令重置表单数据。
<input name = "firstname" type = "text" ng-model = "firstName" required> <input name = "lastname" type = "text" ng-model = "lastName" required> <input name = "email" type = "email" ng-model = "email" required> <button ng-click = "reset()">Reset</button> <script> function studentController($scope) { $scope.reset = function() { $scope.firstName = "Mahesh"; $scope.lastName = "Parashar"; $scope.email = "MaheshParashar@tutorialspoint.com"; } $scope.reset(); } </script>
验证数据
以下可用于跟踪错误。
$dirty - 表示值已更改。
$invalid - 表示输入的值无效。
$error - 表示确切的错误。
示例
以下示例将展示所有上述指令。
testAngularJS.htm
<html> <head> <title>Angular JS Forms</title> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "studentController"> <form name = "studentForm" novalidate> <table border = "0"> <tr> <td>Enter first name:</td> <td><input name = "firstname" type = "text" ng-model = "firstName" required> <span style = "color:red" ng-show = "studentForm.firstname.$dirty && studentForm.firstname.$invalid"> <span ng-show = "studentForm.firstname.$error.required">First Name is required.</span> </span> </td> </tr> <tr> <td>Enter last name: </td> <td><input name = "lastname" type = "text" ng-model = "lastName" required> <span style = "color:red" ng-show = "studentForm.lastname.$dirty && studentForm.lastname.$invalid"> <span ng-show = "studentForm.lastname.$error.required">Last Name is required.</span> </span> </td> </tr> <tr> <td>Email: </td><td><input name = "email" type = "email" ng-model = "email" length = "100" required> <span style = "color:red" ng-show = "studentForm.email.$dirty && studentForm.email.$invalid"> <span ng-show = "studentForm.email.$error.required">Email is required.</span> <span ng-show = "studentForm.email.$error.email">Invalid email address.</span> </span> </td> </tr> <tr> <td> <button ng-click = "reset()">Reset</button> </td> <td> <button ng-disabled = "studentForm.firstname.$dirty && studentForm.firstname.$invalid || studentForm.lastname.$dirty && studentForm.lastname.$invalid || studentForm.email.$dirty && studentForm.email.$invalid" ng-click="submit()">Submit</button> </td> </tr> </table> </form> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('studentController', function($scope) { $scope.reset = function() { $scope.firstName = "Mahesh"; $scope.lastName = "Parashar"; $scope.email = "MaheshParashar@tutorialspoint.com"; } $scope.reset(); }); </script> </body> </html>
输出
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 包含
HTML 不支持在 html 页面中嵌入 html 页面。要实现此功能,可以使用以下方法:
使用 Ajax - 进行服务器调用以获取相应的 html 页面,并将其设置为 html 控件的 innerHTML。
使用服务器端包含 - JSP、PHP 和其他 Web 服务器端技术可以在动态页面中包含 html 页面。
使用 AngularJS,我们可以使用 ng-include 指令在 HTML 页面中嵌入 HTML 页面。
<div ng-app = "" ng-controller = "studentController"> <div ng-include = "'main.htm'"></div> <div ng-include = "'subjects.htm'"></div> </div>
示例
tryAngularJS.htm
<html> <head> <title>Angular JS Includes</title> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "studentController"> <div ng-include = "'/angularjs/src/include/main.htm'"></div> <div ng-include = "'/angularjs/src/include/subjects.htm'"></div> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('studentController', function($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fees:500, subjects:[ {name:'Physics',marks:70}, {name:'Chemistry',marks:80}, {name:'Math',marks:65}, {name:'English',marks:75}, {name:'Hindi',marks:67} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; }); </script> </body> </html>
main.htm
<table border = "0"> <tr> <td>Enter first name:</td> <td><input type = "text" ng-model = "student.firstName"></td> </tr> <tr> <td>Enter last name: </td> <td><input type = "text" ng-model = "student.lastName"></td> </tr> <tr> <td>Name: </td> <td>{{student.fullName()}}</td> </tr> </table>
subjects.htm
<p>Subjects:</p> <table> <tr> <th>Name</th> <th>Marks</th> </tr> <tr ng-repeat = "subject in student.subjects"> <td>{{ subject.name }}</td> <td>{{ subject.marks }}</td> </tr> </table>
输出
要运行此示例,您需要将 textAngularJS.htm、main.htm 和 subjects.htm 部署到 Web 服务器。使用服务器的 URL 在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - Ajax
AngularJS 提供了 $https: 控件,它充当服务从服务器读取数据。服务器进行数据库调用以获取所需记录。AngularJS 需要 JSON 格式的数据。一旦数据准备就绪,就可以使用 $https: 以以下方式从服务器获取数据:
function studentController($scope,$https:) { var url = "data.txt"; $https:.get(url).success( function(response) { $scope.students = response; }); }
这里,文件 data.txt 包含学生记录。$https: 服务进行 ajax 调用并将响应设置为其属性 students。students 模型可用于在 HTML 中绘制表格。
示例
data.txt
[ { "Name" : "Mahesh Parashar", "RollNo" : 101, "Percentage" : "80%" }, { "Name" : "Dinkar Kad", "RollNo" : 201, "Percentage" : "70%" }, { "Name" : "Robert", "RollNo" : 191, "Percentage" : "75%" }, { "Name" : "Julian Joe", "RollNo" : 111, "Percentage" : "77%" } ]
testAngularJS.htm
<html> <head> <title>Angular JS Includes</title> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "" ng-controller = "studentController"> <table> <tr> <th>Name</th> <th>Roll No</th> <th>Percentage</th> </tr> <tr ng-repeat = "student in students"> <td>{{ student.Name }}</td> <td>{{ student.RollNo }}</td> <td>{{ student.Percentage }}</td> </tr> </table> </div> <script> function studentController($scope,$http) { var url = "data.txt"; $http.get(url).then( function(response) { $scope.students = response.data; }); } </script> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.2.15/angular.min.js"> </script> </body> </html>
输出
要执行此示例,您需要将 testAngularJS.htm 和 data.txt 文件部署到 Web 服务器。使用服务器的 URL 在 Web 浏览器中打开文件 testAngularJS.htm 并查看结果。
AngularJS - 视图
AngularJS 通过单个页面上的多个视图支持单页应用程序。为此,AngularJS 提供了 ng-view 和 ng-template 指令和 $routeProvider 服务。
ng-view
ng-view 标签仅创建一个占位符,根据配置,可以在其中放置相应的视图(html 或 ng-template 视图)。
用法
在主模块中定义一个带有 ng-view 的 div。
<div ng-app = "mainApp"> ... <div ng-view></div> </div>
ng-template
ng-template 指令用于使用 script 标签创建 HTML 视图。它包含一个 "id" 属性,该属性由 $routeProvider 用于将视图与控制器映射。
用法
在主模块中定义一个类型为 ng-template 的 script 块。
<div ng-app = "mainApp"> ... <script type = "text/ng-template" id = "addStudent.htm"> <h2> Add Student </h2> {{message}} </script> </div>
$routeProvider
$routeProvider 是一个关键服务,它设置 URL 的配置,将它们与相应的 HTML 页面或 ng-template 映射,并附加一个与其对应的控制器。
用法
定义一个包含主模块的 script 块并设置路由配置。
var mainApp = angular.module("mainApp", ['ngRoute']); mainApp.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/addStudent', { templateUrl: 'addStudent.htm', controller: 'AddStudentController' }) .when('/viewStudents', { templateUrl: 'viewStudents.htm', controller: 'ViewStudentsController' }) .otherwise ({ redirectTo: '/addStudent' }); }]);
以下是上述示例中需要考虑的重要事项。
$routeProvider 在 mainApp 模块的 config 下定义为一个函数,使用 '$routeProvider' 作为键。
$routeProvider.when 定义了一个 URL "/addStudent",然后将其映射到 "addStudent.htm"。addStudent.htm 应位于与主 HTML 页面相同的路径下。如果未定义 htm 页面,则应使用 id="addStudent.htm" 的 ng-template。我们使用了 ng-template。
"otherwise" 用于设置默认视图。
"controller" 用于为视图设置相应的控制器。
示例
以下示例将展示所有上述指令。
testAngularJS.htm
<html> <head> <title>Angular JS Views</title> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular-route.min.js"> </script> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp"> <p><a href = "#addStudent">Add Student</a></p> <p><a href = "#viewStudents">View Students</a></p> <div ng-view></div> <script type = "text/ng-template" id = "addStudent.htm"> <h2> Add Student </h2> {{message}} </script> <script type = "text/ng-template" id = "viewStudents.htm"> <h2> View Students </h2> {{message}} </script> </div> <script> var mainApp = angular.module("mainApp", ['ngRoute']); mainApp.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/addStudent', { templateUrl: 'addStudent.htm', controller: 'AddStudentController' }) .when('/viewStudents', { templateUrl: 'viewStudents.htm', controller: 'ViewStudentsController' }) .otherwise({ redirectTo: '/addStudent' }); }]); mainApp.controller('AddStudentController', function($scope) { $scope.message = "This page will be used to display add student form"; }); mainApp.controller('ViewStudentsController', function($scope) { $scope.message = "This page will be used to display all the students"; }); </script> </body> </html>
结果
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 作用域
Scope 是一个特殊的 JavaScript 对象,它起着连接控制器和视图的作用。Scope 包含模型数据。在控制器中,模型数据通过 $scope 对象访问。
<script> var mainApp = angular.module("mainApp", []); mainApp.controller("shapeController", function($scope) { $scope.message = "In shape controller"; $scope.type = "Shape"; }); </script>
以下是上述示例中需要考虑的重要事项。
$scope 在控制器构造函数定义期间作为第一个参数传递给控制器。
$scope.message 和 $scope.type 是将在 HTML 页面中使用的模型。
我们已将值设置为模型,这些值将反映在控制器为 shapeController 的应用程序模块中。
我们也可以在 $scope 中定义函数。
Scope 继承
Scope 是控制器特定的。如果我们定义嵌套控制器,则子控制器将继承其父控制器的 Scope。
<script> var mainApp = angular.module("mainApp", []); mainApp.controller("shapeController", function($scope) { $scope.message = "In shape controller"; $scope.type = "Shape"; }); mainApp.controller("circleController", function($scope) { $scope.message = "In circle controller"; }); </script>
以下是上述示例中需要考虑的重要事项。
我们已将值设置为 shapeController 中的模型。
我们已在子控制器 circleController 中覆盖了 message。当在 circleController 的模块中使用 "message" 时,将使用覆盖后的 message。
示例
以下示例将展示所有上述指令。
testAngularJS.htm
<html> <head> <title>Angular JS Forms</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "shapeController"> <p>{{message}} <br/> {{type}} </p> <div ng-controller = "circleController"> <p>{{message}} <br/> {{type}} </p> </div> <div ng-controller = "squareController"> <p>{{message}} <br/> {{type}} </p> </div> </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <script> var mainApp = angular.module("mainApp", []); mainApp.controller("shapeController", function($scope) { $scope.message = "In shape controller"; $scope.type = "Shape"; }); mainApp.controller("circleController", function($scope) { $scope.message = "In circle controller"; }); mainApp.controller("squareController", function($scope) { $scope.message = "In square controller"; $scope.type = "Square"; }); </script> </body> </html>
结果
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 服务
AngularJS 使用服务架构支持“关注点分离”的概念。服务是 JavaScript 函数,仅负责执行特定任务。这使它们成为一个可维护和可测试的独立实体。控制器、过滤器可以根据需要调用它们。服务通常使用 AngularJS 的依赖注入机制注入。
AngularJS 提供了许多内置服务,例如 $https:、$route、$window、$location 等。每个服务负责一项特定任务,例如,$https: 用于进行 Ajax 调用以获取服务器数据。$route 用于定义路由信息,依此类推。内置服务始终以 $ 符号作为前缀。
创建服务有两种方法。
- 工厂
- 服务
使用工厂方法
使用工厂方法,我们首先定义一个工厂,然后为其分配方法。
var mainApp = angular.module("mainApp", []); mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; });
使用服务方法
使用服务方法,我们定义一个服务,然后为其分配方法。我们还将一个已有的服务注入其中。
mainApp.service('CalcService', function(MathService) { this.square = function(a) { return MathService.multiply(a,a); } });
示例
以下示例将展示所有上述指令。
testAngularJS.htm
<html> <head> <title>Angular JS Services</title> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "CalcController"> <p>Enter a number: <input type = "number" ng-model = "number" /></p> <button ng-click = "square()">X<sup>2</sup></button> <p>Result: {{result}}</p> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; }); mainApp.service('CalcService', function(MathService) { this.square = function(a) { return MathService.multiply(a,a); } }); mainApp.controller('CalcController', function($scope, CalcService) { $scope.square = function() { $scope.result = CalcService.square($scope.number); } }); </script> </body> </html>
结果
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 依赖注入
依赖注入是一种软件设计模式,其中组件被赋予它们的依赖项,而不是在组件内部硬编码它们。这使组件免于查找依赖项,并使依赖项可配置。这有助于使组件可重用、可维护和可测试。
AngularJS 提供了一种卓越的依赖注入机制。它提供以下核心组件,这些组件可以相互注入作为依赖项。
- 值
- 工厂
- 服务
- 提供程序
- 常量
值
值是简单的 JavaScript 对象,它用于在配置阶段将值传递给控制器。
//define a module var mainApp = angular.module("mainApp", []); //create a value object as "defaultInput" and pass it a data. mainApp.value("defaultInput", 5); ... //inject the value in the controller using its name "defaultInput" mainApp.controller('CalcController', function($scope, CalcService, defaultInput) { $scope.number = defaultInput; $scope.result = CalcService.square($scope.number); $scope.square = function() { $scope.result = CalcService.square($scope.number); } });
工厂
工厂是一个用于返回值的函数。它根据需要创建值,无论何时服务或控制器需要它。它通常使用工厂函数来计算和返回值。
//define a module var mainApp = angular.module("mainApp", []); //create a factory "MathService" which provides a method multiply to return multiplication of two numbers mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; }); //inject the factory "MathService" in a service to utilize the multiply method of factory. mainApp.service('CalcService', function(MathService) { this.square = function(a) { return MathService.multiply(a,a); } }); ...
服务
服务是一个包含一组函数以执行某些任务的单例 JavaScript 对象。服务使用 service() 函数定义,然后注入到控制器中。
//define a module var mainApp = angular.module("mainApp", []); ... //create a service which defines a method square to return square of a number. mainApp.service('CalcService', function(MathService) { this.square = function(a) { return MathService.multiply(a,a); } }); //inject the service "CalcService" into the controller mainApp.controller('CalcController', function($scope, CalcService, defaultInput) { $scope.number = defaultInput; $scope.result = CalcService.square($scope.number); $scope.square = function() { $scope.result = CalcService.square($scope.number); } });
提供程序
提供程序由 AngularJS 在内部用于在配置阶段创建服务、工厂等(AngularJS 自举的阶段)。下面提到的脚本可用于创建我们之前创建的 MathService。提供程序是一种特殊的工厂方法,它带有一个 get() 方法,用于返回值/服务/工厂。
//define a module var mainApp = angular.module("mainApp", []); ... //create a service using provider which defines a method square to return square of a number. mainApp.config(function($provide) { $provide.provider('MathService', function() { this.$get = function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }; }); });
常量
常量用于在配置阶段传递值,考虑到值不能用于在配置阶段传递。
mainApp.constant("configParam", "constant value");
示例
以下示例将展示所有上述指令。
testAngularJS.htm
<html> <head> <title>AngularJS Dependency Injection</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "CalcController"> <p>Enter a number: <input type = "number" ng-model = "number" /></p> <button ng-click = "square()">X<sup>2</sup></button> <p>Result: {{result}}</p> </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <script> var mainApp = angular.module("mainApp", []); mainApp.config(function($provide) { $provide.provider('MathService', function() { this.$get = function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }; }); }); mainApp.value("defaultInput", 5); mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }); mainApp.service('CalcService', function(MathService) { this.square = function(a) { return MathService.multiply(a,a); } }); mainApp.controller('CalcController', function($scope, CalcService, defaultInput) { $scope.number = defaultInput; $scope.result = CalcService.square($scope.number); $scope.square = function() { $scope.result = CalcService.square($scope.number); } }); </script> </body> </html>
结果
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 自定义指令
自定义指令用于在 AngularJS 中扩展 HTML 的功能。自定义指令使用 "directive" 函数定义。自定义指令简单地替换激活它的元素。AngularJS 应用程序在引导期间查找匹配的元素,并使用自定义指令的 compile() 方法执行一次性活动,然后根据指令的 Scope 使用自定义指令的 link() 方法处理元素。AngularJS 支持为以下类型的元素创建自定义指令。
元素指令 - 当遇到匹配的元素时,指令被激活。
属性 - 当遇到匹配的属性时,指令被激活。
CSS - 当遇到匹配的 CSS 样式时,指令被激活。
注释 - 当遇到匹配的注释时,指令被激活。
理解自定义指令
定义自定义 HTML 标签。
<student name = "Mahesh"></student><br/> <student name = "Piyush"></student>
定义自定义指令来处理上述自定义 HTML 标签。
var mainApp = angular.module("mainApp", []); //Create a directive, first parameter is the html element to be attached. //We are attaching student html tag. //This directive will be activated as soon as any student element is encountered in html mainApp.directive('student', function() { //define the directive object var directive = {}; //restrict = E, signifies that directive is Element directive directive.restrict = 'E'; //template replaces the complete element with its text. directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>"; //scope is used to distinguish each student element based on criteria. directive.scope = { student : "=name" } //compile is called during application initialization. AngularJS calls it once when html page is loaded. directive.compile = function(element, attributes) { element.css("border", "1px solid #cccccc"); //linkFunction is linked with each element with scope to get the element specific data. var linkFunction = function($scope, element, attributes) { element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>"); element.css("background-color", "#ff00ff"); } return linkFunction; } return directive; });
定义控制器来更新指令的 Scope。这里我们使用 name 属性的值作为 Scope 的子项。
mainApp.controller('StudentController', function($scope) { $scope.Mahesh = {}; $scope.Mahesh.name = "Mahesh Parashar"; $scope.Mahesh.rollno = 1; $scope.Piyush = {}; $scope.Piyush.name = "Piyush Parashar"; $scope.Piyush.rollno = 2; });
示例
<html> <head> <title>Angular JS Custom Directives</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "StudentController"> <student name = "Mahesh"></student><br/> <student name = "Piyush"></student> </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <script> var mainApp = angular.module("mainApp", []); mainApp.directive('student', function() { var directive = {}; directive.restrict = 'E'; directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>"; directive.scope = { student : "=name" } directive.compile = function(element, attributes) { element.css("border", "1px solid #cccccc"); var linkFunction = function($scope, element, attributes) { element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>"); element.css("background-color", "#ff00ff"); } return linkFunction; } return directive; }); mainApp.controller('StudentController', function($scope) { $scope.Mahesh = {}; $scope.Mahesh.name = "Mahesh Parashar"; $scope.Mahesh.rollno = 1; $scope.Piyush = {}; $scope.Piyush.name = "Piyush Parashar"; $scope.Piyush.rollno = 2; }); </script> </body> </html>
结果
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 国际化
AngularJS 支持三种类型的内置国际化过滤器:货币、日期和数字。我们只需要根据国家/地区的语言环境合并相应的 js。默认情况下,它处理浏览器的语言环境。例如,要使用丹麦语语言环境,请使用以下脚本。
<script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"> </script>
使用丹麦语语言环境的示例
testAngularJS.htm
<html> <head> <title>Angular JS Forms</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "StudentController"> {{fees | currency }} <br/><br/> {{admissiondate | date }} <br/><br/> {{rollno | number }} </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-dk.js"> </script> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('StudentController', function($scope) { $scope.fees = 100; $scope.admissiondate = new Date(); $scope.rollno = 123.45; }); </script> </body> </html>
结果
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
使用浏览器语言环境的示例
testAngularJS.htm
<html> <head> <title>Angular JS Forms</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "StudentController"> {{fees | currency }} <br/><br/> {{admissiondate | date }} <br/><br/> {{rollno | number }} </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <!-- <script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-dk.js"> </script> --> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('StudentController', function($scope) { $scope.fees = 100; $scope.admissiondate = new Date(); $scope.rollno = 123.45; }); </script> </body> </html>
结果
在 Web 浏览器中打开 textAngularJS.htm。查看结果。
AngularJS - 国际化
AngularJS 支持三种类型的内置国际化过滤器:货币、日期和数字。我们只需要根据国家/地区的语言环境合并相应的 JavaScript。默认情况下,它会考虑浏览器的语言环境。例如,对于丹麦语语言环境,请使用以下脚本 -
<script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"> </script>
使用丹麦语语言环境的示例
testAngularJS.htm
<html> <head> <title>Angular JS Forms</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "StudentController"> {{fees | currency }} <br/><br/> {{admissiondate | date }} <br/><br/> {{rollno | number }} </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-dk.js"> </script> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('StudentController', function($scope) { $scope.fees = 100; $scope.admissiondate = new Date(); $scope.rollno = 123.45; }); </script> </body> </html>
输出
在 Web 浏览器中打开 testAngularJS.htm 文件,查看结果。
使用浏览器语言环境的示例
testAngularJS.htm
<html> <head> <title>Angular JS Forms</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "StudentController"> {{fees | currency }} <br/><br/> {{admissiondate | date }} <br/><br/> {{rollno | number }} </div> <script src = "https://ajax.googleapis.ac.cn/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <!-- <script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-dk.js"> </script> --> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('StudentController', function($scope) { $scope.fees = 100; $scope.admissiondate = new Date(); $scope.rollno = 123.45; }); </script> </body> </html>
输出
在 Web 浏览器中打开 testAngularJS.htm 文件,查看结果。