一、簡介
AngularJS 是由 Google 的員工 Mi?ko Hevery 從 2009 年開始著手開發(fā),版本 1.0 是在 2012 年發(fā)布的。該項(xiàng)目目前已由 Google 正式支持,有一個全職的開發(fā)團(tuán)隊(duì)繼續(xù)開發(fā)和維護(hù)這個庫。
AngularJS 可以通過新的屬性和表達(dá)式擴(kuò)展了 HTML,可以構(gòu)建一個單一頁面應(yīng)用程序。AngularJS有著諸多特性,最為核心的是:MVC、模塊化、自動化雙向數(shù)據(jù)綁定、語義化標(biāo)簽、依賴注入等等。
注意:在學(xué)習(xí)AngularJS之前,需要先掌握html/css, javascript等基礎(chǔ)前端知識
使用
AngularJS 是一個 JavaScript 框架。它是一個以 JavaScript 編寫的庫。
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
二、指令和表達(dá)式
指令
AngularJS 通過 ng-directives 擴(kuò)展了 HTML。
ng-app
ng-app 指令定義一個 AngularJS 應(yīng)用程序。
ng-app 指令定義了 AngularJS 應(yīng)用程序的 根元素。
ng-app 指令在網(wǎng)頁加載完畢時會自動引導(dǎo)(自動初始化)應(yīng)用程序。
ng-init
ng-init 指令初始化應(yīng)用程序數(shù)據(jù)。
通常情況下,不使用 ng-init??梢允褂靡粋€控制器或模塊來代替它。
ng-model
ng-model 指令把元素值(比如輸入域的值)綁定到應(yīng)用程序。
ng-bind
ng-bind 指令把應(yīng)用程序數(shù)據(jù)綁定到 HTML 視圖。
ng-repeat
ng-repeat 指令對于集合中(數(shù)組中)的每個項(xiàng)會 克隆一次 HTML 元素。
<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
<p>使用 ng-repeat 來循環(huán)數(shù)組</p>
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
創(chuàng)建自定義指令
除了 AngularJS 內(nèi)置的指令外,我們還可以創(chuàng)建自定義指令。
你可以使用 .directive 函數(shù)來添加自定義的指令。
要調(diào)用自定義指令,HTML 元素上需要添加自定義指令名。
使用駝峰法來命名一個指令, runoobDirective, 但在使用它時需要以 - 分割, runoob-directive:
<body ng-app="myApp">
<runoob-directive></runoob-directive>
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
restrict : "A",
template : "<h1>自定義指令!</h1>"
};
});
</script>
</body>
可以使用如下四種方式來調(diào)用:
·元素名<runoob-directive></runoob-directive>,restrict : "E",
·屬性<div runoob-directive></div>,restrict : "C",
·類名<div class="runoob-directive"></div>,restrict : "A",
·注釋,restrict : "M",
表達(dá)式
AngularJS 表達(dá)式寫在雙大括號內(nèi):{{ expression }}。
AngularJS 表達(dá)式把數(shù)據(jù)綁定到 HTML,這與 ng-bind 指令有異曲同工之妙。
注意,ng-model提供的是$scope --> view and view --> $scope的雙向綁定。而ng-bind提供的是$scope --> view的單向綁定,類似{{ expression }},不過也有細(xì)微的區(qū)別:使用雙大括號會在數(shù)據(jù)加載完之前,瀏覽器先渲染html,從而讓用戶看到類似{{ expression }}這樣的內(nèi)容,而使用ng-bind卻不會。
表達(dá)式中不僅可以有數(shù)字的加減乘除,還可以有類似字符串操作、對象、數(shù)組等。
//字符串
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>姓名: <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>
//對象
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>姓為 {{ person.lastName }}</p>
</div>
//數(shù)組
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>第三個值為 {{ points[2] }}</p>
</div>
Angularjs應(yīng)用
AngularJS 模塊(Module) 定義了 AngularJS 應(yīng)用。
AngularJS 控制器(Controller) 用于控制 AngularJS 應(yīng)用。
ng-app指令定義了應(yīng)用, ng-controller 定義了控制器。
<div ng-app="myApp" ng-controller="myCtrl">
名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
<br>
姓名: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>
三、作用域、控制器和過濾器
作用域
Scope(作用域) 是應(yīng)用在 HTML (視圖) 和 JavaScript (控制器)之間的紐帶。
Scope 是一個對象,有可用的方法和屬性。
Scope 可應(yīng)用在視圖和控制器上。
當(dāng)你在 AngularJS 創(chuàng)建控制器時,你可以將 $scope 對象當(dāng)作一個參數(shù)傳遞:
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
<h1>{{greeting}}</h1>
<button ng-click='sayHello()'>點(diǎn)我</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "Runoob";
$scope.sayHello = function() {
$scope.greeting = 'Hello ' + $scope.name + '!';
};
});
</script>
scope 是一個 JavaScript 對象,帶有屬性和方法,這些屬性和方法可以在視圖和控制器中使用。
控制器
AngularJS 應(yīng)用程序被控制器控制。
ng-controller 指令定義了應(yīng)用程序控制器。
控制器是 JavaScript 對象,由標(biāo)準(zhǔn)的 JavaScript 對象的構(gòu)造函數(shù) 創(chuàng)建。
<div ng-app="myApp" ng-controller="personCtrl">
名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
<br>
姓名: {{fullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
}
});
</script>
過濾器
過濾器可以使用一個管道字符(|)添加到表達(dá)式和指令中。
| 過濾器 | 描述 |
|---|---|
| currency | 格式化數(shù)字為貨幣格式。 |
| filter | 從數(shù)組項(xiàng)中選擇一個子集。 |
| lowercase | 格式化字符串為小寫。 |
| orderBy | 根據(jù)某個表達(dá)式排列數(shù)組。 |
| uppercase | 格式化字符串為大寫。 |
四、服務(wù)
在 AngularJS 中,服務(wù)是一個函數(shù)或?qū)ο?,可在你?AngularJS 應(yīng)用中使用。
AngularJS 內(nèi)建了30 多個服務(wù)。
有個 $location 服務(wù),它可以返回當(dāng)前頁面的 URL 地址。
http服務(wù)
var app = angular.module('myApp', []);
app.controller('siteCtrl', function($scope, $http) {
$http({
method: 'GET',
url: 'https://www.runoob.com/try/angularjs/data/sites.php'
}).then(function successCallback(response) {
$scope.names = response.data.sites;
}, function errorCallback(response) {
// 請求失敗執(zhí)行代碼
});
});
//也可以通過下面的方式進(jìn)行簡寫
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.html").then(function (response) {
$scope.myWelcome = response.data;
});
});
timeout服務(wù)
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
}, 2000);
});
interval服務(wù)
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
創(chuàng)建自定義服務(wù)
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
五、表單
Input
<input type="text" ng-model="firstname">
復(fù)選框
<form>
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>
<h1 ng-show="myVar">My Header</h1>
單選框
<form>
選擇一個選項(xiàng):
<input type="radio" ng-model="myVar" value="dogs">Dogs
<input type="radio" ng-model="myVar" value="tuts">Tutorials
<input type="radio" ng-model="myVar" value="cars">Cars
</form>
下拉菜單
<form>
選擇一個選項(xiàng):
<select ng-model="myVar">
<option value="">
<option value="dogs">Dogs
<option value="tuts">Tutorials
<option value="cars">Cars
</select>
</form>
輸入驗(yàn)證
AngularJS 表單和控件可以提供驗(yàn)證功能,并對用戶輸入的非法數(shù)據(jù)進(jìn)行警告。
<!DOCTYPE html>
<html>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<body>
<h2>Validation Example</h2>
<form ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate>
<p>用戶名:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">用戶名是必須的。</span>
</span>
</p>
<p>郵箱:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">郵箱是必須的。</span>
<span ng-show="myForm.email.$error.email">非法的郵箱。</span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = 'john.doe@gmail.com';
});
</script>
</body>
</html>
六、包含和API
包含
使用 AngularJS, 你可以使用 ng-include 指令來包含 HTML 內(nèi)容
<body ng-app="">
<div ng-include="'runoob.htm'"></div>
</body>
如果被包含的html里面包含js文件,也是可以被執(zhí)行的。
默認(rèn)情況下是不能跨域包含的,如果要跨域包含,則需要設(shè)置白名單。
<body ng-app="myApp">
<div ng-include="'http://c.runoob.com/runoobtest/angular_include.php'"></div>
<script>
var app = angular.module('myApp', [])
app.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'http://c.runoob.com/runoobtest/**'
]);
});
</script>
</body>
| API | 描述 |
|---|---|
| angular.lowercase() | 轉(zhuǎn)換字符串為小寫 |
| angular.uppercase() | 轉(zhuǎn)換字符串為大寫 |
| angular.isString() | 判斷給定的對象是否為字符串,如果是返回 true。 |
| angular.isNumber() | 判斷給定的對象是否為數(shù)字,如果是返回 true。 |
API
AngularJS 全局 API 用于執(zhí)行常見任務(wù)的 JavaScript 函數(shù)集合:
| API | 描述 |
|---|---|
| angular.lowercase() | 轉(zhuǎn)換字符串為小寫 |
| angular.uppercase() | 轉(zhuǎn)換字符串為大寫 |
| angular.isString() | 判斷給定的對象是否為字符串,如果是返回 true。 |
| angular.isNumber() | 判斷給定的對象是否為數(shù)字,如果是返回 true。 |
七、路由
AngularJS 路由允許我們通過不同的 URL 訪問不同的內(nèi)容。
通過 AngularJS 可以實(shí)現(xiàn)多視圖的單頁Web應(yīng)用(single page web application,SPA)。
通常我們的URL形式為 http://runoob.com/first/page,但在單頁Web應(yīng)用中 AngularJS 通過 # + 標(biāo)記 實(shí)現(xiàn)。
實(shí)例解析:
1、載入了實(shí)現(xiàn)路由的 js 文件:angular-route.js。
2、包含了 ngRoute 模塊作為主應(yīng)用模塊的依賴模塊。
angular.module('routingDemoApp',['ngRoute'])
3、使用 ngView 指令。
<div ng-view></div>
該 div 內(nèi)的 HTML 內(nèi)容會根據(jù)路由的變化而變化。
4、配置 $routeProvider,AngularJS $routeProvider 用來定義路由規(guī)則。
module.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/',{template:'這是首頁頁面'})
.when('/computers',{template:'這是電腦分類頁面'})
.when('/printers',{template:'這是打印機(jī)頁面'})
.otherwise({redirectTo:'/'});
}]);
AngularJS 模塊的 config 函數(shù)用于配置路由規(guī)則。通過使用 configAPI,我們請求把$routeProvider注入到我們的配置函數(shù)并且使用$routeProvider.whenAPI來定義我們的路由規(guī)則。
$routeProvider 為我們提供了 when(path,object) & otherwise(object) 函數(shù)按順序定義所有路由,函數(shù)包含兩個參數(shù):
第一個參數(shù)是 URL 或者 URL 正則規(guī)則。
第二個參數(shù)是路由配置對象。
路由設(shè)置對象
AngularJS 路由也可以通過不同的模板來實(shí)現(xiàn)。
$routeProvider.when 函數(shù)的第一個參數(shù)是 URL 或者 URL 正則規(guī)則,第二個參數(shù)為路由配置對象。
路由配置對象語法規(guī)則如下:
$routeProvider.when(url, {
template: string,
templateUrl: string,
controller: string, function 或 array,
controllerAs: string,
redirectTo: string, function,
resolve: object<key, function>
});
參數(shù)說明:
template:
如果我們只需要在 ng-view 中插入簡單的 HTML 內(nèi)容,則使用該參數(shù):
.when('/computers',{template:'這是電腦分類頁面'})
templateUrl:
如果我們只需要在 ng-view 中插入 HTML 模板文件,則使用該參數(shù):
$routeProvider.when('/computers', {
templateUrl: 'views/computers.html',
});
以上代碼會從服務(wù)端獲取 views/computers.html 文件內(nèi)容插入到 ng-view 中。
controller:
function、string或數(shù)組類型,在當(dāng)前模板上執(zhí)行的controller函數(shù),生成新的scope。
controllerAs:
string類型,為controller指定別名。
redirectTo:
重定向的地址。
resolve:
指定當(dāng)前controller所依賴的其他模塊。
示例
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script src="http://apps.bdimg.com/libs/angular-route/1.3.13/angular-route.js"></script>
<script type="text/javascript">
angular.module('ngRouteExample', ['ngRoute'])
.controller('HomeController', function ($scope, $route) { $scope.$route = $route;})
.controller('AboutController', function ($scope, $route) { $scope.$route = $route;})
.config(function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'embedded.home.html',
controller: 'HomeController'
}).
when('/about', {
templateUrl: 'embedded.about.html',
controller: 'AboutController'
}).
otherwise({
redirectTo: '/home'
});
});
</script>
</head>
<body ng-app="ngRouteExample" class="ng-scope">
<script type="text/ng-template" id="embedded.home.html">
<h1> Home </h1>
</script>
<script type="text/ng-template" id="embedded.about.html">
<h1> About </h1>
</script>
<div>
<div id="navigation">
<a href="#/home">Home</a>
<a href="#/about">About</a>
</div>
<div ng-view="">
</div>
</div>
</body>
</html>