1.环境设置
在本章中,我们将讨论如何设置AngularJS库在Web应用程序开发中使用。我们还将简要地研究了目录结构和它的内容。
当打开链接https://angularjs.org/,会看到有两个选项下载AngularJS库:
-
GitHub下载 - 单击此按钮去到GitHub,并获得所有最新的脚本。
-
下载 - 或点击此按钮,屏幕下方会看到:
此屏幕给出了使用角JS如下的各种选项:
-
下载和本地主机文件
-
有两种不同的选择:旧版和最新。名字本身是自我说明。旧版版本已经低于1.2.x版本和最新为1.3.x版。
-
我们也可以使用缩小,无压缩或压缩版本。
-
-
CDN访问:也可以使用CDN。在CDN会给世界各地的访问,在这种情况下,谷歌的主机区域性数据中心。这意味着使用CDN的移动主机的文件从自己的服务器到一系列外部因素的责任。这也提供了一个优点,即如果访问者你的网页已经下载来自相同的CDN AngularJS副本,它不必被重新下载。
-
在本教程中使用CDN版本库。
例子
现在让我们使用AngularJS库编写一个简单的例子。创建一个HTML文件 myfirstexample.html 如下:
<!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script> </head> <body ng-app="myapp"> <div ng-controller="HelloController" > <h2>Welcome {{helloTo.title}} to the world of Yiibai!</h2> </div> <script> angular.module("myapp", []) .controller("HelloController", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "AngularJS"; }); </script> </body> </html>
下面的章节详细描述了上面的代码:
包括AngularJS
我们已经包含了AngularJS的JavaScript文件中的HTML页面,所以我们可以使用AngularJS:
<head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </head>
检查AngularJS的最新版本在其官方网站。
指向AngularJS应用
接下来,我们告诉一下HTML的一部分包含AngularJS应用。这可以通过将ng-app属性到AngularJS应用程序的根目录下的HTML元素。可以将它添加到HTML元素或body元素,如下所示:
<body ng-app="myapp"> </body>
视图
这部分的视图:
<div ng-controller="HelloController" > <h2>Welcome {{helloTo.title}} to the world of Yiibai!</h2> </div>
ng-controller 告诉AngularJS什么是控制器和视图。 helloTo.title告诉AngularJS编写名为helloTo.title的HTML在这个位置的“model”的值。
控制器
控制器的部分是:
<script> angular.module("myapp", []) .controller("HelloController", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "AngularJS"; }); </script>
此代码先注册名为HelloController中的名为MyApp角模块控制器的功能。我们将学习更多有关在各自的章节模块和控制器。控制器功能被登记在经由angular.module(...)的角。controller(...)函数调用。
传递给控制器函数的$scope参数模型。控制器功能增加了helloTo的JavaScript对象,该对象中加上一个标题字段。
执行
将以上代码保存为myfirstexample.htmll在任何浏览器中打开它。会看到如下的输出:
当页面在浏览器中加载时,下面的事件发生:
-
HTML文档被加载到浏览器中,并且由浏览器进行计算。 AngularJS JavaScript文件被加载,角全局对象被创建。接下来,JavaScript的一个注册控制器功能被执行。
-
AngularJS通过HTML扫描,以寻找AngularJS应用程序和视图。一旦视图的找到,它连接了视图到对应的控制器函数。
-
接下来AngularJS执行控制函数。然后,它呈现与填充控制器模型数据视图。页面现在已准备就绪。
2.MVC体系结构
模型 - 视图 - 控制器或MVC,MVC是普遍的叫法,是一种软件设计模式,用于开发Web应用程序。模型- 视图 - 控制器模式是由以下三部分组成:
-
模型/Model - 一个负责维护数据模式的最低水平。
-
视图/View - 负责显示所有或数据到用户的部分。
-
控制器/Controller - 软件代码控制Model和View之间的相互作用。
MVC是受欢迎的,因为它隔离了应用逻辑从用户界面层和支持的关注点分离。这里的控制器接收用于该应用程序的所有请求,制备视图所需要的任何数据。视图,使用制备的控制器,产生一个最终像样的响应的数据。 MVC抽象可以用图形表示如下。
模型 - model
模型是负责管理应用程序的数据。它响应来自视图的请求,同时也响应指令从控制器进行自我更新。
视图 - view
在一个特定的格式的演示数据,由控制器决定触发显示数据。它们是基于脚本的模板系统,如JSP,ASP,PHP,非常容易使用AJAX技术的集成。
控制器 - controller
控制器负责响应于用户输入并执行交互数据模型对象。控制器接收到输入,它验证输入,然后执行修改数据模型的状态的业务操作。
AngularJS是一个MVC框架。在接下来的章节中,让我们看到了AngularJS如何使用MVC方法。
3.第一个应用程序
按以下步骤来创建AngularJS应用
第1步:加载框架
作为一个纯粹的JavaScript框架,它可以使用<script>标签来添加。
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/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.html<html> <title>AngularJS First Application</title> <body> <h1>Sample Application</h1> <div ng-app=""> <p>我的名字: <input type="text" ng-model="name"></p> <p>Hello, <span ng-bind="name"></span>!</p> </div> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
输出
在Web浏览器打开textAngularJS.html。请输入姓名并看到的结果。
如何让AngularJS与HTML集成
-
ng-app指令指示AngularJS应用的开始。
-
ng-model指令创建一个名为“name”的模型变量在HTML页面中,并有ng-app指令在div内使用。
-
ng-bind使用模型名称只要在文本框中用户输入的东西显示在HTML span标签。
-
结束</ div>标记表示AngularJS应用程序的结束。
4.指令
AngularJS指令用于扩展HTML。这些都是先从ng- 前缀的特殊属性。我们将讨论以下指令:
-
ng-app - 该指令启动一个AngularJS应用。
-
ng-init - 该指令初始化应用程序数据。
-
ng-model - 此指令定义的模型,该模型是变量在AngularJS使用。
-
ng-repeat - 该指令将重复集合中的每个项目的HTML元素。
ng-app指令
ng-app 指令启动一个AngularJS应用。它定义根元素。它会自动初始化或启动加载包含AngularJS应用程序的Web页面的应用程序。它也被用来加载各种AngularJS模块AngularJS应用。在下面的例子中,我们定义默认AngularJS应用使用div元素的ng-app 属性。
<div ng-app=""> ... </div>
ng-init 指令
ng-init 指令初始化一个AngularJS应用程序的数据。它被用来把值在应用程序中使用的变量。在下面的例子中,我们将初始化countries数组。使用JSON语法来定义countries数组。
<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指令
ng-model指令定义在AngularJS应用中使用的模型/变量。在下面的例子中,我们定义了一个名为“name”的模型。
<div ng-app=""> ... <p>Enter your Name: <input type="text" ng-model="name"></p> </div>
ng-repeat 指令
ng-repeat 指令重复html元素集合中的每个项目。在下面的例子中,我们已经迭代了数组countries。
<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.html<html> <title>AngularJS Directives</title> <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="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
输出
在Web浏览器打开textAngularJS.html。输入姓名并看到以下结果。
5.表达式
表达式用于应用程序数据绑定到HTML。表达式都写在双括号就像{{表达式}}。表达式中的行为跟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.html 文件代码如下:<html> <title>AngularJS Expressions</title> <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="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
输出
在Web浏览器打开textAngularJS.html。看到结果如下:
6.控制器
AngularJS应用主要依赖于控制器来控制数据在应用程序中的流动。控制器采用ng-controller指令定义。控制器是一个包含属性/属性和JavaScript对象的功能。每个控制器接受$scope参数指定应用程序/模块,由控制器控制。
<div ng-app="" ng-controller="studentController"> ... </div>
在这里,我们已经声明采用ng-controller指令的控制器studentController。作为下一步,我们将定义studentController如下
<script> function studentController($scope) { $scope.student = { firstName: "yiibai", lastName: "com", 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函数中,我们现在要学生对象返回组合的名字。
-
作为一个说明,还可以定义控制器对象在单独的JS文件,并把有关文件中的HTML页面。
现在可以使用ng-model或使用表达式如下使用studentController学生的属性。
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。
-
现在,只要输入first name和lastname输入框中输入什么,可以看到两个名称自动更新。
例子
下面的例子将展示使用控制器。
testAngularJS.html 文件内容如下:<html> <head> <title>Angular JS Controller</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="" 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> function studentController($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; } </script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
输出
在Web浏览器打开textAngularJS.html,看到以下结果:
7.过滤器
过滤器是用来更改修改数据,并且可以在表达式或使用管道符指令将其归入。以下是常用的过滤器的列表。
S.No. | 名称 | 描述 |
---|---|---|
1 | 大写 | 转换文本为大写文本。 |
2 | 小写 | 转换文本为小写文本。 |
3 | 货币 | 货币格式格式文本。 |
4 | 过滤器 | 过滤数组中它根据所提供的标准的一个子集。 |
5 | 排序 | 排序提供标准的基础数组。 |
大写过滤器
添加大写的过滤器使用管道符的表达式。在这里,添加了大写过滤器,全部用大写字母打印学生姓名。
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}}
小写过滤器
添加小写的过滤器,使用管道符的表达式。在这里添加小写过滤器,以小写字母打印学生姓名。
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() | lowercase}}
货币滤波器
加币过滤器使用管道符返回数的表达式。在这里,我们添加了过滤器,货币使用货币格式的打印费用。
Enter fees: <input type="text" ng-model="student.fees"> fees: {{student.fees | currency}}
过滤器的过滤器
要仅显示所需的主题,我们使用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标记。
Subject: <ul> <li ng-repeat="subject in student.subjects | orderBy:'marks'"> {{ subject.name + ', marks:' + subject.marks }} </li> </ul>
例子
下面的例子将展示上述所有的过滤器。
testAngularJS.html<html> <head> <title>Angular JS Filters</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="" 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> function studentController($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> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
输出
在Web浏览器打开textAngularJS.html,看到以下结果:
8.表格
表格数据本质上通常是重复的。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.html<html> <head> <title>Angular JS Table</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 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> function studentController($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> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
输出
在Web浏览器打开textAngularJS.html,看到以下结果:
9.HTML DOM
以下指令可用于应用程序数据绑定到HTML DOM元素的属性。
S.No. | 名称 | 描述 |
---|---|---|
1 | ng-disabled | 禁用一个给定的控制 |
2 | ng-show | 显示一个给定的控制 |
3 | ng-hide | 隐藏在给定的控制 |
4 | ng-click | 表示AngularJS click事件 |
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></td> <button ng-click="clickCounter = clickCounter + 1">Click Me!</button>
例子
下面的例子将展示上述所有指令。
testAngularJS.html<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="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
输出
在Web浏览器打开textAngularJS.html,看到以下结果:
10.模块
AngularJS支持模块化的方法。模块用于单独的逻辑表示服务,控制器,应用程序等,并保持代码的整洁。我们在单独的js文件中定义的模块,并将其命名为按照module.js文件形式。在这个例子中,我们要创建两个模块。
-
Application Module - 用于初始化控制器应用程序
-
Controller Module - 用于定义控制器
应用模块
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; } }; });
在这里,我们已经声明采用studentController模块的mainApp.controller功能的控制器。
使用模块
<div ng-app="mainApp" ng-controller="studentController"> .. <script src="mainApp.js"></script> <script src="studentController.js"></script>
在这里,我们使用 ng-app 指令和控制器采用ng-controller指令应用模块。我们已经在主要的HTML页面导入mainApp.js和studentController.js。
示例
下面的例子将展示上述所有模块。
testAngularJS.htm
<html> <head> <title>Angular JS Modules</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="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 src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> <script src="mainApp.js"></script> <script src="studentController.js"></script> </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。看到结果如下。
11.表单
AngularJS提供丰富填写表单和验证。我们可以用ng-click来处理AngularJS点击按钮事件,然后使用 $dirty 和 $invalid标志做验证的方式。使用novalidate表单声明禁止任何浏览器特定的验证。表单控件使用了大量的角活动。让我们快速浏览一下有关事件先。
事件
AngularJS提供可与HTML控件相关联的多个事件。例如ng-click通常与按钮相关联。以下是AngularJS支持的事件。
-
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
使用点击一个按钮的指令,表单重置数据。
<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@yiibai.com"; } $scope.reset(); } </script>
验证数据
可使用下面跟踪误差。
-
$dirty - 规定值已被改变。
-
$invalid- 该值的状态是无效的。
-
$error- 指出确切的错误。
例子
下面的例子将展示上述所有指令。
testAngularJS.html<html> <head> <title>Angular JS Forms</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"> <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> function studentController($scope) { $scope.reset = function(){ $scope.firstName = "Mahesh"; $scope.lastName = "Parashar"; $scope.email = "MaheshParashar@yiibai.com"; } $scope.reset(); } </script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
输出
在Web浏览器打开textAngularJS.html。看到结果如下。
12.包括
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.html'"></div> <div ng-include="'subjects.html'"></div> </div>
例子
tryAngularJS.html
<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">
<div ng-include="'main.html'"></div>
<div ng-include="'subjects.html'"></div>
</div>
<script>
function studentController($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>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>
main.html
<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.html
<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.html,main.html和subjects.html 到一个网络服务器。使用服务器URL在Web浏览器中打开textAngularJS.html。看到结果。
13.Ajax
AngularJS提供$http控制,可以作为一项服务从服务器读取数据。服务器可以使一个数据库调用来获取记录。 AngularJS需要JSON格式的数据。一旦数据准备好,$http可以用以下面的方式从服务器得到数据。
function studentController($scope,$http) { var url="data.txt"; $http.get(url).success( function(response) { $scope.students = response; }); }
在这里,data.txt中包含的学生记录。 $http服务使Ajax调用和设置针对其学生的属性。 “学生”模型可以用来用来绘制 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.html
<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).success( function(response) { $scope.students = response; }); } </script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
输出
要运行这个例子,需要部署textAngularJS.html,data.txt到一个网络服务器。使用URL在Web浏览器中打开textAngularJS.html请求服务器。看到结果如下:
14.视图
AngularJS支持通过在单个页面上的多个视图的单页应用。要做到这一点AngularJS提供ng-view 和 ng-template指令,以及 $routeProvider 服务。
ng-view
ng-view 标记只是简单地创建一个占位符,是一个相应的视图(HTML或ng-template视图),可以根据配置来放置。
使用
定义一个div与ng-view在主模块中。
<div ng-app="mainApp"> ... <div ng-view></div> </div>
ng-template
ng-template 指令是用来创建使用script标签的HTML视图。它包含一个用于由$routeProvider映射控制器视图“id”属性。
使用
定义类型作为主模块中 ng-template 的脚本块。
<div ng-app="mainApp"> ... <script type="text/ng-template" id="addStudent.html"> <h2> Add Student </h2> {{message}} </script> </div>
$routeProvider
$routeProvider是组网址的配置,将它们映射相应的HTML页面或 ng-template,并附加一个控制器使用相同键的服务。
使用
定义类型作为主模块中 ng-template 的脚本块。
<div ng-app="mainApp"> ... <script type="text/ng-template" id="addStudent.html"> <h2> Add Student </h2> {{message}} </script> </div>
使用
定义主模块的脚本块,并设置路由配置。
var mainApp = angular.module("mainApp", ['ngRoute']); mainApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/addStudent', { templateUrl: 'addStudent.html', controller: 'AddStudentController' }). when('/viewStudents', { templateUrl: 'viewStudents.html', controller: 'ViewStudentsController' }). otherwise({ redirectTo: '/addStudent' }); }]);
以下是在上面的例子中需要考虑的重要问题
-
$routeProvider被定义为使用关键字作为'$routeProvider“下mainApp模块的配置功能;
-
$routeProvider当定义了URL“/addStudent”映射到“addStudent.html”。 addStudent.html应存在于相同的路径主要的html 页面。如果htm页面没有定义,那么ng-template被id=“addStudent.html”使用。我们已经使用了ng-template;
-
“otherwise”是用来设置的默认视图;
-
“conlloer”是用来设置该视图对应的控制器;
例子
下面的例子将展示上述所有指令。
testAngularJS.html<html> <head> <title>Angular JS Views</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/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.html"> <h2> Add Student </h2> {{message}} </script> <script type="text/ng-template" id="viewStudents.html"> <h2> View Students </h2> {{message}} </script> </div> <script> var mainApp = angular.module("mainApp", ['ngRoute']); mainApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/addStudent', { templateUrl: 'addStudent.html', controller: 'AddStudentController' }). when('/viewStudents', { templateUrl: 'viewStudents.html', 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.html。看到结果如下:
15.作用域
范围扮演其视图连接控制器的角色一个特殊的JavaScript对象。范围包含了模型数据。在控制器,模型数据通过$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定义函数功能。
继承范围
范围是特定的控制器。如果我们定义嵌套的控制器,然后控制器子将继承其父控制的范围。
<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消息。当“消息”内的控制器circleController的模块使用时,将用于重写的消息。
例子
下面的例子将展示上述所有指令。
testAngularJS.html<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="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/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.html。看到结果如下。
16.服务
AngularJS支持使用服务的体系结构“关注点分离”的概念。服务是JavaScript函数,并负责只做一个特定的任务。这也使得他们即维护和测试的单独实体。控制器,过滤器可以调用它们作为需求的基础。服务使用AngularJS的依赖注入机制注入正常。
AngularJS提供例如许多内在的服务,如:$http, $route, $window, $location等。每个服务负责例如一个特定的任务,$http是用来创建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.html<html> <head> <title>Angular JS Forms</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" /> <button ng-click="square()">X<sup>2</sup></button> <p>Result: {{result}}</p> </div> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> <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.html。看到结果如下。
17.依赖注入
依赖注入是一个在组件中给出的替代了硬的组件内的编码它们的依赖关系的软件设计模式。这减轻一个组成部分,从定位的依赖,依赖配置。这有助于使组件可重用,维护和测试。
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.html<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" /> <button ng-click="square()">X<sup>2</sup></button> <p>Result: {{result}}</p> </div> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/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.html。看到结果如下。
18.自定义指令
自定义指令中使用AngularJS扩展HTML的功能。自定义指令使用的“指令”的功能定义。自定义指令只是替换了它被激活的元素。引导过程中AngularJS应用程序找到了匹配的元素,并做好使用自定义指令compile()方法一次活动再处理使用基于指令的范围自定义指令link()方法的元素。 AngularJS提供支持,以下列元素的类型来创建自定义指令。
-
Element directives - 指令遇到时激活一个匹配的元素。
-
Attribute - - 指令遇到时激活一个匹配的属性。
-
CSS - - 指令遇到时激活匹配CSS样式。
-
Comment - - 指令遇到时激活匹配的注释。
了解自定义指令
定义自定义的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; });
定义控制器以更新范围为指令。在这里,我们使用name属性值作为子的作用域。
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="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/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.html。看到结果如下:
19.国际化
AngularJS支持内置的国际化三种类型的过滤器货币,日期和数字。只需要根据国家的区域纳入相应的JS。默认情况下它处理浏览器的语言环境。例如,要使用丹麦语的语言环境,使用下面的脚本
<script src="https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script>
使用丹麦语的语言环境实例
<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="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> <script src="https://code.angularjs.org/1.2.5/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.html。看到结果如下。
使用浏览器的语言环境示例
<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="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> <!-- <script src="https://code.angularjs.org/1.2.5/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.html。看到结果如下。