AngularJS是一个用于web应用程序或者网站的开源JavaScript框架。它扩展了HTML语法,并使其动态化,AngularJS可用于创建单页应用程序(SPA:Single Page Applications)。AngularJS通过数据绑定和依赖注入简化代码的编写。

AngularJS优点

  • 开源框架
  • 谷歌支持
  • 使用MVC设计模式支持关注点分离
  • 易于扩展和定制
  • 易于单元测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app>
Enter you Name: <input type="text" ng-model="name" /><br />
Hello <label for="" ng-bind="name"></label>
</body>
</html>

![1][AngularJS直观展示.jpg]

First AngularJS App

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app>
<h1>First AngularJs App</h1>

Enter Numbers to Multiply:

<input type="text" ng-model="num1">x <input type="text" ng-model="num2">
=<span>{{num1*num2}}</span>
</body>

</html>
<!--
1.html:模板Template
2.ng-XXX:指令Directives
3.{{XXX}}:表达式Expression
-->

![2][AngularJSApp.jpg]

Template

模板是带有附加标记的HTML。AngularJS编译模板并呈现生产的HTML。

Directive

指令是DOM元素上的标记(属性),它将特定的行为添加到DOM元素。AngularJS中大多数指令都是以ng开头的。

ng-app:指示一个起点,引导编译HTML模板。

ng-model:将HTML元素绑定到$scope对象上的属性。

Expression

通常包含在之类的双花括号中,AngularJS框架计算表达式结果。

ng-app Directive

ng-app指令是AngularJS应用程序的起点,它自动初始化AngularJS框架。AngularJS框架在加载整个HTML之后,首先检查ng-app指令,它将自行引导并编译HTML模板。

  • 在AngularJS中编译HTML意味着将事件侦听器附加到HTML以使其具有交互性。
  • AngularJS功能只在ng-app指令内部有效。
  • 一个HTML中只能有一个ng-app指令。

通过bootstrap可以手动初始化AngularJS框架。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body>
<h1>First AngularJs App</h1>

Enter Numbers to Multiply:
<input type="text" ng-model="num1">x <input type="text" ng-model="num2">=<span>{{num1*num2}}</span>
</body>
<script>
//手动初始化AngularJS框架
angular.element(document).ready(function () {
angular.bootstrap(document);
});
</script>
</html>

Expression

AngularJS会计算表达式的值,并将结果绑定到HTML。

表达式可以包括字面量、运算、变量等。

Directive

指令扩展了HTML,AngularJS包含各种内置指令,大部分已ng开头,你还可以为程序创建自定义指令。

重要的内置指令:

Directive Description
ng-app Auto boostrap AngularJS application
ng-init Initializes AngularJS variables
ng-model Binds HTML control’s value to a property on the $scope object
ng-controller Attaches the controller of MVC to the view
ng-bind Replaces the value of HTML control with the value of AngularJS expression
ng-repeat Repeats HTML template once per each item in the specified collection
ng-show Display HTML element based on the value of the specified expression
ng-readonly Makes HTML element read-only based on the value of the specified expesson
ng-disabled Sets the disabled attribute on the HTML element if specified expession evaluates to true
ng-if Removes or recreates HTML based on an expression
ng-click Specified custome behavior when an element is clicked

ng-app

初始化AngularJS并使指定的元素成为应用程序的根元素。

ng-init

初始化AngularJS应用程序中的变量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body>
<div ng-app ng-init="greet='Hello World!';age=18;tech=['Java','C#','PHP'];addr={city:'河南',country:'信阳'}">
MyAge:{{age}}
MyTech:{{tech[1]}}
MyCity:{{addr.city}}
</div>
</body>
</html>

<!--
MyAge:18
MyTech:C#
MyCity:河南
-->

ng-model

实现数据的双向绑定。它将<input>,<select>,<textarea>元素绑定到$scope对象对应的属性上,元素的值即为属性的值。

将数据从控制器传到视图,反之,亦然。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app>
<input type="text" ng-model="name">
<div>
Hello {{name}}
</div>
</body>
</html>
<!--
ng-init初始化的变量不会添加到$scope对象上
ng-model属性会添加到$scope对象上
-->

ng-bind

将通过$scope或者ng-model声明的model属性或者表达式的结构绑定到HTML元素。

将数据从控制器传到视图,反之,不能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app>
<div>
5+5 = <span ng-bind="5+5"></span><br />

Enter your name: <input type="text" ng-model="name"> <br />
Hello <span ng-bind="name"></span>
</div>
</body>

</html>

ng-repeat

对指定数组集合中的每项重复创建HTML元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app ng-init="students=['zhangsan','lisi','wangwu']">
<ol>
<li ng-repeat="name in students">
{{name}}
</li>
</ol>
</body>
</html>

![3][ng-repeat.jpg]

ng-if

根据表达式返回的布尔值【True】创建HTML元素,【False】删除HTML元素。

ng-readonly

根据表达式返回的布尔值【True】HTML元素只读。

ng-disabled

根据表达式返回的布尔值【True】HTML元素禁用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app ng-init="checked=true">
Click Me: <input type="checkbox" ng-model="checked" /> <br />
<div>
New: <input type="text" ng-if="checked" />
</div>
<div>
Read-only: <input type="text" ng-readonly="checked" value="This is Readonly" />
</div>
<div>
Disabled: <input type="text" ng-disabled="checked" value="This is Disabled" />
</div>
</body>

</html>

Directive Syntax

AngularJS指令可以多种方式应用于DOM元素。ng-不是强制性的。

例如:ng-model可以写成x-ng-model或者data-ng-model,指令可以从x-或者data-开头

​ ng-model还可以写成ng_model或者ng:model,指令可以将-替换成_或者

Controller

控制器是在AngularJS中是一个JavaScript函数。它使用$scope对象维护应用程序数据和行为。

将属性和方法附加到控制器函数的$scope对象,控制器函数将添加、更新数据并将行为附加到HTML元素。

ng-controller指令用于在HTML元素中指定控制器,该控制器控制HTML元素及其子元素中的数据。

AngularJS框架为每个控制器函数注入$scope对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myNgApp">
<div ng-controller="myController">
<!-- 输出$scope对象的message属性值 -->
{{message}}
</div>
<script>
var ngApp = angular.module("myNgApp", []);
ngApp.controller("myController", function ($scope) {
$scope.message = "Hello World!"; //向$scope中添加message属性并赋值
});
</script>
</body>
</html>

Attach Behaviors

可以将多个方法附加到控制器内的$scope对象,这些方法可作为事件处理程序或者其他目的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myNgApp">
<div ng-controller="myController">
Enter Message: <input type="text" ng-model="message" /><br />
<button ng-click="showMessage(message)">Show Message</button>
</div>
<script>
var ngApp = angular.module("myNgApp", []);
ngApp.controller("myController", function ($scope) {
$scope.message = "Hello World!"; //向$scope中添加message属性并赋值
$scope.showMessage = function (msg) { //向$scope中添加showMessage方法
alert(msg);
};
});
</script>
</body>
</html>

Attach Complex object

可以向$scope添加复杂对象,然后在HTML中显示该对象的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myNgApp">
<h2>Student Information:</h2>
<div ng-controller="myController">
First Name: {{student.firstName}} <br />
Last Name:{{student.lastName}}
</div>
<script>
var ngApp = angular.module("myNgApp", []);
ngApp.controller("myController", function ($scope) {
$scope.student = {
firstName: "zhang",
lastName: "san"
}; //向$scope中添加复杂对象
});
</script>
</body>
</html>

Nested Controllers

Angular允许使用嵌套Controllers。

子控制器可以访问父控制器函数中附加的属性和方法,反之,不能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myNgApp">
<div ng-controller="parentController">
Message:{{message1}}
<div ng-controller="childController">
Parent Message:{{message1}}<br />
Child Message:{{message2}}
</div>
Child Message:{{message2}}
</div>
<script>
var ngApp = angular.module("myNgApp", []);
ngApp.controller("parentController", function ($scope) {
$scope.message1 = "This is Parent!";
});
ngApp.controller("childController", function ($scope) {
$scope.message2 = "This is Child!";
});
</script>
</body>
</html>
<!--
Message:This is Parent!
Parent Message:This is Parent!
Child Message:This is Child!
Child Message:
-->

Scope

AngularJS中的$scope是一个内置对象,它包含应用程序的数据和方法,可以在控制器中为 $scope对象创建属性。

AngularJS为应用程序的每个控制器创建并注入不同的$scope对象。因此一个控制器内附加到$scope的数据和方法无法再另一个控制器中访问。

使用嵌套控制器,子控制器继承父控制器的范围对象,因此子控制器可以访问父控制器中添加的属性,反之,不能。

AngularJS应用程序只有一个$rootScope,所有的$scope对象都是子对象,附加到$rootScope的属性和方法可供所有控制器使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myNgApp">
<div ng-controller="parentController">
ControllerName:{{controllerName}}<br />
Message:{{message}}
<div style="margin:10px 0 10px 20px" ng-controller="childController">
ControllerName:{{controllerName}}<br />
Message:{{message}}
</div>
</div>
<div ng-controller="siblingController">
ControllerName:{{controllerName}}<br />
Message:{{message}}
</div>

<script>
var ngApp = angular.module("myNgApp", []);

ngApp.controller("parentController", function ($scope, $rootScope) {
$scope.controllerName = "parentController";
$rootScope.message = "Hello World";
})

ngApp.controller("childController", function ($scope) {
$scope.controllerName = "childController";
})

ngApp.controller("siblingController", function ($scope) {

})
</script>
</body>
</html>

<!--
ControllerName:parentController
Message:Hello World
ControllerName:childController
Message:Hello World
ControllerName:
Message:Hello World
-->

$scope对象的重要方法:

Method Description
$new() Create new child scope
$watch() Register a callback to be executed whenever model property changes
$watchGroup() Register a callback to be executed whenever model properties changes, Here, specify an array of properties to be tracked
$watchCollection() Register a callback to be executed whenever model object or array property changes
$digest() Processes all of the watchers of the current scope and if children
$destroy() Removes the current scope(and all of its children) from the parent scope
$eval() Executed the expression on the current scope and returns the result
$apply() Executed an expression in angular outside the angular framework
$on() Register a callback for an event
$emit() Dispatchers the specified event upwards till $rootScope
$broadcast() Dispatchers the specified event downwards to all child scopes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myNgApp">
<div ng-controller="myController">
Enter Message: <input type="text" ng-model="message" /> <br />
New Message:{{newMessage}}<br />
Old Message:{{oldMessage}}
</div>

<script>
var ngApp = angular.module("myNgApp", []);

ngApp.controller("myController", function ($scope) {
$scope.message = "Hello World";

$scope.$watch("message", function (newValue, oldValue) {
$scope.newMessage = newValue;
$scope.oldMessage = oldValue;
})
});
</script>
</body>
</html>

Events

AngularJS包含某些指令,可用于为各种DOM事件提供自定义行为,如click等。

Event Directive
ng-blur
ng-change
ng-click
ng-dblclick
ng-focus
ng-keydown
ng-keyup
ng-keypress
ng-mousedown
ng-mouseenter
ng-mouseleave
ng-mouseover
ng-mouseup

ng-click

handler for click event

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">
<div ng-controller="myController">
Enter Password: <input type="password" ng-model="password" />
<button ng-click="DisplayMessage(password)">Show Password</button>
</div>

<script>
var myApp = angular.module("myApp", []);

myApp.controller("myController", function ($scope, $window) {
$scope.DisplayMessage = function (value) {
$window.alert(value);
}
})
</script>
</body>
</html>

Services

AngularJS服务是用于特定任务的JavaScript函数,可以在整个应用程序中重用。

AngularJS包含用于不同目的的服务,如$http服务可用于向远程服务器发送Ajax请求。

AngularJS允许自定义服务。

AngularJS内置服务与内置对象一样,以$开头。

![4][AngularJS_Services.jpg]

AngularJS内置Services:

$anchorScroll $exceptionHandler $interval $rootScope
$animate $filter $locale $sceDelegate
$cacheFactory $httpParamSerializer $loaction $sce
$templateCache $httpParamSerializerJQLike $log $templateRequest
$compile $http $parse $timeout
$controller $httpBackend $q $window
$document $interpolate $rootElement

所有的Angular服务都是懒加载和单例,这意味着Angular框架在应用程序组件依赖它时实例化服务,此外,所有的组件共享共同的服务实例。

$http

$http service用于使用浏览器的XMLHttpRequest或者JSONP从远处服务器发送或者接收数据。

$http是一个服务对象,有以下方法:

Method Description
$http.get() Perform Http GET request
$http.head() Perform Http HEAD request
$http.post() Perform Http POST request
$http.put() Perform Http PUT request
$http.delete() Perform Http DELETE request
$http.jsonp() Perform Http JSONP request
$http.patch() Perform Http PATCH request

$http.get()

将HTTP GET请求发送到远程服务器并检索数据。

方法返回HttpPromise对象,其中包含处理HTTP GET请求响应的各种方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">
<div ng-controller="myController">
Response Data:{{data}}
Error:{{error}}
</div>

<script>
var myApp = angular.module("myApp", []);

myApp.controller("myController", function ($scope, $http) {
var onSuccess = function (data, status, headers, config) {
$scope.data = data;
}

var onError = function (data, status, headers, config) {
$scope.error = status;
}

// var promise=$http.get("/demo/getdata").success(onSuccess).error(onError);
var promise = $http.get("/demo/getdata");
promise.success(onSuccess);
promise.error(onError);
})
</script>
</body>
</html>

$http.post()

将HTTP POST请求发送到远程服务器以提交和检索数据。

同样,返回HttpPromise对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">
<div ng-controller="myController">
Response Data:{{data}}
Error:{{error}}
</div>

<script>
var myApp = angular.module("myApp", []);

myApp.controller("myController", function ($scope, $http) {
var onSuccess = function (data, status, headers, config) {
$scope.data = data;
}

var onError = function (data, status, headers, config) {
$scope.error = status;
}

$http.post("/demo/sumitData", {
myData: "Hello world"
})
.success(onSuccess)
.error(onError);
})
</script>
</body>
</html>

$http()

使用$http服务的构造函数来执行HTTP请求。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">
<div ng-controller="myController">
Response Data:{{data}}
Error:{{error}}
</div>

<script>
var myApp = angular.module("myApp", []);

myApp.controller("myController", function ($scope, $http) {
var onSuccess = function (data, status, headers, config) {
$scope.data = data;
}

var onError = function (data, status, headers, config) {
$scope.error = status;
}

var getReq = {
method: "GET",
url: "/demo/getdata"
}
//GET请求
$http(getReq).success(onSuccess).error(onerror);

var postReq = {
method: "POST",
url: "/demo/subimtData",
data: {
myData: "Hello world"
}
}
//POST请求
$http(postReq).success(onSuccess).error(onerror);
})
</script>
</body>
</html>

$log

日志服务$log,将消息记录到浏览器的控制台。

$log服务包含记录错误(error),信息(info),警告(warn),调试(debug)信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">
<div ng-controller="myController">
<p>Please check the browser console for the logging information.</p>
</div>

<script>
var myApp = angular.module("myApp", []);

myApp.controller("myController", function ($log) {
$log.log("This is log.");
$log.error("This is error.");
$log.info("This is info.");
$log.warn("This is warning.");
$log.debug("This is debug");
})
</script>
</body>
</html>

![5][AngularJS_log.jpg]

$interval

$interval与JavaScript中的setInterval()一样,是setInterval()方法的包装。

$interval服务在每个指定的毫秒持续时间内执行指定的函数。

$interval(fn, delay, [count], [invokeApply], [Pass]);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">

<div ng-controller="myController">
{{counter}}
</div>
<script>
var myApp = angular.module("myApp", []);

myApp.controller("myController", function ($scope, $interval) {
$scope.counter = 0;

var increaseCounter = function () {
$scope.counter = $scope.counter + 1;
}

$interval(increaseCounter, 1000);
})
</script>
</body>
</html>

$interval服务返回一个HttpPromise对象,可以通过$interval.cancel(promise)方法停止计数器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">

<div ng-controller="myController">
{{counter}}
<button ng-click="cancel()">Cancel</button>
</div>
<script>
var myApp = angular.module("myApp", []);

myApp.controller("myController", function ($scope, $interval) {
$scope.counter = 0;

var increaseCounter = function () {
$scope.counter = $scope.counter + 1;
}

var promise = $interval(increaseCounter, 1000);

$scope.cancel = function () {
$interval.cancel(promise);
$scope.counter = "Cancelled";
}
})
</script>
</body>
</html>

$window

$window服务,引用浏览器窗口对象,是窗口对象的包装。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">

<div ng-controller="myController">
<button ng-click="DisplayAlert('Hello World!')">Display Alert</button>
<button ng-click="DisplayPrompt()">Display Prompt</button>
</div>
<script>
var myApp = angular.module("myApp", []);

myApp.controller("myController", function ($scope, $window) {

$scope.DisplayAlert = function (message) {
$window.alert(message);
}

$scope.DisplayPrompt = function () {
var name = $window.prompt("Enter your Name:");
$window.alert("Hello " + name);
}
})
</script>
</body>
</html>

Filters

AngularJS 过滤器允许格式化要显示在UI上的数据,而无需改变原有格式。

1
{{expression | filterName:parameter }}

Angular包含各种过滤器用来格式化不同的数据类型,常重要的过滤器如下:

Name Description
Number Formats a numeric data as text with comma and function
Currency Formats numeric data into specified currency format and fraction
Date Formats date to string in specified format
Uppercase Converts string to upper case
Lowercase Converts string to lower case
Filter Filters an array based on specified criterial and returns new array
orderBy Sorts an array based on specified predicate expression
Json Converts JavaScript object into JSON string
limitTo Returns new array containing specified number of elements from an existing array

Number Filter

1
{{ number_expression | number:fractionSize}}

如果指定的表达式未返回有效数字,则数字过滤器将显示空字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app>
Enter Amount: <input type="text" ng-model="amount"> <br/>

100000|number={{100000|number}}<br/>
amount|number={{amount|number}}<br/>
amount|number:2={{amount|number:2}}<br/>
amount|number:4={{amount|number:4}}<br/>
amount|number= <span ng-bind="amount|number"></span>
</body>
</html>

<!--
Enter Amount: 1000

100000|number=100,000 逗号分割
amount|number=1,000 逗号分割
amount|number:2=1,000.00 逗号分割,保留2位小数
amount|number:4=1,000.0000 逗号分割,保留4位小数
amount|number= 1,000 逗号分割
-->

Currency Filter

1
{{ expression | currency : 'currency_symbol' : 'fraction'}}

如果没有提供货币符号,则使用当前区域设置的默认符号。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">
<div ng-controller="myController">
Default currency:{{person.salary|currency}}<br />
Custome currency identifier:{{person.salary|currency:'Rs.'}}<br />
No Fraction:{{person.salary|currency:'Rs.':0}}<br />
Fraction 2: <span ng-bind="person.salary|currency:'GBP':2"></span>
</div>

<script>
var myApp = angular.module("myApp", []);
myApp.controller("myController", function ($scope) {
$scope.person = {
firstName: "zhang",
lastName: "san",
salary: 20000
}
})
</script>
</body>
</html>
<!--
Default currency:$20,000.00
Custome currency identifier:Rs.20,000.00
No Fraction:Rs.20,000
Fraction 2: GBP20,000.00
-->

Date Filter

1
{{ date_expression | date : 'format'}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app>
<div ng-init="person.DOB='323234234898'">
Default date:{{person.DOB|date}}<br />
Short date:{{person.DOB|date:'short'}}<br />
Long date:{{person.DOB|date:'longDate'}}<br />
Year:{{person.DOB|date:'yyyy'}}
</div>
</body>
</html>

<!--
Default date:Mar 30, 1980
Short date:3/30/80 11:17 AM
Long date:March 30, 1980
Year:1980
-->

Uppercase/Lowercase Filer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app>
<div ng-init="person.firstName='Zhang';person.lastName='San'">
Lower case:{{person.firstName+''+person.lastName|lowercase}}<br />
Upper case:{{person.firstName+''+person.lastName|uppercase}}
</div>
</body>
</html>

<!--
Lower case:zhangsan
Upper case:ZHANGSAN
-->

##Filter

根据指定的条件从数组中选择项目并返回新数组。

1
{{ expression | filter : filter_criteria }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">
<div ng-controller="myController">
Enter Name to search: <input type="text" ng-model="searchCondition" /><br />
Result:{{myArr|filter:searchCondition}}
</div>

<script>
var myApp = angular.module("myApp", []);
myApp.controller("myController", function ($scope) {
$scope.myArr = ['zhao', 'qian', 'sun', 'li']
})
</script>
</body>
</html>

<!--
Enter Name to search: i

Result:["qian","li"]
-->

##orderBy Filter

根据指定的表达式谓词对数组进行排序。

1
{{ expression | orderBy : predicate_expression : reverse}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app="myApp">
<div ng-controller="myController">
<select ng-model="SortOrder">
<option value="+name">Name(asc)</option>
<option value="-name">Name(desc)</option>
<option value="+phone">Phone(asc)</option>
<option value="-phone">Phone(desc)</option>
</select>

<ul ng-repeat="person in persons|orderBy:SortOrder">
<li>{{person.name}}-{{person.phone}}</li>
</ul>
</div>

<script>
var myApp = angular.module("myApp", []);
myApp.controller("myController", function ($scope) {
$scope.persons = [{
name: "zhangsan",
phone: 1111
}, {
name: "lisi",
phone: 2222
}, {
name: "wangwu",
phone: 3333
}];
})
</script>
</body>
</html>

<!--
Phone(desc):
wangwu-3333
lisi-2222
zhangsan-1111
-->

Modules

AngularJS中的模块是应用程序的不同部分的容器,如控制器,服务,过滤器,指令等。

使用模块分离关注点。

在模块中使用AngularJS特定函数可以停止全局scope污染。

Application Module

AngularJS应用程序必须创建顶级应用程序模块,此应用程序模块可以包含其他模块,控制器等。

1
2
3
4
5
6
7
8
9
10
11
12
<body ng-app="myApp">
<div ng-controller="myController">
{{message}}
</div>
<script>
//第一个参数:模块名称,第二个参数:依赖的模块组
var myApp = angular.module('myApp',[]);
//通过controller()方法,创建控制器模块myController
//因为控制器模块是在myApp模块内部创建,因此不会成为全局函数
myApp.controller("myController",function($scope){})
</script>
</body>

Modules in Separate Files

模块分离,可以将模块写入到不同的js文件中,在同一HTML中引入。

1
2
3
4
5
6
7
<body ng-app="myApp">
<div ng-controller="myController">
{{message}}
</div>
<script src="app.js" ></script>
<script src="myController.js" ></script>
</body>
1
var myApp = angular.module("myApp", []);
1
2
3
myApp.controller("myController", function ($scope) {
$scope.message = "Hello Angular World!";
});

Form

使用AngularJS实现Form操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<!DOCTYPE html>
<html lang="en" ng-app="studentApp">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-controller="studentController">
<h1>Student Information:</h1>
<form ng-submit="submitStudentForm()">
<label for="firstName">First Name:</label><br />
<input type="text" id="firstName" ng-model="student.firstName" /><br />

<label for="lastName">Last Name:</label><br />
<input type="text" id="lastName" ng-model="student.lastName" /><br />

<label for="dob">DOB:</label><br />
<input type="date" id="dob" ng-model="student.DOB" /><br />

<label for="gender">Gender:</label><br />
<select id="gender" ng-model="student.gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br />

<span>Training Type:</span><br />
<label><input type="radio" value="online" name="training" ng-model="student.trainingType" />Online</label><br />
<label><input type="radio" value="onsite" name="training" ng-model="student.trainingType" />Onsite</label><br />

<span>Subjects:</span><br />
<label><input type="checkbox" ng-model="student.maths" />Maths</label><br />
<label><input type="checkbox" ng-model="student.physics" />Physics</label><br />

<input type="submit" value="submit" /><br />
<input type="reset" value="reset" ng-click="resetForm" /><br />
</form>

<script>
//创建App Module
var studentApp = angular.module("studentApp", []);
//创建Controller
studentApp.controller("studentController", function ($scope, $http) {
//创建学生对象
$scope.originalStudent = {
firstName: "zhang",
lastName: "san",
DOB: new Date(),
gender: "male",
trainingType: "online",
maths: false,
physics: true
};
//将创建的学生对象复制到student,绑定到Form上
$scope.student = angular.copy($scope.originalStudent);
//提交事件
$scope.submitStudentForm = function () {
var onSuccess = function (data, status, headers, config) {
alert("Student save SuccessFully.");
};

var onError = function (data, status, headers, config) {
alert("Error occured.");
};

$http.post("/student/submitData", {
student: $scope.student
})
.success(onSuccess)
.error(onError);
}
//重置事件
$scope.resetForm = function () {
$scope.student = angular.copy($sope.originalStudent);
}
})
</script>
</body>
</html>

Validation

AngularJS可以对HTML进行客户端验证,常用的验证指令如下:

Directive Description
ng-required Sets required attribute on an input filed
ng-minlength Sets minlength attribute on an input field
ng-maxlength Sets maxlength attribute on an input field .Setting the attribute to a negative or non-numeric value,allows view values of any length
ng-pattern Sets pattern validation error key if the ngModel value does not match the specified RegEx expression
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app>
<h1>Student Information:</h1>
<form name="studentForm" novalidate>
<label for="firstName">First Name:</label><br />
<input type="text" id="firstName" ng-model="student.firstName" ng-required="true" /><br />
<span ng-show="studentForm.firstName.$touched && studentForm.firstName.$error.required">First Name is Required.</span>

<label for="lastName">Last Name:</label><br />
<input type="text" name="lastName" ng-minlength="3" ng-maxlength="10" ng-model="student.lastName" />
<span ng-show="studentForm.lastName.$touched && studentForm.lastName.$error.minlength">min 3 chars.</span>
<span ng-show="studentForm.lastName.$touched && studentForm.lastName.$error.maxlength">Max 10 chars.</span><br /><br />

<input type="submit" value="submit" /><br />
</form>
</body>
</html>

State Properties

Angular包含一些返回form和输入控件状态的一些属性。

检查form状态:formName.propertyName

检查input状态:formName.inputFiledName.propertyName

Property Description
$error $error object contains all the validation attributes applied to the specified element
$pristine Returns true if the user has not interacted with control yeat else returns false
$valid Returns true if the model is valid
$invalid Returns true if the model is invalid
$dirty Returns true if user changed the value of model at least once
$touched Returns true if the user has tabbed out from the control
$untouched Returns true if the user has not tabbed out from the control
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-app>
<h1>Student Information:</h1>
<form name="studentForm">
<p>
FirstName Status:<br />

Pristine:{{studentForm.firstName.$pristine}}<br />
Touched:{{studentForm.firstName.$touched}}<br />
Untouched:{{studentForm.firstName.$untouched}}<br />
Valid:{{studentForm.firstName.$valid}}<br />
Invalid:{{studentForm.firstName.$invalid}}<br />
Dirty:{{studentForm.firstName.$dirty}}<br />
Error:{{studentForm.firstName.$error}}<br />
</p>
<label for="firstName">First Name:</label><br />
<input type="text" id="firstName" ng-model="student.firstName" ng-required="true" /><br />
<span ng-show="studentForm.firstName.$touched && studentForm.firstName.$error.required">First Name is Required.</span>

<label for="lastName">Last Name:</label><br />
<input type="text" name="lastName" ng-minlength="3" ng-maxlength="10" ng-model="student.lastName" />
<span ng-show="studentForm.lastName.$touched && studentForm.lastName.$error.minlength">min 3 chars.</span>
<span ng-show="studentForm.lastName.$touched && studentForm.lastName.$error.maxlength">Max 10 chars.</span><br /><br />

<input type="submit" value="submit" /><br />
</form>
</body>
</html>

Routing

使用AngularJS构建SPA(单页应用程序),单页应用程序是一个Web应用程序,可以加载单个HTML页面,并在用户与Web应用程序交互时动态更新页面。

AngularJS使用路由模块ngRoute支持SPA。此路由模块基于URL进行操作。当用户请求特定URL时,路由引擎会捕获该URL并根据定义的路由规则呈现视图。

Exception Handling

每个应用都需要适当的异常处理机制,你可以使用try…catch..finally来处理AngularJS模块中的异常。

AngularJS拥有内置的$exceptionHandler服务,该服务处理应用程序中未捕获的异常。

$exceptionHandler服务默认实现将异常信息记录到浏览器控制台中,你可以根据要求覆盖此服务。

$exceptionHandler不处理语法错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
<html lang="en" ng-app="myApp">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
</head>

<body ng-controller="myController">
Status:{{status}}<br />
Data:{{data}}<br />

<input type="button" value="Get Data" ng-click="GetData()" />
<script>
var app = angular.module("myApp", []);

app.config(function ($provide) {
$provide.decorator("$exceptionHandler", function ($delegate) {
return function (exception, cause) {
$delegate(exception, cause);

alert("Error occured! Please contract admin.")
}
})
})

app.controller("myController", function ($scope) {
var onSuccess = function (response) {
$scope.status = response.status;
$scope.data = response.data;
}

var onError = function (response) {
$scope.status = response.status;
$scope.data = response.data;
}

$scope.GetData = function () {
$http.get("/getdata").then(onSuccess, onError);
}
})
</script>
</body>
</html>
<!--
使用app.config()方法中的$provide.decorate()方法覆盖provide服务的默认行为。
decorate方法允许我们覆盖或者修改服务的行为。
-->
× 请我吃糖~
打赏二维码