AngularJS是一個開源Web應(yīng)用程序框架。它最初是由Misko Hevery和Adam Abrons開發(fā)于2009年。現(xiàn)在是由谷歌維護(hù)。
AngularJS的定義,它的官方文檔介紹如下:
AngularJS是動態(tài)的Web應(yīng)用程序結(jié)構(gòu)框架。它可以讓你使用HTML作為模板語言,擴(kuò)展HTML的語法清晰,簡潔地表達(dá)應(yīng)用程序的組件。Angular分明的數(shù)據(jù)綁定和依賴注入必須編寫代碼。而這一切都在瀏覽器內(nèi)發(fā)生,這使得它與任何服務(wù)器技術(shù)的理想合作伙伴。特點(diǎn)
AngularJS是一個功能強(qiáng)大的基于Javascript開發(fā)框架來創(chuàng)建富互聯(lián)網(wǎng)應(yīng)用(RIA)。
AngulajJS為開發(fā)者提供選項來編寫客戶端應(yīng)用程序(使用JavaScript)在一個干凈的MVC(模型 - 視圖 - 控制器)的方式。
AngularJS應(yīng)用是跨瀏覽器兼容的。自動AngularJS處理適用于每個瀏覽器的javascript代碼。
AngularJS是開源的,完全免費(fèi)的,并且由數(shù)千名世界各地的開發(fā)。它是根據(jù)Apache許可證2.0版許可。
總體而言,AngularJS是一個框架可以用來構(gòu)建大規(guī)模,高性能的網(wǎng)絡(luò)應(yīng)用,同時也易于維護(hù)。
核心功能
以下是AngularJS的最重要的核心的功能:
數(shù)據(jù)綁定:它是模型和視圖組件之間的數(shù)據(jù)的自動同步。
適用范圍:這些是指模型對象。充當(dāng)控制器和視圖之間的膠水。
控制器:這些是綁定到特定范圍的Javascript函數(shù)。
服務(wù):AngularJS配有多個內(nèi)置的服務(wù),例如$http提供xmlHttPRequest。這些是在應(yīng)用程序?qū)嵗淮蔚膯我粚ο蟆?/p>
過濾器:這些從數(shù)組項目中選擇一個子集,并返回一個新的數(shù)組。
指令:指令是關(guān)于DOM元素標(biāo)記(如元素,屬性,CSS等等)。這些可以被用來創(chuàng)建作為新的自定義窗口小部件自定義的HTML標(biāo)簽。 AngularJS有內(nèi)置的指令(ngBind,ngModel...)
模板:這些都與控制器和模型信息呈現(xiàn)的視圖。這些可以使用“諧音”的單個文件(如index.html),或在一個頁面上的多個視圖。
路由:它是切換視圖的概念。
模型 - 視圖 :MVC是一個設(shè)計模式將應(yīng)用劃分為不同的部分(稱為模型,視圖和控制器),每一個具有不同的責(zé)任。 AngularJS沒有傳統(tǒng)意義上的MVC實(shí)現(xiàn),而是更接近于MVVM(模型 - 視圖 - 視圖模型)。AngularJS團(tuán)隊讓它作為模型視圖而不管。
深層鏈接:深層鏈接能夠使其可書簽應(yīng)用程序的狀態(tài)進(jìn)行編碼的URL。應(yīng)用程序可以從該URL為相同的狀態(tài)恢復(fù)。
依賴注入: AngularJS有一個內(nèi)置的依賴注入子系統(tǒng),通過使應(yīng)用程序幫助開發(fā)人員更易于開發(fā),理解和測試。
概念
下圖描繪了AngularJS,我們將詳細(xì)在隨后的章節(jié)討論的一些重要部分。
AngularJS的優(yōu)點(diǎn)
AngularJS提供在一個非常干凈和維護(hù)方式來創(chuàng)建單頁的應(yīng)用。
AngularJS提供了數(shù)據(jù)綁定功能為HTML從而給用戶提供豐富而敏感的體驗
AngularJS代碼可單元測試。
AngularJS使用依賴注入和運(yùn)用關(guān)注點(diǎn)分離。
AngularJS提供了可重用的組件。
AngularJS能為開發(fā)人員編寫更少的代碼,并獲得更多的功能。
在AngularJS,視圖都是純HTML頁面,并用JavaScript編寫控制器完成業(yè)務(wù)處理。
AngularJS應(yīng)用程序可以在所有主要瀏覽器和智能手機(jī),包括Android和iOS系統(tǒng)的手機(jī)/平板電腦上運(yùn)行。
AngulaJS的缺點(diǎn)
雖然AngularJS帶有許多加分,但是我們應(yīng)該考慮以下幾點(diǎn):
不安全:JavaScript只有框架編寫的應(yīng)用程序在AngularJS是不安全的。服務(wù)器端的認(rèn)證和授權(quán)是必須的,以保持應(yīng)用程序的安全。
不可降解:如果應(yīng)用程序的用戶禁用JavaScript的話用戶將只能看到基本的頁面,僅此而已。
AngularJS組件
AngularJS框架可分為以下三個主要部分組成:
ng-app : 該指令規(guī)定,并鏈接一個AngularJS應(yīng)用程序的HTML。
ng-model : 該指令結(jié)合AngularJS應(yīng)用數(shù)據(jù)的值到HTML的輸入控件。
ng-bind : 該指令子帶AngularJS應(yīng)用數(shù)據(jù)的HTML標(biāo)簽。
AngularJS環(huán)境設(shè)置
在本章中,我們將討論如何建立AngularJS庫在Web應(yīng)用程序開發(fā)中使用。我們還將簡要地學(xué)習(xí)目錄結(jié)構(gòu)和它的內(nèi)容。
打開鏈接https://angularjs.org/(打不開可能需要翻墻),會看到有兩個下載AngularJS庫的選項:
![]()
View on GitHub- 單擊此按鈕跳到GitHub,并獲得所有最新的腳本。
Download- 或者點(diǎn)擊此按鈕,會看到屏幕如下:
此屏幕給出了使用AngularJS如下多種選擇:
Downloading and hosting files locally
有兩種不同的選擇:舊版和最新版。舊版是版本低于1.2.x版本,最新是1.3.x版本。
我們也可以使用縮小,非壓縮或壓縮版本。
CDN access: 也可以使用一個CDN。CDN全世界可訪問,它放在谷歌主機(jī)區(qū)域性數(shù)據(jù)中心。 這也提供了一個優(yōu)點(diǎn),即如果訪問者的網(wǎng)頁已經(jīng)從相同的CDN 下載了AngularJS的副本,它不必再重新下載。
在本教程中我們使用的是CDN版本庫示例
現(xiàn)在讓我們使用AngularJS庫編寫一個簡單的例子。讓我們創(chuàng)建一個HTML文件 first-angular.html 如下:
<!doctype html><html> <head> <script src="https://Ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script> <title>第一個AngularJS程序</title> </head> <body ng-app="myapp"> <div ng-controller="HelloController" > <h2>你好 !第一個{{helloTo.title}}程序示例</h2> </div> <script> angular.module("myapp", []) .controller("HelloController", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "AngularJS"; }); </script> </body></html>下面的章節(jié)詳細(xì)描述上面的代碼:
包括AngularJS
我們已經(jīng)包括了AngularJS的JavaScript文件到HTML頁面中,所以我們可以用AngularJS:
<head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script></head>在其官方網(wǎng)站檢查AngularJS的最新版本。
指向AngularJS應(yīng)用程序
接下來我們指示HTML的哪一部分包含了AngularJS應(yīng)用程序。這可以通過ng-app屬性到AngularJS應(yīng)用程序的根HTML元素。可以把它添加到HTML元素或body元素,如下所示:
<body ng-app="myapp"></body>視圖
這是視圖的一部分:
<div ng-controller="HelloController" > <h2>Welcome {{helloTo.title}} to the world of Yiibai tutorials!</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模塊。 我們將學(xué)習(xí)更多關(guān)于它們在各自的模塊和控制器章節(jié)。控制器函數(shù)注冊在Angular中,通過angular.module(...).controller(...) 的函數(shù)來調(diào)用。
傳遞給控制器函數(shù)的$scope參數(shù)是模型。控制器函數(shù)增加了helloTo的 JavaScript對象,并在該對象它增加了一個標(biāo)題字段。
執(zhí)行
將以上代碼保存為 first-angular.html ,并在瀏覽器中打開它。會看到如下的輸出:
![]()
當(dāng)頁面在瀏覽器中加載,輸出下面的結(jié)果:
HTML文檔加載到瀏覽器,并且由瀏覽器進(jìn)行評估計算。AngularJS JavaScript文件被加載,Angular 全局對象被創(chuàng)建。接下來,JavaScript一個注冊控制器的函數(shù)被執(zhí)行。
接下來AngularJS通過HTML掃描,以尋找AngularJS應(yīng)用程序和視圖。當(dāng)視圖的定位后,它連接視圖到對應(yīng)的控制器函數(shù)。
接下來,AngularJS執(zhí)行控制器函數(shù)。然后,它呈現(xiàn)通過控制器模型數(shù)據(jù)來自填充的視圖。此時網(wǎng)頁已準(zhǔn)備就緒。
AngularJS MVC 架構(gòu)
模型視圖控制器(Model View Controller)或MVC,因為它是俗稱,是一種Web應(yīng)用程序開發(fā)設(shè)計模式。
模型-視圖-控制器模式由以下三部分組成:
Model - 是一個最低水平負(fù)責(zé)維護(hù)數(shù)據(jù)的模式。
View - 這是負(fù)責(zé)顯示所有或一部分的數(shù)據(jù)到用戶。
Controller - 軟件代碼控制模型和視圖之間的相互作用。
MVC是很流行的,因為它從用戶界面層和支持分離關(guān)注隔離了應(yīng)用邏輯。在這里,控制器接收應(yīng)用程序的所有請求,然后使用Model,以準(zhǔn)備視圖需要的數(shù)據(jù)。然后視圖使用控制器準(zhǔn)備的數(shù)據(jù),以產(chǎn)生一個最終的像樣響應(yīng)的數(shù)據(jù)輸出。 MVC的抽象圖形可以表示如下。
模型
模型負(fù)責(zé)管理應(yīng)用程序的數(shù)據(jù)。它響應(yīng)從視圖請求,同時也從控制器響應(yīng)指令到自我更新。
視圖
在一個特定的格式的呈現(xiàn)數(shù)據(jù),由控制器決定呈現(xiàn)數(shù)據(jù)觸發(fā)。 它們都是基于腳本的模板系統(tǒng),如jsp,asp,php也很容易使用AJAX技術(shù)來集成。
控制器
控制器負(fù)責(zé)響應(yīng)于用戶輸入并執(zhí)行交互數(shù)據(jù)模型對象。控制器接收輸入,并驗證輸入,然后執(zhí)行修改數(shù)據(jù)模型的業(yè)務(wù)操作的狀態(tài)。
AngularJS是一個基于MVC的框架。在接下來的章節(jié)中,讓我們看看AngularJS如何使用MVC方法論。
AngularJS 表達(dá)式
表達(dá)式用于應(yīng)用程序綁定數(shù)據(jù)到HTML。表達(dá)式編寫在雙括號就如:{{ expression}}. 表達(dá)式中的行為方式與 ng-bind 指令相同。AngularJS應(yīng)用表達(dá)式是純JavaScript表達(dá)式和輸出正在使用的數(shù)據(jù)。
使用數(shù)字
<p>Expense on Books : {{cost * quantity}} Rs</p>使用字符串
<p>Hello {{student.firstname + " " + student.lastname}}!</p>使用對象
<p>Roll No: {{student.rollno}}</p>使用數(shù)組
<p>Marks(Math): {{marks[3]}}</p>示例
下面的例子將展示上述所有表達(dá)式。
sampleAngularJS.html<html><title>AngularJS 表達(dá)式</title><body><h1>Sample application</h1><div ng-app="" ng-init="quantity=1;cost=30; student={firstname:'李',lastname:'剛',rollno:101};marks=[82,91,78,77,64]"> <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://www.yiibai.com/js/angular.min.js"></script></body></html>輸出結(jié)果
在瀏覽器中打開:sampleAngularJS.html, 看到結(jié)果如下:
AngularJS 控制器
AngularJS應(yīng)用主要依賴于控制器來控制數(shù)據(jù)流在應(yīng)用程序中.控制器使用 ng-controller 指令定義。控制器是一個包含屬性/屬性和函數(shù)的JavaScript對象。每個控制器接受$scope作為參數(shù)引用到應(yīng)用程序/模塊,由控制器來控制。
<div ng-app="" ng-controller="studentController">...</div>在這里,我們采用 ng-controller 指令聲明控制器studentController。作為下一個步驟,我們將定義 studentController 如下:
<script>function studentController($scope) { $scope.student = { firstName: "李", lastName: "四", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } };}</script>studentController定義一個以 $scope 作為參數(shù)的JavaScript對象。
$scope表示應(yīng)用程序,它使用studentController對象。
$ scope.student是studentController對象的屬性。
firstName 和 lastName 是 $scope.student 對象的兩個屬性。我們已經(jīng)為它們設(shè)置了缺省值。
fullName是 $scope.student 對象的函數(shù),其任務(wù)是返回合并后的名字。
在fullName函數(shù)中我們得到了 student 對象,然后返回合并后的名字。
我們還可以定義控制器對象在單獨(dú)的JS文件,并參考(引入)該文件在HTML頁面。
現(xiàn)在,我們可以在studentController使用ng-model或表達(dá)式來獲取學(xué)生的屬性。
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.fileName()到HTML。
現(xiàn)在,只要輸入名字和姓氏在輸入框中,可以看到全名(fullname)自動更新。
示例
下面的例子將展示控制器的使用。
testAngularJS.html<html><head><title>Angular JS Controller</title><script src="http://www.yiibai.com/js/angular.min.js"></script></head><body><h2>AngularJS應(yīng)用示例</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>您輸入的名字是: {{student.fullName()}}</div><script>var mainApp = angular.module("mainApp", []);mainApp.controller('studentController', function($scope) { $scope.student = { firstName: "李", lastName: "剛", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } };});</script></body></html>輸出
在瀏覽器中打開:textAngularJS.html ,將看以下的結(jié)果:
AngularJS 過濾器
過濾器用來改變修改的數(shù)據(jù),并可以在表達(dá)式或使用管道字符指令來過濾。以下是常用的過濾器的列表。
S.No. 名稱 描述 1 uppercase 轉(zhuǎn)換文本為大寫文字。 2 lowercase 轉(zhuǎn)換文本為小寫文字。 3 currency 以貨幣格式格式化文本。 4 filter 過濾數(shù)組到根據(jù)提供標(biāo)準(zhǔn)的一個子集。 5 orderby 排序基于提供標(biāo)準(zhǔn)的數(shù)組。 大寫過濾器
添加大寫字母過濾器使用管道符表達(dá)式。在這里,我們添加大寫過濾器中的所有字母為大寫,并打印學(xué)生的名字。
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}}小寫過濾器
添加小寫過濾器使用管道符表達(dá)式。在這里,我們添加小寫過濾器全部以小寫字母打印學(xué)生的名字。
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}}貨幣過濾器
添加貨幣過濾器使用管道符返回數(shù)的表達(dá)式。在這里,我們添加貨幣過濾器使用貨幣格式的打印費(fèi)用。
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>排序過濾器
由標(biāo)記來排序科目,我們使用的OrderBy標(biāo)記。
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><script src="http://www.yiibai.com/js/angular.min.js"></script></head><body><h2>AngularJS過濾器應(yīng)用示例</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: "李", lastName: "Gang", fees:500, subjects:[ {name:'物理',marks:70}, {name:'化學(xué)',marks:80}, {name:'數(shù)學(xué)',marks:65}, {name:'外語', marks:87} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } };});</script></body></html>輸出結(jié)果
在瀏覽器中打開:textAngularJS.html,看到結(jié)果如下:
AngularJS 表格
表中的數(shù)據(jù)本質(zhì)上是通常可重復(fù)。 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樣式設(shè)置樣式。
<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 文件內(nèi)容:<html><head><title>AngularJS表格示例</title><script src="http://www.yiibai.com/js/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 表格應(yīng)用示例</h2><div ng-app="mainApp" ng-controller="studentController"><table border="0"><tr><td>姓:</td><td><input type="text" ng-model="student.firstName"></td></tr><tr><td>名: </td><td><input type="text" ng-model="student.lastName"></td></tr><tr><td>名字: </td><td>{{student.fullName()}}</td></tr><tr><td>科目:</td><td><table> <tr> <th>名字</th> <th>標(biāo)記</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: "周", lastName: "杰倫", fees:500, subjects:[ {name:'物理',marks:73}, {name:'化學(xué)',marks:90}, {name:'數(shù)學(xué)',marks:68}, {name:'英文',marks:85}, {name:'生物',marks:77} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } };});</script></body></html>輸出結(jié)果
在瀏覽器中打開:textAngularJS.html ,看到結(jié)果如下:
AngularJS HTML DOM
下面的指令可用于綁定應(yīng)用程序數(shù)據(jù)到HTML DOM元素的屬性。
S.No. 名稱 描述 1 ng-disabled 禁用給定的控制 2 ng-show 顯示了一個給定的控制 3 ng-hide 隱藏一個給定的控制 4 ng-click 表示一個AngularJS click事件 ng-disabled 指令
添加ng-disabled屬性到一個HTML按鈕,并把它傳遞模型。綁定模型到復(fù)選框,來看看變化。
<input type="checkbox" ng-model="enableDisableButton">Disable Button<button ng-disabled="enableDisableButton">Click Me!</button>ng-show 指令
添加 ng-show 屬性到HTML按鈕,并把它傳遞到模型。該模型綁定復(fù)選框。
<input type="checkbox" ng-model="showHide1">Show Button<button ng-show="showHide1">Click Me!</button>ng-hide 指令
添加 ng-hide 屬性到HTML按鈕,并把它傳遞模型。該模型綁定復(fù)選框。
<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 HTML DOM 應(yīng)用示例</h2><div ng-app=""><table border="0"><tr> <td><input type="checkbox" ng-model="enableDisableButton">Disable Button</td> <td><button ng-disabled="enableDisableButton">點(diǎn)擊我!</button></td></tr><tr> <td><input type="checkbox" ng-model="showHide1">顯示按鈕</td> <td><button ng-show="showHide1">Click Me!</button></td></tr><tr> <td><input type="checkbox" ng-model="showHide2">隱藏按鈕</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">點(diǎn)擊我!</button></td></tr></table></div><script src="http://www.yiibai.com/js/angular.min.js"></script></body></html>輸出結(jié)果
在瀏覽器中打開:textAngularJS.html ,看到結(jié)果如下:
AngularJS 模塊
AngularJS支持模塊化方法。模塊用于單獨(dú)的邏輯表示服務(wù),控制器,應(yīng)用程序等。為保持代碼簡潔,我們在單獨(dú)的 js 文件中定義模塊,并將其命名為 module.js文件。 在這個例子中,我們要創(chuàng)建兩個模塊。
應(yīng)用模塊 - 控制器用于初始化應(yīng)用程序。
控制器模塊 - 用于定義控制器。
應(yīng)用模塊
mainApp.jsvar mainApp = angular.module("mainApp", []);在這里,我們聲明了使用 angular.module 函數(shù)的應(yīng)用程序mainApp模塊。我們已經(jīng)傳遞一個空數(shù)組給它。這個數(shù)組通常包含依賴模塊。
控制器模塊
studentController.jsmainApp.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 函數(shù)的一個控制器 studentController 模塊。
使用模塊
<div ng-app="mainApp" ng-controller="studentController">..<script src="mainApp.js"></script><script src="studentController.js"></script>這里我們使用 ng-app 指令和控制器使用 ng-controller 指令的應(yīng)用模塊。我們已經(jīng)在主HTML頁面導(dǎo)入 mainApp.js 和 studentController.js。
實(shí)例
下面的例子將展示上述所有模塊。
testAngularJS.html<html><head><title>Angular JS 模塊實(shí)例</title><script src="http://www.yiibai.com/js/angular.min.js"></script><script src="mainApp.js"></script><script src="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 模塊應(yīng)用實(shí)例</h2><div ng-app="mainApp" ng-controller="studentController"><table border="0"><tr><td>姓:</td><td><input type="text" ng-model="student.firstName"></td></tr><tr><td>名: </td><td><input type="text" ng-model="student.lastName"></td></tr><tr><td>姓名: </td><td>{{student.fullName()}}</td></tr><tr><td>科目:</td><td><table> <tr> <th>名字</th> <th>標(biāo)記</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.jsvar mainApp = angular.module("mainApp", []);studentController.jsmainApp.controller("studentController", function($scope) { $scope.student = { firstName: "周", lastName: "杰倫", fees:500, subjects:[ {name:'物理',marks:78}, {name:'化學(xué)',marks:82}, {name:'語文',marks:68}, {name:'外語',marks:79}, {name:'Java',marks:87} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } };});輸出結(jié)果
在瀏覽器中打開 textAngularJS.html; 看到的結(jié)果如下所示:
AngularJS表單
AngularJS豐富表格填寫和驗證。 我們可以用ng-click來處理AngularJS點(diǎn)擊按鈕,使用$dirty和$invalid 來做驗證。使用 novalidate 以及表單來聲明禁止瀏覽器做特定的驗證。表單控件大量使用Angular事件。讓我們首先快速瀏覽一下事件。
事件
AngularJS提供可與HTML控件相關(guān)聯(lián)的多個事件。例如ng-click通常與按鈕相關(guān)聯(lián)。下面是支持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
表格的復(fù)位數(shù)據(jù)上使用 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 = "[email protected]"; } $scope.reset();}</script>驗證數(shù)據(jù)
以下可用于跟蹤錯誤。
$dirty - 狀態(tài)指示值已被改變
$invalid- 指示值的狀態(tài)是無效的
$error- 指出確切的錯誤
示例
下面的例子將展示上述所有指令。
testAngularJS.html<html><head><title>AngularJS 表單</title><script src="http://www.yiibai.com/js/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 表單應(yīng)用示例</h2><div ng-app="mainApp" ng-controller="studentController"><form name="studentForm" novalidate><table border="0"><tr><td>姓氏:</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">姓氏不可為空.</span> </span></td></tr><tr><td>名字: </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">名字必填.</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 必填.</span> <span ng-show="studentForm.email.$error.email">無效的Email地址.</span> </span></td></tr><tr><td><button ng-click="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()">提交</button></td></tr></table></form></div><script>var mainApp = angular.module("mainApp", []);mainApp.controller('studentController', function($scope) { $scope.reset = function(){ $scope.firstName = "Zhuo"; $scope.lastName = "Jar"; $scope.email = "yiibai.com@Gmail.com"; } $scope.reset();});</script></body></html>輸出結(jié)果
在瀏覽器中打開 textAngularJS.html。看到結(jié)果結(jié)果如下:
AngularJS Includes
HTML不支持HTML頁面嵌入到HTML頁面。為了實(shí)現(xiàn)這一函數(shù)通過以下方式被使用:
使用Ajax - 使服務(wù)器調(diào)用來獲取相應(yīng)的HTML頁面,并將其設(shè)置在HTML控制的innerHTML。
使用服務(wù)器端包含 - JSP,PHP和其他Web端服務(wù)器技術(shù)可以包括HTML頁面在動態(tài)頁面內(nèi)。
使用AngularJS,我們可以用ng-include 指令使嵌入一個HTML頁面在HTML頁面中。
<div ng-app="" ng-controller="studentController"> <div ng-include="'main.htm'"></div> <div ng-include="'subjects.htm'"></div></div>實(shí)例
tryAngularJS.html<html><head><title>Angular JS Includes 示例</title><script src="http://www.yiibai.com/js/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 Include示例</h2><div ng-app="mainApp" ng-controller="studentController"><div ng-include="'main.html'"></div><div ng-include="'subjects.html'"></div></div><script>var mainApp = angular.module("mainApp", []);mainApp.controller('studentController', function($scope) { $scope.student = { firstName: "周", lastName: "杰倫", fees:500, subjects:[ {name:'物理',marks:78}, {name:'化學(xué)',marks:82}, {name:'語文',marks:68}, {name:'外語',marks:79}, {name:'Java',marks:87} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } };});</script></body></html>main.html<table border="0"> <tr><td>姓氏:</td><td><input type="text" ng-model="student.firstName"></td></tr> <tr><td>名字: </td><td><input type="text" ng-model="student.lastName"></td></tr> <tr><td>全名: </td><td>{{student.fullName()}}</td></tr></table>subjects.html<p>科目:</p><table> <tr> <th>名字</th> <th>標(biāo)記</th> </tr> <tr ng-repeat="subject in student.subjects"> <td>{{ subject.name }}</td> <td>{{ subject.marks }}</td> </tr></table>輸出結(jié)果
要運(yùn)行這個例子,需要部署textAngularJS.html,main.html 和 subjects.html 到Web服務(wù)器。使用 URL 訪問服務(wù)器并在 Web 瀏覽器中打開 textAngularJS.html。看到結(jié)果如下:
AngularJS Ajax
AngularJS提供 $http 控制,可以作為一種服務(wù)從服務(wù)器讀取數(shù)據(jù)。服務(wù)器可以建立數(shù)據(jù)庫調(diào)用來獲取記錄。AngularJS需要JSON格式的數(shù)據(jù)。一旦數(shù)據(jù)準(zhǔn)備好,$http可以用以下面的方式從服務(wù)器得到數(shù)據(jù)。
function studentController($scope,$http) {var url="data.txt"; $http.get(url).success( function(response) { $scope.students = response; });}在這里,data.txt中包含了學(xué)生記錄。$http服務(wù)使 Ajax 調(diào)用并設(shè)置響應(yīng)到學(xué)生的屬性。 "students" 模型可以用于繪制 HTML 表格。
示例
data.txt[{"Name" : "周杰倫","RollNo" : 104,"Percentage" : "80%"},{"Name" : "陳小春","RollNo" : 231,"Percentage" : "71%"},{"Name" : "張學(xué)友","RollNo" : 391,"Percentage" : "75%"},{"Name" : "鄧紫祺","RollNo" : 451,"Percentage" : "77%"}]testAngularJS.html<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Angular JS Includes示例</title><script src="http://www.yiibai.com/js/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 應(yīng)用示例</h2><div ng-app="mainApp" ng-controller="studentController"><table> <tr> <th>名字</th> <th>號碼</th> <th>百分比</th> </tr> <tr ng-repeat="student in students"> <td>{{ student.Name }}</td> <td>{{ student.RollNo }}</td> <td>{{ student.Percentage }}</td> </tr></table></div><script>var mainApp = angular.module("mainApp", []);mainApp.controller('studentController', function($scope, $http) { var url="data.txt"; $http.get(url).success( function(response) { $scope.students = response; });});</script></body></html>輸出結(jié)果
要運(yùn)行這個例子,需要部署 textAngularJS.html,data.txt 到 Web 服務(wù)器。在服務(wù)器使用 URL 在Web瀏覽器中打開textAngularJS.html。看到結(jié)果如下:
AngularJS 視圖
AngularJS支持通過單個頁面上的多個視圖單頁應(yīng)用。要做到這一點(diǎn)AngularJS提供了ng-view 、 ng-template 指令和 $routeProvider 服務(wù)。
ng-view
NG-view標(biāo)記簡單地創(chuàng)建一個占位符,其中一個相應(yīng)的視圖(HTML或ng-template視圖),可以根據(jù)配置來放置。
使用
定義主模塊使用一個 div 及ng-view。
<div ng-app="mainApp">... <div ng-view></div></div>ng-template
ng-template指令用于創(chuàng)建使用腳本標(biāo)記的HTML視圖。它包含一個“id”屬性用于由 $routeProvider 映射帶有控制器的視圖。
使用
定義腳本塊類型為 ng-template 的主模塊 。
<div ng-app="mainApp">... <script type="text/ng-template" id="addStudent.htm"> <h2> Add Student </h2> {{message}} </script></div>$routeProvider
$routeProvider是用來設(shè)置URL配置的關(guān)鍵服務(wù),映射與對應(yīng)的HTML頁面或ng-template,并附加相同的控制器。
使用
定義腳本塊類型為 ng-template 的主模塊 。
<div ng-app="mainApp">... <script type="text/ng-template" id="addStudent.htm"> <h2> Add Student </h2> {{message}} </script></div>使用
定義腳本塊及主模塊,并設(shè)置路由配置。
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' }); }]);以下是在上面的例子中要考慮的重點(diǎn)。
$ routeProvider定義作為一個函數(shù)在mainApp模塊的配置下,使用鍵 '$routeProvider'.
$routeProvider定義URL “/addStudent”,然后映射到“addStudent.htm”。addStudent.htm 存在于相同的路徑的主html頁面。如果HTM網(wǎng)頁沒有定義,那么NG-模板使用id="addStudent.htm"。我們使用ng-template。
"otherwise" 用于設(shè)置的默認(rèn)視圖。
"controller" 用于為視圖設(shè)置相應(yīng)的控制器。
示例
下面的例子將展示上述所有指令。
testAngularJS.html<html><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Angular JS 視圖</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script></head><body> <h2>AngularJS 視圖應(yīng)用示例</h2> <div ng-app="mainApp"> <p><a href="#addStudent">添加學(xué)生</a></p> <p><a href="#viewStudents">查看學(xué)生</a></p> <div ng-view></div> <script type="text/ng-template" id="addStudent.html"> <h2> 添加學(xué)生 </h2> {{message}} </script> <script type="text/ng-template" id="viewStudents.html"> <h2> 查看學(xué)生 </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 = "這個頁面是用于顯示學(xué)生信息的輸入表單"; }); mainApp.controller('ViewStudentsController', function($scope) { $scope.message = "這個頁面是用于顯示所有學(xué)生信息"; }); </script></body></html>結(jié)果
在瀏覽器中打開 textAngularJS.html 看到結(jié)果如下:
AngularJS 作用域
作用域是視圖連接控制器起特殊作用的JavaScript對象。作用域包含模型數(shù)據(jù)。在控制器,模型數(shù)據(jù)通過$ scope對象訪問。
<script> var mainApp = angular.module("mainApp", []); mainApp.controller("shapeController", function($scope) { $scope.message = "In shape controller"; $scope.type = "Shape"; });</script>以下是在上面的例子中要考慮的重點(diǎn)。
$scope被作為第一個參數(shù)在其構(gòu)造器確定指示控制器。
$scope.message 和 $scope.type 在HTML頁面中使用模型。
我們已經(jīng)設(shè)置了模型的值,這將反映在應(yīng)用模塊,其控制器shapeController中。
也可以在 $scope 內(nèi)定義函數(shù)。
繼承作用域
作用域由控制器指定。如果我們定義嵌套控制器,那么子控制器將繼承其父控制器的作用域范圍。
<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>以下是在上面的例子中要考慮的重點(diǎn)。
我們在shapeController設(shè)定模型的值。
我們重載子控制器 circleController 的消息。當(dāng)模塊的控制器 circleController 中的 “message” 一起使用,將重寫消息。
示例
下面的例子將展示上述所有指令。
testAngularJS.html<html><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Angular JS 表單</title></head><body> <h2>AngularJS 表單應(yīng)用示例</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://www.yiibai.com/js/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>輸出結(jié)果
在瀏覽器中打開 textAngularJS.html 看到結(jié)果如下:
AngularJS Services
AngularJS使用服務(wù)架構(gòu)支持“分離 - 關(guān)注”的概念。服務(wù)(Services)是JavaScript函數(shù),并負(fù)責(zé)只做一個特定的任務(wù)。這使得它們維護(hù)和測試單個的實(shí)體。控制器,過濾器可以基于請求調(diào)用它們。服務(wù)注入正常使用AngularJS的依賴注入機(jī)制。
AngularJS提供例如,$http, $route, $window, $location等許多內(nèi)置服務(wù),每個服務(wù)負(fù)責(zé)例如一個特定的任務(wù),$http是用來做AJAX調(diào)用來從服務(wù)器獲取數(shù)據(jù)。 $route用來定義路由信息等。內(nèi)置的服務(wù)總是以$符號為前綴。
有兩種方法來創(chuàng)建服務(wù)。
factory
service
使用工廠方法
使用工廠方法,我們首先定義一個工廠,然后分配方法給它。
var mainApp = angular.module("mainApp", []); mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; });使用服務(wù)方法
使用服務(wù)的方法,我們定義了一個服務(wù),然后分配方法給它。 也可以注入已可用的服務(wù)給它。
mainApp.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); }});示例
下面的例子將展示上述所有指令。
testAngularJS.html<html><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Angular JS 服務(wù)示例</title> <script src="http://www.yiibai.com/js/angular.min.js"></script></head><body> <h2>AngularJS 服務(wù)應(yīng)用示例</h2> <div ng-app="mainApp" ng-controller="CalcController"> <p>輸入一個數(shù)字: <input type="number" ng-model="number" /> <button ng-click="square()">X<sup>2</sup></button> <p>結(jié)果: {{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>結(jié)果
在瀏覽器中打開 textAngularJS.html 看到結(jié)果如下:
AngularJS依賴注入
依賴注入是部件賦予的,不是硬組件內(nèi)的編碼的依賴設(shè)計模式。這從定位減輕組件的依賴,使依賴可配置。這有助于使組件可重復(fù)使用,維護(hù)和測試。
AngularJS提供了一個至高無上的依賴注入機(jī)制。它提供了一種可被注入彼此作為依賴以下核心組件。
值 - value
工廠 - factory
服務(wù) - service
提供者 - provider
常量 - constant
值
值是簡單的JavaScript對象,并用它在配置階段傳遞值到控制器。
//define a modulevar 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); }});工廠
工廠是一個函數(shù)用于返回結(jié)果值。它根據(jù)需要創(chuàng)建一個值,當(dāng)一個服務(wù)或控制器需要時。它通常使用一個工廠函數(shù)來計算和返回結(jié)果值
//define a modulevar mainApp = angular.module("mainApp", []);//create a factory "MathService" which provides a method multiply to return multiplication of two numbersmainApp.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); }});...服務(wù)
服務(wù)是一個單獨(dú)的JavaScript包含了一組函數(shù)對象來執(zhí)行某些任務(wù)。服務(wù)正在使用 service() 函數(shù),然后注射到控制器中。
//define a modulevar 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 controllermainApp.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內(nèi)部創(chuàng)建的服務(wù),工廠等。在配置階段(第一階段AngularJS引導(dǎo)自身期間)。下面提及的腳本可以被用來創(chuàng)建,我們已經(jīng)在前面創(chuàng)建了MathService。提供者是一個特殊的工廠方法使用get()方法來返回值/服務(wù)/工廠。
//define a modulevar 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; }; });});常量
常量用于通過配置的相應(yīng)值,考慮到值不能在配置階段傳遞使用。
mainApp.constant("configParam", "constant value");示例
下面的例子將展示上述所有指令的使用。
testAngularJS.html<html><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>AngularJS 依賴注入</title></head><body> <h2>AngularJS 依賴注入應(yīng)用示例</h2> <div ng-app="mainApp" ng-controller="CalcController"> <p>輸入一個整數(shù): <input type="number" ng-model="number" /> <button ng-click="square()">X<sup>2</sup></button> <p>結(jié)果值: {{result}}</p> </div> <script src="http://www.yiibai.com/js/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>結(jié)果
在瀏覽器中打開 textAngularJS.html 看到結(jié)果如下:
AngularJS自定義指令
自定義指令用于在AngularJS中來擴(kuò)展HTML的功能。自定義指令使用“指令”函數(shù)定義。自定義指令只是替換了被激活的元素。AngularJS應(yīng)用程序引導(dǎo)過程中找到匹配的元素,并使用自定義指令compile() 方法,一次使用基于指令的范圍自定義指令link() 方法處理元素。AngularJS 為下面的元素類型創(chuàng)建自定義的指令提供支持。
元素指令 - 當(dāng)遇到指令激活匹配的元素。
屬性 - - 當(dāng)遇到指令激活屬性時匹配。
CSS - - 當(dāng)遇到指令激活匹配CSS樣式。
注釋 - - 當(dāng)遇到指令激活匹配的注釋。
理解自定義指令
定義自定義HTML標(biāo)簽。
<student name="Mahesh"></student><br/><student name="Piyush"></student>定義自定義指令來處理上面的自定義HTML標(biāo)簽。
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 htmlmainApp.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;});定義控制器以更新指令的作用域。這里我們使用名稱屬性的值作為子的作用域。
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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Angular JS 自定義指令</title></head><body> <h2>AngularJS 自定義指令示例</h2> <div ng-app="mainApp" ng-controller="StudentController"> <student name="Mahesh"></student><br/> <student name="Piyush"></student> </div> <script src="http://www.yiibai.com/js/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> , 編號: <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> , 編號: <b>"+$scope.student.rollno+"</b><br/>"); element.css("background-color", "#eee"); } return linkFunction; } return directive; }); mainApp.controller('StudentController', function($scope) { $scope.Mahesh = {}; $scope.Mahesh.name = "張學(xué)友"; $scope.Mahesh.rollno = 100; $scope.Piyush = {}; $scope.Piyush.name = "陳奕迅"; $scope.Piyush.rollno = 102; }); </script></body></html>結(jié)果
在Web瀏覽器中打開textAngularJS.htm。看到結(jié)果如下:
AngularJS國際化
AngularJS支持內(nèi)置國際化三種類型的過濾器:貨幣,日期和數(shù)字。我們只需要根據(jù)國家的區(qū)域合并相應(yīng)的JS。默認(rèn)情況下它處理瀏覽器的語言環(huán)境。例如,使用丹麥語區(qū)域設(shè)置,使用下面的腳本:
<script src="https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script>使用中文區(qū)域設(shè)置示例
testAngularJS.html<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Angular JS 國際化</title></head><body> <h2>AngularJS 國際化應(yīng)用示例</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.3.14/angular.min.js"></script> <script src="http://cdnjscn.b0.upaiyun.com/libs/angular-i18n/1.2.0/angular-locale_zh-cn.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>結(jié)果
在Web瀏覽器中打開textAngularJS.htm。看到結(jié)果如下:
![]()
使用瀏覽器的語言環(huán)境示例
testAngularJS.html<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Angular JS 瀏覽器語言設(shè)置示例</title></head><body> <h2>AngularJS 區(qū)域語言設(shè)置(瀏覽器設(shè)置)</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.3.14/angular.min.js"></script> <!-- <script src="http://cdnjscn.b0.upaiyun.com/libs/angular-i18n/1.2.0/angular-locale_zh-hk.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>結(jié)果
在Web瀏覽器中打開textAngularJS.html。看到結(jié)果如下:
新聞熱點(diǎn)
疑難解答