Академический Документы
Профессиональный Документы
Культура Документы
API,
.
ng
html A,
href.
ngClick
, : <a href="" ngclick="model.$save()">Save</a>
,
, IE:
1. <a>
2. </a>
form
FormController.
name ,
, .
ngForm
angular . , ,
, .
<form> , angular
ngForm, , <form>,
.
CSS
ng-valid .
ng-invalid .
ng-pristine .
ng-dirty .
Angular ,
, .
JavaScript,
.
Angular ( )
<form> action.
, JavaScript,
:
ngSubmit
ngClick submit (input[type=submit])
,
ngSubmit ngClick. - html:
, enter ,
(ngSubmit).
2
submit, enter
input
submit, enter
input[type=submit] (ngClick) (ngSubmit)
, IE:
1. <form
2.
[name="{string}"]>
3. </form>
name(optional) {string=}
. ,
, .
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<form name="myForm" ng-controller="Ctrl">
9.
10.
11.
<tt>userType = {{userType}}</tt><br>
12.
13.
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
14.
15.
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
16.
17.
</form>
</body>
18. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.userType = 'guest';
3. }
expect(binding('userType')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
4. });
5.
6. it('should be invalid if empty', function() {
7. input('userType').enter('');
8.
9.
expect(binding('userType')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
10. });
input
, IE:
1. <input
2.
ngModel="{string}"
3.
[name="{string}"]
4.
5.
[required]
[ngRequired="{boolean}"]
6.
7.
[ngMinlength="{number}"]
[ngMaxlength="{number}"]
8.
[ngPattern="{string}"]
9.
[ngChange="{string}"]>
10. </input>
ngModel {string}
angular .
name(optional) {string=}
, .
required(optional) {string=}
required ,
.
ngRequired(optional) {boolean=}
required, true
ngMinlength(optional) {number=}
minlength , ,
.
ngMaxlength(optional) {number=}
maxlength , ,
.
ngPattern(optional) {string=}
pattern ,
RegExp. ,
/regexp/,
, .
ngChange(optional) {string=}
Angular , ,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
<script src="script.js"></script>
6.
7.
</head>
<body>
8.
9.
<div ng-controller="Ctrl">
<form name="myForm">
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
</form>
<hr>
21.
22.
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
23.
24.
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
25.
26.
<tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
27.
28.
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
29.
30.
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
31. </body>
32. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.user = {name: 'guest', last: 'visitor'};
3. }
expect(binding('myForm.userName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
5. });
6.
7. it('should be invalid if empty when required', function() {
8.
input('user.name').enter('');
9.
10.
expect(binding('user')).toEqual('{"last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('false');
11.
expect(binding('myForm.$valid')).toEqual('false');
12. });
13.
14. it('should be valid if empty when min length is set', function() {
15. input('user.last').enter('');
16.
17.
expect(binding('user')).toEqual('{"name":"guest","last":""}');
expect(binding('myForm.lastName.$valid')).toEqual('true');
18. expect(binding('myForm.$valid')).toEqual('true');
19. });
20.
21. it('should be invalid if less than required min length', function() {
22.
23.
input('user.last').enter('xx');
expect(binding('user')).toEqual('{"name":"guest"}');
24.
25.
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
26. expect(binding('myForm.$valid')).toEqual('false');
27. });
28.
29. it('should be invalid if longer than max length', function() {
30.
31.
32.
33.
.toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
34.
35.
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
expect(binding('myForm.$valid')).toEqual('false');
36. });
input [checkbox]
HTML .
1. <input type="checkbox"
2.
ng-model="{string}"
3.
4.
[name="{string}"]
[ng-true-value="{string}"]
5.
6.
[ng-false-value="{string}"]
[ng-change="{string}"]>
ngModel {string}
angular .
name(optional) {string=}
, .
ngTrueValue(optional) {string=}
, , .
ngFalseValue(optional) {string=}
, , .
ngChange(optional) {string=}
Angular , ,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<form name="myForm" ng-controller="Ctrl">
9.
10.
11.
12.
13.
14.
<tt>value2 = {{value2}}</tt><br/>
</form>
15. </body>
16. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.value1 = true;
3.
$scope.value2 = 'YES'
4. }
expect(binding('value1')).toEqual('true');
expect(binding('value2')).toEqual('YES');
4.
5.
input('value1').check();
6.
input('value2').check();
7.
expect(binding('value1')).toEqual('false');
8.
expect(binding('value2')).toEqual('NO');
9. });
input [email]
email . email
, email.
1. <input type="email"
2.
3.
ng-model="{string}"
[name="{string}"]
4.
5.
[required]
[ng-required="{string}"]
6.
7.
[ng-minlength="{number}"]
[ng-maxlength="{number}"]
8.
[ng-pattern="{string}"]>
ngModel {string}
angular .
name(optional) {string=}
, .
required(optional) {string=}
required ,
.
ngRequired(optional) {boolean=}
required, true
ngMinlength(optional) {number=}
minlength , ,
.
ngMaxlength(optional) {number=}
maxlength , ,
.
ngPattern(optional) {string=}
pattern ,
RegExp. ,
/regexp/,
, .
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
6.
7.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
8.
9.
10.
11.
12.
13.
14.
15.
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
16.
17.
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
18.
19.
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
20.
21.
</form>
</body>
22. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.text = 'me@example.com';
3. }
expect(binding('text')).toEqual('me@example.com');
expect(binding('myForm.input.$valid')).toEqual('true');
4. });
5.
6. it('should be invalid if empty', function() {
7.
input('text').enter('');
8.
expect(binding('text')).toEqual('');
9.
expect(binding('myForm.input.$valid')).toEqual('false');
10. });
11.
12. it('should be invalid if not email', function() {
13.
14.
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
15. });
input [number]
.
number , .
1. <input type="number"
2.
ng-model="{string}"
3.
4.
[name="{string}"]
[min="{string}"]
5.
6.
[max="{string}"]
[required]
7.
8.
[ng-required="{string}"]
[ng-minlength="{number}"]
9.
10.
[ng-maxlength="{number}"]
[ng-pattern="{string}"]
11.
[ng-change="{string}"]>
ngModel {string}
angular .
name(optional) {string=}
, .
min(optional) {string=}
min , min.
max(optional) {string=}
max , max.
required(optional) {string=}
required ,
.
ngRequired(optional) {boolean=}
required, true
ngMinlength(optional) {number=}
minlength , ,
.
ngMaxlength(optional) {number=}
maxlength , ,
.
ngPattern(optional) {string=}
pattern ,
RegExp. ,
/regexp/,
, .
ngChange(optional) {string=}
Angular , ,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
6.
7.
8.
9.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<form name="myForm" ng-controller="Ctrl">
Number: <input type="number" name="input" ng-model="value"
10.
11.
12.
13.
Required!</span>
<span class="error" ng-show="myForm.list.$error.number">
14.
15.
16.
17.
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
18.
19.
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
20.
21.
</form>
</body>
22. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.value = 12;
3. }
expect(binding('value')).toEqual('12');
expect(binding('myForm.input.$valid')).toEqual('true');
4. });
5.
6. it('should be invalid if empty', function() {
7. input('value').enter('');
8.
9.
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
10. });
11.
12. it('should be invalid if over max', function() {
13. input('value').enter('123');
14. expect(binding('value')).toEqual('');
15. expect(binding('myForm.input.$valid')).toEqual('false');
16. });
input [radio]
HTML .
1. <input type="radio"
2.
3.
ng-model="{string}"
value="{string}"
4.
5.
[name="{string}"]
[ng-change="{string}"]>
ngModel {string}
angular .
name(optional) {string=}
, .
value {string}
, , .
ngChange(optional) {string=}
Angular , ,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<form name="myForm" ng-controller="Ctrl">
9.
10.
11.
12.
13.
14.
</form>
</body>
15. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.color = 'blue';
3. }
expect(binding('color')).toEqual('blue');
4.
5.
input('color').select('red');
expect(binding('color')).toEqual('red');
6. });
input [text]
HTML angular.
1. <input type="text"
2.
ng-model="{string}"
3.
4.
[name="{string}"]
[required]
5.
6.
[ng-required="{string}"]
[ng-minlength="{number}"]
7.
8.
[ng-maxlength="{number}"]
[ng-pattern="{string}"]
9.
[ng-change="{string}"]>
ngModel {string}
angular .
name(optional) {string=}
, .
required(optional) {string=}
required ,
.
ngRequired(optional) {boolean=}
required, true
ngMinlength(optional) {number=}
minlength , ,
.
ngMaxlength(optional) {number=}
maxlength , ,
.
ngPattern(optional) {string=}
pattern ,
RegExp. ,
/regexp/,
, .
ngChange(optional) {string=}
Angular , ,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
6.
7.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
8.
9.
10.
11.
ng-pattern="word" required>
<span class="error" ng-show="myForm.input.$error.required">
12.
13.
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
14.
15.
16.
17.
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
18.
19.
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
20.
21.
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
22. </body>
23. </html>
Script.js
1. function Ctrl($scope) {
2.
3.
$scope.text = 'guest';
$scope.word = /^\w*$/;
4. }
input('text').enter('');
8.
9.
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
10. });
11.
12. it('should be invalid if multi word', function() {
13. input('text').enter('hello world');
14. expect(binding('myForm.input.$valid')).toEqual('false');
15. });
input [url]
URL. url
, URL.
1. <input type="url"
2.
ng-model="{string}"
3.
4.
[name="{string}"]
[required]
5.
6.
[ng-required="{string}"]
[ng-minlength="{number}"]
7.
8.
[ng-maxlength="{number}"]
[ng-pattern="{string}"]
9.
[ng-change="{string}"]>
ngModel {string}
angular .
name(optional) {string=}
, .
required(optional) {string=}
required ,
.
ngRequired(optional) {boolean=}
required, true
ngMinlength(optional) {number=}
minlength , ,
.
ngMaxlength(optional) {number=}
maxlength , ,
.
ngPattern(optional) {string=}
pattern ,
RegExp. ,
/regexp/,
, .
ngChange(optional) {string=}
Angular , ,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<form name="myForm" ng-controller="Ctrl">
9.
10.
11.
12.
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
13.
14.
15.
16.
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
17.
18.
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
19.
20.
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
21. </body>
22. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.text = 'http://google.com';
3. }
input('text').enter('');
expect(binding('text')).toEqual('');
9.
expect(binding('myForm.input.$valid')).toEqual('false');
10. });
11.
12. it('should be invalid if not url', function() {
13.
14.
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
15. });
ngApp
.
HTML. ,
.
, ngApp html,
{{ 1+2 }} 3.
ngApp .
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
6.
7.
<body>
I can add: 1 + 2 =
{{ 1+2 }}
8.
</body>
9. </html>
1. <ANY ng-app="{angular.Module}">
2.
...
3. </ANY>
ngApp {angular.Module} ,
.
ngBind
ngBind Angular,
, , .
, ngBind ,
, .
, .. ngBind,
{{ expression }} .
ngBind , ,
.
ngCloak .
1. <ANY ng-bind="{expression}">
2.
...
3. </ANY>
ngBind {expression} .
; , .
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
6.
7.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
8.
9.
<div ng-controller="Ctrl">
Enter name: <input type="text" ng-model="name"><br>
10.
11.
12. </body>
13. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.name = 'Whirled';
3. }
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
5. });
ngBindHtmlUnsafe
innerHTML expression
. innerHTML
! ,
ngBindHtml, .
. $sanitize .
1. <ANY ng-bind-html-unsafe="{expression}">
2.
...
3. </ANY>
ngBindHtmlUnsafe {expression} .
ngBindTemplate
ngBindTemplate ,
ngBindTemplate. ngBind, ngBindTemplate
{{ }} . ( ,
HTML SPAN, TITLE,
OPTION).
1. <ANY ng-bind-template="{string}">
2.
...
3. </ANY>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
6.
7.
8.
9.
10.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
11.
12.
</div>
13. </body>
14. </html>
Script.js
1. function Ctrl($scope) {
2.
3.
$scope.salutation = 'Hello';
$scope.name = 'World';
4. }
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
4.
5.
expect(using('.doc-example-live').binding('name')).
toBe('World');
6.
7.
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
8.
9.
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
10.
11.
expect(using('.doc-example-live').binding('name')).
toBe('user');
12. });
ngChange
, .
, .
, ngModel .
, IE:
1. <ng-change>
2. </ng-change>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
<script src="script.js"></script>
6.
7.
</head>
<body>
8.
9.
<div ng-controller="Controller">
<input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-chan
ge-example1" />
10.
<input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
11.
12.
13.
14.
counter = {{counter}}
</div>
15. </body>
16. </html>
Script.js
1. function Controller($scope) {
2.
3.
$scope.counter = 0;
$scope.change = function() {
4.
5.
};
$scope.counter++;
6. }
expect(binding('counter')).toEqual('0');
element('#ng-change-example1').click();
4.
5.
expect(binding('counter')).toEqual('1');
expect(binding('confirmed')).toEqual('true');
6. });
7.
8. it('should not evaluate the expression if changing from model', function() {
9.
element('#ng-change-example2').click();
10.
11.
expect(binding('counter')).toEqual('0');
expect(binding('confirmed')).toEqual('true');
12. });
ngChecked
HTML , checked.
( true, false). angular
. ngChecked.
1. <INPUT ng-checked="{expression}">
2.
...
3. </INPUT>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
6.
7.
<body>
Check me to check both: <input type="checkbox" ng-model="master"><br/>
8.
9.
10. </html>
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
5. });
ngClass
1. <ANY ng-class="{expression}">
2.
...
3. </ANY>
ngClass {expression} .
, , , ,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
6.
7.
<body>
<input type="button" value="set" ng-click="myVar='my-class'">
8.
9.
10.
11.
12. </html>
Style.css
1. .my-class {
2.
color: red;
3. }
toMatch(/my-class/);
5.
6.
using('.doc-example-live').element(':button:first').click();
7.
8.
expect(element('.doc-example-live span').prop('className')).
toMatch(/my-class/);
9.
10.
using('.doc-example-live').element(':button:last').click();
11.
12.
expect(element('.doc-example-live span').prop('className')).not().
13.
toMatch(/my-class/);
14. });
ngClassEven
1. <ANY ng-class-even="{expression}">
2.
...
3. </ANY>
ngClassEven {expression} .
, , .
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9.
10.
11.
12.
13.
14.
</span>
</li>
</ol>
</body>
15. </html>
Style.css
1. .odd {
2.
color: red;
3. }
4. .even {
5.
color: blue;
6. }
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
5.
toMatch(/even/);
6. });
ngClassOdd
4. <ANY ng-class-odd="{expression}">
5.
...
6. </ANY>
ngClassOdd {expression} .
, , .
Index.html
16. <!doctype html>
17. <html ng-app>
18. <head>
19.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
20.
</head>
21.
22.
<body>
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
23.
24.
25.
26.
27.
28.
</li>
</ol>
29. </body>
30. </html>
Style.css
7. .odd {
8.
color: red;
9. }
10. .even {
11. color: blue;
12. }
10.
11.
12. });
ngClick
ngClick , ,
.
1. <ANY ng-click="{expression}">
2.
...
3. </ANY>
2.
...
3. </ANY>
ngClick {expression} . (
$event)
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
6.
7.
<body>
<button ng-click="count = count + 1" ng-init="count=0">
8.
9.
10.
11.
Increment
</button>
count: {{count}}
</body>
12. </html>
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
5. });
ngCloak
ngCloak Angular
. ,
, html .
<body>,
, .
ngCloak css angular.js
angular.min.js. css :
css , html ( )
ng-cloak . Angular ,
, ngCloak,
.
angular.js head html
; , css
.
, IE7, ( CSS 2.1)
[ng\:cloak]. , css
ngCloak ngCloak, .
1. <ANY ng-cloak>
2.
...
3. </ANY>
1. <ANY class="ng-cloak">
2.
...
3. </ANY>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9.
</body>
10. </html>
expect(element('.doc-example-live #template1').attr('ng-cloak')).
not().toBeDefined();
4.
5.
expect(element('.doc-example-live #template2').attr('ng-cloak')).
not().toBeDefined();
6. });
ngController
ngController .
angular Model-View-Controller.
MVC angular:
Model , ;
DOM.
View (HTML ) .
Controller ngController ;
.
, ,
$route.
1. <ANY ng-controller="{expression}">
2.
...
3. </ANY>
ngController {expression}
, .
.
, , .
Angular . ,
this .
.
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="SettingsController">
9.
10.
11.
12.
Contact:
<ul>
13.
14.
15.
16.
<option>phone</option>
<option>email</option>
17.
18.
</select>
<input type="text" ng-model="contact.value"/>
19.
20.
21.
22.
</li>
<li>[ <a href="" ng-click="addContact()">add</a> ]</li>
23.
24.
</ul>
</div>
25. </body>
26. </html>
Script.js
1. function SettingsController($scope) {
2.
3.
4.
5.
6.
7.
$scope.greet = function() {
8.
9.
alert(this.name);
};
10.
11.
$scope.addContact = function() {
12.
13.
this.contacts.push({type:'email', value:'yourname@example.org'});
};
14.
15.
$scope.removeContact = function(contactToRemove) {
16.
17.
18.
19.
};
20.
21.
$scope.clearContact = function(contact) {
contact.type = 'phone';
22.
23.
contact.value = '';
};
24. }
4.
5.
6.
7.
.toBe('john.smith@example.org');
8.
9.
10.
11.
12.
13.
14. });
ngCsp
1. <html ng-csp>
2.
...
3. </html>
1. <html class="ng-csp">
2.
...
3. </html>
1000.
ngDblclick
ngDblclick
dblclick.
1. <ANY ng-dblclick="{expression}">
2.
...
3. </ANY>
. ngClick
ngDisabled
HTML ,
disabled. ( true, false) angular
. ,
ngDisabled.
1. <INPUT ng-disabled="{expression}">
2.
...
3. </INPUT>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9.
</body>
10. </html>
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
5. });
ngForm
, IE:
1. <ng-form
2.
[ngForm="{string}"]>
3. </ng-form>
1. <ANY ng-form
2.
[name="{string}"]>
3.
...
4. </ANY>
2.
...
3. </ANY>
name|ngForm(optional) {string=} . ,
,
.
ngHide
1. <ANY ng-hide="{expression}">
2.
...
3. </ANY>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
6.
7.
<body>
Click me: <input type="checkbox" ng-model="checked"><br/>
8.
9.
10.
11. </html>
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
4.
5.
input('checked').check();
6.
7.
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
8.
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
9. });
ngHref
href Angular
URL, , angular
( ), 404 .
ngHref .
:
1. <a href="http://www.gravatar.com/avatar/{{hash}}"/>
1. <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
1. <A ng-href="{template}">
2.
...
3. </A>
link href:
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
</head>
6.
<body>
7.
8.
9.
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br
/>
10.
11.
12.
13.
14. </body>
15. </html>
element('#link-1').click();
expect(input('value').val()).toEqual('1');
4.
expect(element('#link-1').attr('href')).toBe("");
5. });
6.
7. it('should execute ng-click but not reload when href empty string', function() {
8.
9.
element('#link-2').click();
expect(input('value').val()).toEqual('2');
10. expect(element('#link-2').attr('href')).toBe("");
11. });
12.
13. it('should execute ng-click and change url when ng-href specified', function() {
14.
15.
expect(element('#link-3').attr('href')).toBe("/123");
16.
17.
element('#link-3').click();
expect(browser().window().path()).toEqual('/123');
18. });
19.
20. it('should execute ng-click but not reload when href empty string and name specifi
ed', function() {
21.
22.
element('#link-4').click();
expect(input('value').val()).toEqual('4');
23. expect(element('#link-4').attr('href')).toBe('');
24. });
25.
26. it('should execute ng-click but not reload when no href but name specified', funct
ion() {
27. element('#link-5').click();
28.
29.
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe(undefined);
30. });
31.
32. it('should only change url when only ng-href', function() {
33. input('value').enter('6');
34.
35.
expect(element('#link-6').attr('href')).toBe('6');
36.
element('#link-6').click();
37.
expect(browser().location().url()).toEqual('/6');
38. });
ngInclude
, HTML .
(Same Origin Policy)
( , ngInclude -
file://).
, IE:
1. <ng-include
2.
src="{string}"
3.
[onload="{string}"]
4.
[autoscroll="{string}"]>
5. </ng-include>
1. <ANY ng-include="{string}"
2.
[onload="{string}"]
3.
[autoscroll="{string}"]>
4.
...
5. </ANY>
onload(optional) {string=} , ,
.
, .
, .
,
true.
$includeContentLoaded
ngInclude.
:
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="Ctrl">
9.
10.
11.
12.
</select>
url of the template: <tt>{{template.url}}</tt>
13.
14.
<hr/>
<div ng-include src="template.url"></div>
15.
16.
</div>
</body>
17. </html>
Template1.html
1. Content of template1.html
Template2.html
1. Content of template2.html
Script.js
1. function Ctrl($scope) {
2.
$scope.templates =
3.
4.
5.
6. }
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template2.html/);
9. });
10. it('should change to blank', function() {
11. select('template').option('');
12. expect(element('.doc-example-live [ng-include]').text()).toEqual('');
13. });
ngInit
ngInit
.
1. <ANY ng-init="{expression}">
2.
...
3. </ANY>
ngInit {expression} .
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9.
10.
</div>
</body>
11. </html>
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
4. });
ngList
, , .
1. <input ng-list="{string}">
2.
...
3. </input>
ngList(optional) {string=} ,
. /something/,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<form name="myForm" ng-controller="Ctrl">
9.
10.
11.
12.
Required!</span>
<tt>names = {{names}}</tt><br/>
13.
14.
<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
<tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
15.
16.
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
17.
18.
</form>
</body>
19. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.names = ['igor', 'misko', 'vojta'];
3. }
expect(binding('names')).toEqual('["igor","misko","vojta"]');
expect(binding('myForm.namesInput.$valid')).toEqual('true');
4. });
5.
6. it('should be invalid if empty', function() {
7.
input('names').enter('');
8.
9.
expect(binding('names')).toEqual('[]');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
10. });
ngModel
Angular, .
input, select, textarea.
, ngModel.
ngModel :
,
input, textarea select,
(, required, number, email, url),
(valid/invalid, dirty/pristine, validation errors),
css (ng-valid, ng-invalid, ng-dirty, ngpristine),
form.
ngModel, :
input
text
checkbox
radio
number
email
url
select
textarea
1. <input ng-model>
2.
...
3. </input>
1. <input class="ng-model">
2.
...
3. </input>
ngMousedown
ngMousedown ,
mousedown ( ).
1. <ANY ng-mousedown="{expression}">
2.
...
3. </ANY>
ngMousedown {expression}
mousedown. ( $event)
ngClick
ngMouseenter
mouseenter ( ).
1. <ANY ng-mouseenter="{expression}">
2.
...
3. </ANY>
ngClick
ngMouseleave
mouseleave ( ).
1. <ANY ng-mouseleave="{expression}">
2.
...
3. </ANY>
ngClick
ngMousemove
mousemove ( ).
1. <ANY ng-mousemove="{expression}">
2.
...
3. </ANY>
ngClick
ngMouseover
mouseover ( ).
1. <ANY ng-mouseover="{expression}">
2.
...
3. </ANY>
ngClick
ngMouseup
mouseup.
1. <ANY ng-mouseup="{expression}">
2.
...
3. </ANY>
ngClick
ngMultiple
HTML ,
multiple. ( true, false)
angular .
ngMultiple.
1. <SELECT ng-multiple="{expression}">
2.
...
3. </SELECT>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9.
10.
<option>Misko</option>
<option>Igor</option>
11.
12.
<option>Vojta</option>
<option>Di</option>
13.
14.
</select>
</body>
15. </html>
input('checked').check();
expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
5. });
ngNonBindable
, angular,
, . ngNonBindable
angular HTML.
1. <ANY ng-non-bindable>
2.
...
3. </ANY>
1. <ANY class="ng-non-bindable">
2.
...
3. </ANY>
1000.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
6.
7.
<body>
<div>Normal: {{1 + 2}}</div>
8.
9.
10. </html>
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
5. });
ngPluralize
ngPluralize
en-US. angular.js
( Angular i18n ). ngPluralize
,
.
ngPluralize
Angular,
when .
JSON, Angular .
ngPluralize:
1. <ng-pluralize count="personCount"
2.
when="{'0': 'Nobody is viewing.',
3.
4.
5. </ng-pluralize>
ngPluralize offset
offset .
, "4 people are viewing this document",
"John, Kate and 2 others are viewing this document". offset
. :
6.
ewing.'}">
7. </ng-pluralize>
(one, other),
0, 1 2. , John, ,
"John is viewing". , ,
2 3, Angular 1 ,
. 'one'
"John, Marry and one other person are viewing".
, , 0
. , , 3,
0, 1, 2 3. "one" "other".
, IE:
1. <ng-pluralize
2.
count="{string|expression}"
3.
when="{string}"
4.
[offset="{number}"]>
5. </ng-pluralize>
1. <ANY ng-pluralize
2.
count="{string|expression}"
3.
when="{string}"
4.
5.
[offset="{number}"]>
...
6. </ANY>
count {string|expression} .
when {string} ,
.
offset(optional) {number=} .
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
6.
7.
8.
9.
10.
11.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
12.
13.
14.
15.
Without Offset:
<ng-pluralize count="personCount"
16.
17.
18.
19.
20.
21.
22.
23.
With Offset(2):
<ng-pluralize count="personCount" offset=2
24.
25.
26.
27.
28.
29.
30.
31.
</div>
</body>
32. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.person1 = 'Igor';
3.
4.
$scope.person2 = 'Misko';
$scope.personCount = 1;
5. }
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('1 person is viewing.');
4.
5.
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor is viewing.');
6.
7.
using('.doc-example-live').input('personCount').enter('0');
8.
9.
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('Nobody is viewing.');
10.
11.
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Nobody is viewing.');
12.
13.
using('.doc-example-live').input('personCount').enter('2');
14.
15.
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('2 people are viewing.');
16.
expect(element('.doc-example-live ng-pluralize:last').text()).
17.
18.
19.
20.
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).
21.
22.
23.
24.
25.
26.
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).
27.
28.
29.
30. });
31.
32. it('should show data-binded names', function() {
33.
34.
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:last').text()).
35.
36.
37.
38.
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
39.
40.
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
41. });
ngReadonly
HTML , ,
readonly. ( , true, , ,
false) angular
. ngReadonly.
1. <INPUT ng-readonly
2.
expression="{string}">
3.
...
4. </INPUT>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
6.
7.
<body>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/
>
8.
9.
</body>
10. </html>
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
input('checked').check();
4.
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
5. });
ngRepeat
ngRepeat .
, ,
, $index
.
,
, :
1. <ANY ng-repeat="{repeat_expression}">
2.
...
3. </ANY>
3. </ANY>
.
1000.
ngRepeat {repeat_expression} ,
. :
,
ngRepeat:
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9.
10.
11.
12.
13.
14.
15. </body>
16. </html>
expect(r.row(0)).toEqual(["1","John","25"]);
5.
expect(r.row(1)).toEqual(["2","Mary","28"]);
6. });
ngSelected
HTML ,
selected. ( , , true, - false)
angular .
ngSelected.
1. <OPTION ng-selected
2.
expression="{string}">
3.
...
4. </OPTION>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
6.
7.
<body>
Check me to select: <input type="checkbox" ng-model="selected"><br/>
8.
9.
<select>
<option>Hello!</option>
10.
11.
12. </body>
13. </html>
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('selected').check();
4.
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
5. });
ngShow
1. <ANY ng-show="{expression}">
2.
...
3. </ANY>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
6.
7.
<body>
Click me: <input type="checkbox" ng-model="checked"><br/>
8.
9.
10.
11. </html>
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
5.
6.
input('checked').check();
7.
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
8.
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
9. });
ngSrc
1. <img src="http://www.gravatar.com/avatar/{{hash}}"/>
1. <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
1. <IMG ng-src="{template}">
2.
...
3. </IMG>
ngStyle
1. <ANY ng-style="{expression}">
2.
...
3. </ANY>
ngStyle {expression} ,
CSS,
CSS.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9.
10.
<br/>
<span ng-style="myStyle">Sample Text</span>
11.
12.
<pre>myStyle={{myStyle}}</pre>
</body>
13. </html>
Style.css
1. span {
2.
color: black;
3. }
element('.doc-example-live :button[value=set]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
5.
6.
element('.doc-example-live :button[value=clear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
7. });
ngSubmit
angular onsubmit ( ).
(
).
1. <form ng-submit="{expression}">
2.
...
3. </form>
ngSubmit {expression} .
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
6.
7.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
8.
9.
10.
11.
12.
13.
<pre>list={{list}}</pre>
</form>
14. </body>
15. </html>
Script.js
1. function Ctrl($scope) {
2.
3.
$scope.list = [];
$scope.text = 'hello';
4.
5.
$scope.submit = function() {
if (this.text) {
6.
7.
8.
9.
10. }
this.list.push(this.text);
this.text = '';
}
};
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
4.
5.
expect(binding('list')).toBe('["hello"]');
expect(input('text').val()).toBe('');
6. });
7. it('should ignore empty strings', function() {
8.
9.
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
10.
11.
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
12. });
ngSwitch
DOM.
, IE:
<ANY ng-switch="expression">
<ANY ng-switch-when="matchValue1">...</ANY>
<ANY ng-switch-when="matchValue2">...</ANY>
...
<ANY ng-switch-default>...</ANY>
</ANY>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
6.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
7.
<body>
8.
<div ng-controller="Ctrl">
9.
10.
11.
12.
<tt>selection={{selection}}</tt>
<hr/>
13.
14.
15.
16.
17.
18.
</div>
</div>
19. </body>
20. </html>
Script.js
1. function Ctrl($scope) {
2.
3.
4. }
ngTransclude
DOM .
1. <ANY ng-transclude>
2.
...
3. </ANY>
1. <ANY class="ng-transclude">
2.
...
3. </ANY>
Index.html
1. <!doctype html>
2. <html ng-app="transclude">
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="Ctrl">
9.
10.
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
11.
12.
<pane title="{{title}}">{{text}}</pane>
</div>
13. </body>
14. </html>
Script.js
1. function Ctrl($scope) {
2.
3.
4. }
5.
6. angular.module('transclude', [])
7. .directive('pane', function(){
8.
9.
return {
restrict: 'E',
10.
11.
transclude: true,
scope: 'isolate',
12.
13.
locals: { title:'bind' },
template: '<div style="border: 1px solid black;">' +
14.
15.
16.
17.
18. });
2.
input('title').enter('TITLE');
3.
input('text').enter('TEXT');
4.
5.
expect(binding('title')).toEqual('TITLE');
expect(binding('text')).toEqual('TEXT');
6. });
ngView
ngView $route,
(index.html). , ,
, $route.
, IE:
1. <ng-view>
2. </ng-view>
1. <ANY ng-view>
2.
...
3. </ANY>
1. <ANY class="ng-view">
2.
...
3. </ANY>
$viewContentLoaded
, ngView .
:
: ngView
Index.html
1. <!doctype html>
2. <html ng-app="ngView">
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="MainCntl">
9.
10.
Choose:
<a href="Book/Moby">Moby</a> |
11.
12.
13.
14.
15.
16.
<div ng-view></div>
17.
18.
<hr />
19.
20.
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
21.
22.
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
23.
24.
<pre>$routeParams = {{$routeParams}}</pre>
</div>
25. </body>
26. </html>
Book.html
1. controller: {{name}}<br />
2. Book Id: {{params.bookId}}<br />
Chapter.html
1. controller: {{name}}<br />
2. Book Id: {{params.bookId}}<br />
3. Chapter Id: {{params.chapterId}}
Script.js
1. angular.module('ngView', [], function($routeProvider, $locationProvider) {
2.
3.
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
4.
5.
controller: BookCntl
});
6.
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
7.
templateUrl: 'chapter.html',
8.
9.
controller: ChapterCntl
});
10.
11.
12. $locationProvider.html5Mode(true);
13. });
14.
15. function MainCntl($scope, $route, $routeParams, $location) {
16.
17.
$scope.$route = $route;
$scope.$location = $location;
$scope.name = "BookCntl";
$scope.params = $routeParams;
24. }
25.
26. function ChapterCntl($scope, $routeParams) {
27. $scope.name = "ChapterCntl";
28. $scope.params = $routeParams;
29. }
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
4.
5.
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
6.
7.
8.
9.
element('a:contains("Scarlet")').click();
content = element('.doc-example-live [ng-view]').text();
10.
11.
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
12. });
script
script, text/ng-template,
$templateCache, ngInclude, ngView
.
, IE:
1. <script
2.
type="text/ng-template">
3. </script>
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
6.
7.
<body>
<script type="text/ng-template" id="/tpl.html">
8.
9.
10. </html>
select
ngOptions
ngOptions
<option> <select> ,
ngOptions . select ,
,
ngModel selected.
, <option>,
, <select>.
null "not selected". .
: ngOptions <option>
ngRepeat select
. , option
.
, IE:
1. <select
2.
ngModel="{string}"
3.
[name="{string}"]
4.
5.
[required]
[ngRequired="{string}"]
6.
[ngOptions="{comprehension_expression}"]>
7. </select>
name(optional) {string=} ,
.
required(optional) {string=}
, .
ngOptions(optional) {comprehension_expression=}
:
- :
label for value in array
select as label for value in array
label group by group for value in array
select as label group by group for value in array
- :
label for (key , value) in object
select as label for (key , value) in object
label group by group for (key, value) in object
select as label group by group for (key, value) in object
array / object: , / .
value: ,
array object .
key: ,
object .
label: ,
<option>.
value (, value.propertyName).
select: ,
<select> . ,
select value.
group: ,
option DOM <optgroup>.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="MyCntrl">
9.
10.
<ul>
<li ng-repeat="color in colors">
11.
12.
13.
14.
</li>
<li>
15.
16.
17.
18.
</ul>
<hr/>
19.
20.
21.
22.
23.
24.
<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
25.
26.
27.
28.
</span><br/>
29.
30.
31.
</select><br/>
32.
33.
34.
35.
36.
37.
38.
39.
ng-style="{'background-color':color.name}">
</div>
40.
41.
</div>
</body>
42. </html>
Script.js
1. function MyCntrl($scope) {
2.
$scope.colors = [
3.
{name:'black', shade:'dark'},
4.
5.
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
6.
7.
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
8.
9.
];
$scope.color = $scope.colors[2]; // red
10. }
select('color').option('0');
expect(binding('{selected_color:color}')).toMatch('black');
5.
6.
using('.nullable').select('color').option('');
expect(binding('{selected_color:color}')).toMatch('null');
7. });
textarea
, IE:
1. <textarea
2.
ngModel="{string}"
3.
4.
[name="{string}"]
[required]
5.
6.
[ngRequired="{string}"]
[ngMinlength="{number}"]
7.
8.
[ngMaxlength="{number}"]
[ngPattern="{string}"]
9.
[ngChange="{string}"]>
10. </textarea>
Parameters
ngRequired(optional) {string=}
required required , ngRequired
true. ngRequired required
required.
currency
($1,234.56). ,
, .
HTML
{{ currency_expression | currency[:symbol] }}
JavaScript
$filter('currency')(amount[, symbol])
amount {number} .
symbol(optional) {string=} .
{string} .
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
<body>
8.
<div ng-controller="Ctrl">
9.
10.
11.
12.
13.
</div>
</body>
14. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.amount = 1234.56;
3. }
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
4. });
5. it('should update', function() {
6.
7.
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
8.
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
9. });
date
.
:
'ss': (00-59)
's': (0-59)
'a': am/pm 12- .
'Z': 4 ( ), ( ) (-1200+1200)
.
(, "h 'in the morning'").
, (, "h
o''clock").
HTML
{{ date_expression | date[:format] }}
JavaScript
$filter('date')(date[, format])
format(optional) {string=} ( ).
, mediumDate.
{string} ,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9.
10.
11.
12.
13. </body>
14. </html>
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
4.
5.
6.
7.
8. });
filter
.
: Array Angular.
ng.$filter Angular .
HTML
{{ filter_expression | filter:expression }}
JavaScript
$filter('filter')(array, expression)
array {Array} .
expression {string|Object|function()}
.
:
: ,
.
,
. , !.
: -,
. , {name:"M", phone:"1"}
, name "M"
phone "1". $ (
{$:"text"})
. ,
.
:
. .
,
true.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9.
10.
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
11.
12.
{name:'Julie', phone:'555-8765'}]"></div>
13.
14.
15.
16.
17.
18.
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
19.
20.
</tr>
</table>
21.
22.
<hr>
Any: <input ng-model="search.$"> <br>
23.
24.
25.
26.
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
27.
28.
29.
30.
<td>{{friend.phone}}</td>
</tr>
31.
32.
</table>
</body>
33. </html>
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.nam
e')).
toEqual(['Mary', 'Mike', 'Adam']);
4.
5.
6.
input('searchText').enter('76');
7.
8.
toEqual(['John', 'Julie']);
9. });
10.
11. it('should search in specific fields when filtering with a predicate object', func
12.
13.
tion() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name
')).
14.
toEqual(['Mary', 'Mike', 'Julie']);
15. });
json
JavaScript JSON.
.
JSON.
HTML
{{ json_expression | json }}
JavaScript
$filter('json')(object)
{string} JSON.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9. </html>
"name": ?"value"\n}/);
3. });
limitTo
.
,
( ) limit.
: Array Angular.
ng.$filter Angular.
1. filter:limitTo(array, limit);
array {Array} .
limit {string|Number} .
limit , .
. limit ,
.
{Array} , ,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
5.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
6.
</head>
7.
<body>
8.
9.
<div ng-controller="Ctrl">
Limit {{numbers}} to: <input type="integer" ng-model="limit">
10.
11.
12. </body>
13. </html>
Script.js
1. function Ctrl($scope) {
2.
3.
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.limit = 3;
4. }
expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3');
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
4. });
5.
6. it('should update the output when -3 is entered', function() {
7.
input('limit').enter(-3);
8.
expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
9. });
10.
11. it('should not exceed the maximum size of input array', function() {
12.
13.
input('limit').enter(100);
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]');
14. });
lowercase
HTML
{{ lowercase_expression | lowercase }}
JavaScript
$filter('lowercase')()
number
.
, .
HTML
{{ number_expression | number[:fractionSize] }}
JavaScript
$filter('number')(number[, fractionSize])
number {number|string} .
fractionSize(optional=2) {(number|string)=}
.
{string} ,
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="Ctrl">
9.
10.
11.
12.
13.
14.
</div>
</body>
15. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.val = 1234.56789;
3. }
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
4.
expect(binding('-val | number:4')).toBe('-1,234.5679');
5. });
6.
7. it('should update', function() {
8.
9.
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
10.
11.
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
12. });
orderBy
.
: Array Angular .
ng.$filter Angular.
array {Array}
expression {function(*)|string|Array.<(function(*)|string)>} ,
.
:
: .
<, =, >.
: , ,
'name' 'name'. +
(, +name -name).
: .
, ,
, ..
reverse(optional) {boolean=} .
{Array} .
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="Ctrl">
9.
10.
11.
12.
13.
14.
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
15.
16.
17.
mber</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></t
h>
18.
</tr>
19.
20.
21.
22.
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
23.
24.
25.
26.
</tr>
</table>
</div>
</body>
27. </html>
Script.js
1. function Ctrl($scope) {
2.
3.
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
4.
5.
6.
7.
8.
$scope.predicate = '-age';
9. }
expect(binding('predicate')).toBe('-age');
3.
4.
5.
6.
7. });
8.
9. it('should reorder the table when user selects different predicate', function() {
10. element('.doc-example-live a:contains("Name")').click();
11.
12.
13.
14.
15.
16.
element('.doc-example-live a:contains("Phone")').click();
17.
18.
19.
20.
21. });
uppercase
HTML
{{ uppercase_expression | uppercase }}
JavaScript
$filter('uppercase')()
$anchorScroll
, $location.hash()
, Html5.
$location.hash()
.
$anchorScrollProvider.disableAutoScrolling().
$window
$location
$rootScope
1. $anchorScroll();
$cacheFactory
1. $cacheFactory(cacheId[, options]);
cacheId {string} .
options(optional) {object=} ,
. :
{object} :
{object} info() , .
{void} put({string} key, {*} value) - .
{{*}} get({string} key) undefined
.
{void} remove({string} key) - .
{void} removeAll() , -.
{void} destroy() $cacheFactory.
$compile
HTML DOM ,
.
DOM DOM
.
, .
, ,
,
DOM.
Index.html
1. <!doctype html>
2. <html ng-app="compile">
3.
<head>
4.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="Ctrl">
9.
10.
11.
12.
<div compile="html"></div>
</div>
13. </body>
14. </html>
Script.js
1. // $compileProvider
2. angular.module('compile', [], function($compileProvider) {
3.
// 'compile',
4.
5.
// . '$compile'
$compileProvider.directive('compile', function($compile) {
//
return function(scope, element, attrs) {
6.
7.
8.
9.
scope.$watch(
function(scope) {
// 'compile'
return scope.$eval(attrs.compile);
10.
11.
12.
13.
},
function(value) {
14.
15.
// 'compile'
// DOM
16.
17.
element.html(value);
18.
19.
// DOM
// .
// : .childNodes
//
20.
21.
22.
23.
$compile(element.contents())(scope);
}
24.
25.
);
};
26. })
27. });
28.
29. function Ctrl($scope) {
30.
31.
32. }
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');
4.
expect(element('div[compile]').text()).toBe('Angular!');
5. });
maxPriority {number} (
, )
{function(scope[, cloneAttachFn])} ,
. ( DOM ) . :
scope - .
cloneAttachFn - cloneAttachFn ,
cloneAttachFn
DOM .
cloneAttachFn :
cloneAttachFn(clonedElement, scope) :
clonedElement .
scope .
.
, , cloneAttachFn.
, $digest,
Angular .
, :
, ()
DOM .
1. var element = $compile('<p>{{total}}</p>')(scope);
,
.
cloneAttachFn:
1. var templateHTML = angular.element('<p>{{total}}</p>'),
2.
scope = ....;
3.
4. var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scop
e) {
5.
// DOM ,
6. });
7.
8. // DOM `clone`
, HTML Angular
.
$controller
$controller .
$injector, ,
BC .
$injector
1. $controller(constructor, locals);
Parameters
constructor {Function|string} ,
. , ,
, :
,
$controllerProvider
, ,
window[constructor] window
locals {Object} .
{Object} .
$document
$window
$exceptionHandler
angular .
$log.error,
.
, angular-mocks.js, mock
$exceptionHandler .
$log
1. $exceptionHandler(exception[, cause]);
exception {Error} , .
cause(optional) {string=}
.
$filter
.
:
{{ expression [| filter_name[:parameter_value] ... ] }}
1. $filter(name);
name {String}
{Function}
$http
$http Angular,
HTTP XMLHttpRequest JSONP.
$http, $httpBackend
mock.
, $resource.
$http API deferred/promise APIs $q.
API ,
, ,
.
$http ,
HTTP , promise $http
: success error.
//
//
}).
error(function(data, status, headers, config) {
// ,
//
});
$http promise,
then ,
. API
.
200 299 ,
success. ,
, XMLHttpRequest ,
error .
1. $http.get('/someUrl').success(successCallback);
2. $http.post('/someUrl', data).success(successCallback);
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
HTTP
$http HTTP .
$httpProvider.defaults.headers, :
$httpProvider.defaults.headers.common ( ):
Accept: application/json, text/plain, * / *
X-Requested-With: XMLHttpRequest
$httpProvider.defaults.headers.post: ( POST )
Content-Type: application/json
$httpProvider.defaults.headers.put ( PUT )
Content-Type: application/json
,
. HTTP ,
POST PUT, HTTP
, , $httpProvider.defaults.headers.get['MyHeader']='value'.
,
$http.defaults , .
, .
, Angular :
:
data , JSON.
XSRF, ( ).
JSON, JSON.
,
$httpProvider.defaults.transformRequest
$httpProvider.defaults.transformResponse.
, push
unshift .
,
, .
, /,
$http transformRequest / transformResponse
.
, cache true.
, $http .
.
, , ,
.
GET URL , ,
, .
return function(promise) {
return promise.then(function(response) {
// -
}, function(response) {
5.
6.
// -
if (canRecover(response)) {
7.
8.
9.
10.
return responseOrNewPromise
}
11.
12.
return $q.reject(response);
});
13. }
14. });
15.
16. $httpProvider.responseInterceptors.push('myHttpInterceptor');
17.
18.
19. //
20. $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
21.
22.
return function(promise) {
// -
23. }
24. });
-, :
JSON
XSRF
, , . Angular
, ,
.
JSON
JSON - URL JSON,
JSONP . ,
")]}',\n" JSON. Angular
JSON.
, :
1. ['one','two']
, :
1. )]}',
2. ['one','two']
Angular , JSON.
,
JavaScript XSRF-TOKEN HTTP GET .
XHR , HTTP
X-XSRF-TOKEN, .
( ,
JavaScript ).
.
$httpBackend
$browser
$cacheFactory
$rootScope
$q
$injector
1. $http(config);
config {object} .
:
data {string|Object}
.
status {number} HTTP .
headers {function([headerName])} .
config {Object} ,
.
delete(url, config)
DELETE.
:
config(optional) {Object=}
:
{HttpPromise}
get(url, config)
GET.
:
config(optional) {Object=}
:
{HttpPromise}
head(url, config)
HEAD.
:
config(optional) {Object=}
:
{HttpPromise}
jsonp(url, config)
JSONP.
:
config(optional) {Object=}
:
{HttpPromise}
POST.
:
data {*}
config(optional) {Object=}
PUT.
:
data {*}
config(optional) {Object=}
{HttpPromise}
Properties
defaults
$httpProvider.defaults.
.
" HTTP " " ".
pendingRequests
.
.
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="FetchCtrl">
9.
10.
<select ng-model="method">
<option>GET</option>
11.
12.
<option>JSONP</option>
</select>
13.
14.
15.
16.
17.
ack=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&cal
18.
lback=JSON_CALLBACK')">Invalid JSONP</button>
<pre>http status code: {{status}}</pre>
19.
20.
21.
</div>
</body>
22. </html>
http-hello.html
1. Hello, $http!
Script.js
1. function FetchCtrl($scope, $http, $templateCache) {
2.
3.
$scope.method = 'GET';
$scope.url = 'http-hello.html';
4.
5.
$scope.fetch = function() {
6.
7.
$scope.code = null;
$scope.response = null;
8.
9.
10.
11.
success(function(data, status) {
$scope.status = status;
12.
13.
$scope.data = data;
}).
14.
15.
error(function(data, status) {
$scope.data = data || "Request failed";
16.
17.
$scope.status = status;
});
18.
19.
};
20.
21.
22.
23.
$scope.url = url;
};
24. }
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
5.
expect(binding('data')).toMatch(/Hello, \$http!/);
6. });
7.
8. it('should make a JSONP request to angularjs.org', function() {
9.
10.
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
11.
12.
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
13. });
14.
15. it('should make JSONP request to invalid URL and invoke the error handler',
16.
function() {
17.
18.
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
19.
20.
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
21. });
$httpBackend
HTTP backend
XMLHttpRequest JSONP .
,
: $http $resource.
mock
.
$httpBackend
$browser
$window
$document
$interpolate
.
HTML $compile . $interpolateProvider
.
var $interpolate = ...; // injected
var exp = $interpolate('Hello {{name}}!');
expect(exp({name:'Angular'}).toEqual('Hello Angular!');
$parse
1. $interpolate(text[, mustHaveExpression]);
text {string} .
{function(context)} ,
. :
context: , .
endSymbol()
, . }}.
$interpolateProvider#endSymbol .
:
{string} .
startSymbol()
, . {{.
$interpolateProvider#startSymbol .
:
{string} .
$locale
$locale Angular.
api:
id {string} (, en-us)
$location
$location:
URL ,
URL.
URL.
URL ,
( ).
.
URL (protocol, host, port, path, search,
hash).
Angular: $location
$browser
$sniffer
$rootElement
absUrl()
.
url
RFC 3986.
:
{string} url
hash(hash)
.
.
, $location.
:
hash(optional) {string=}
{string}
host()
.
url.
:
{string} url.
path(path)
.
url .
, , $location.
: (/),
, .
:
path(optional) {string=}
:
{string}
port()
, url.
:
{Number}
protocol()
url.
:
{string} url
replace()
, $location $digest
, .
search(search, paramValue)
.
( ) url .
, $location.
:
search(optional) {string|object<string,string>=} ,
:
{string}
url(url)
url.
url (, /path?a=b#hash) .
, ,
$location.
:
url(optional) {string=} url
(, /path?a=b#hash)
:
{string} url
$log
.
( ).
.
$window
error()
info()
log()
warn()
Index.html
1. <!doctype html>
2. <html ng-app>
3.
<head>
4.
5.
6.
7.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
8.
9.
<div ng-controller="LogCtrl">
<p>Reload this page with open console, enter text and hit the log button...<
/p>
10.
Message:
11.
12.
13.
<button ng-click="$log.warn(message)">warn</button>
14.
<button ng-click="$log.info(message)">info</button>
15.
<button ng-click="$log.error(message)">error</button>
16.
17.
</div>
</body>
18. </html>
Script.js
1. function LogCtrl($scope, $log) {
2.
$scope.$log = $log;
3.
$scope.message = 'Hello World!';
4. }
$parse
Angular .
1. var getter = $parse('user.name');
2. var setter = getter.assign;
3. var context = {user:{name:'angular'}};
4. var locals = {user:{name:'local'}};
5.
6. expect(getter(context)).toEqual('angular');
7. setter(context, 'newValue');
8. expect(context.user.name).toEqual('newValue');
9. expect(getter(context, locals)).toEqual('local');
1. $parse(expression);
expression {string} .
{function(context, locals)} ,
:
context {object} ,
( ).
locals {object=} ,
context.
assign, ,
.
$q
promise/deferred , Kris
Kowal's Q.
7.
8.
setTimeout(function() {
// ,
// $apply .
scope.$apply(function() {
9.
10.
11.
12.
if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');
13.
14.
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
15.
16.
17.
18.
}
});
}, 1000);
, .
promise deferred API.
promise api ,
(CPS) .
Q ,
promise.
Deferred API
deferred $q.defer().
deferred Promise
.
Promise API
promise
deferred.promise.
promise
(deferred) , .
promise
then promise,
promise:
1. promiseB = promiseA.then(function(result) {
2.
return result + 1;
3. });
4.
5. // promiseB promiseA
6. // promiseA 1
promise
promise ( ), /
promise . api
$http.
Q $q
:
$q ng.$rootScope.Scope
, ,
,
.
$q promise angular, ,
promise , , .
Q , $q, . $q ,
.
4.
5.
var resolvedValue;
6.
7.
8.
9.
// promise
10.
11.
deferred.resolve(123);
// , 'then' .
12.
13.
// , promise API ,
// .
14.
15.
expect(resolvedValue).toBeUndefined();
16.
17.
18. expect(resolvedValue).toEqual(123);
19. });
$rootScope
all(promises)
{Promise} promise,
, promise ,
promises. promise , promise
.
defer()
Deferred , .
:
{Deferred}
deferred.
reject(reason)
promise reason.
promise. promise ,
.
deferred/promise try/catch/throw,
reject throw JavaScript. ,
promise
promise, "throw" ,
reject.
1. promiseB = promiseA.then(function(result) {
2.
// success: - promiseB
3.
//
4.
return result;
5. }, function(reason) {
// error: , ,
//
promiseB newPromiseOrValue,
6.
7.
//
promiseB
if (canHandle(reason)) {
8.
9.
//
return newPromiseOrValue;
10.
11.
12.
13.
}
return $q.reject(reason);
14. });
reason {*} , , ,
.
:
{Promise} promise reason.
when(value)
, promise $q promise.
, , promise,
promise , .
:
$rootElement
Angular. ngApp
, angular.bootstrap.
$injector , $rootElement.injector().
$rootScope
.
.
.
: .
$route
URL (HTML ).
$location.url()
.
$routeProvider API.
$route ngView $routeParams.
$location
$routeParams
reload()
, $location .
ngView , .
current
. :
controller: , .
locals: , $controller
. locals resolve.
locals :
routes
$scope .
$template HTML .
Events
$routeChangeError
, promise .
:
:
:
current {Route} .
previous {Route} .
$routeChangeStart
. route
, .
, ,
resolve. ,
$routeChangeSuccess.
:
:
:
next {Route} .
current {Route} .
$routeChangeSuccess
. ngView
.
:
:
:
angularEvent {Object} .
current {Route} .
previous {Route|Undefined} ,
undefined, .
$routeUpdate
reloadOnSearch false,
.
:
:
Example
URL $route
URL, ngView .
, ,
.
Index.html
1. <!doctype html>
2. <html ng-app="ngView">
3.
<head>
4.
5.
6.
7.
8.
9.
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="MainCntl">
Choose:
10.
11.
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
12.
13.
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
14.
15.
16.
17.
<div ng-view></div>
<hr />
18.
19.
<pre>$location.path() = {{$location.path()}}</pre>
20.
21.
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
22.
23.
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
24.
25.
</div>
</body>
26. </html>
Book.html
1. controller: {{name}}<br />
2. Book Id: {{params.bookId}}<br />
Chapter.html
1. controller: {{name}}<br />
2. Book Id: {{params.bookId}}<br />
3. Chapter Id: {{params.chapterId}}
Script.js
1. angular.module('ngView', [], function($routeProvider, $locationProvider) {
2.
3.
4.
5.
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl,
resolve: {
6.
7.
8.
9.
10.
11.
return delay.promise;
}
12.
13.
}
});
14.
15.
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
16.
17.
controller: ChapterCntl
});
18.
19.
20. $locationProvider.html5Mode(true);
21. });
22.
23. function MainCntl($scope, $route, $routeParams, $location) {
24.
25.
$scope.$route = $route;
$scope.$location = $location;
$scope.name = "BookCntl";
$scope.params = $routeParams;
32. }
33.
34. function ChapterCntl($scope, $routeParams) {
35. $scope.name = "ChapterCntl";
36. $scope.params = $routeParams;
37. }
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
4.
5.
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
6.
7.
8.
9.
element('a:contains("Scarlet")').click();
sleep(2); // promises are not part of scenario waiting
10.
11.
expect(content).toMatch(/controller\: BookCntl/);
$routeParams
. ,
$location search(), path(). path , $route.
, path search.
$routeParams (
) .
$route
$templateCache
html .
$cacheFactory.
$timeout
Angular window.setTimeout. fn
try/catch $exceptionHandler.
promise
, .
, $timeout.cancel(promise).
$timeout.flush()
.
$browser
Parameters
fn {function()} .
delay(optional=0) {number=} .
Methods
cancel(promise)
, promise. promise
.
:
:
{boolean} true, .
$window
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
</head>
<body>
7.
8.
9.
10. </html>
Module
modules Angular.
config(configFn)
,
.
:
configFn {Function} .
.
constant(name, object)
,
. $provide.constant().
:
name {string}
object {*} .
controller(name, constructor)
$controllerProvider.register().
:
name {string} .
constructor {Function} .
directive(name, directiveFactory)
$compileProvider.directive().
:
name {string}
directiveFactory {Function}
.
factory(name, providerFunction)
$provide.factory().
:
name {string}
providerFunction {Function}
.
filter(name, filterFactory)
$filterProvider.register().
:
name {string} .
filterFactory {Function}
.
provider(name, providerType)
$provide.provider().
:
name {string}
providerType {Function}
.
run(initializationFn)
,
.
:
initializationFn {Function}
. .
service(name, constructor)
$provide.service().
:
name {string}
constructor {Function}
.
value(name, object)
$provide.value().
:
name {string}
object {*} .
name
:
{string} .
requires
, .
:
{Array.<string>} ,
.
Attributes
/ ,
DOM.
{{ }}. , .. Angular
:
<span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
$set(name, value)
DOM .
:
name {string} .
$attr .
value {string} .
$attr
:
{object} DOM
. ,
.
Scope
$rootScope
$injector. $new().
( , HTML .)
, ,
.
1. angular.injector(['ng']).invoke(function($rootScope) {
2.
var scope = $rootScope.$new();
3.
scope.salutation = 'Hello';
4.
5.
scope.name = 'World';
6.
7.
expect(scope.greeting).toEqual(undefined);
8.
9.
scope.$watch('name', function() {
scope.greeting = scope.salutation + ' ' + scope.name + '!';
10.
11.
}); //
12.
expect(scope.greeting).toEqual(undefined);
13.
scope.name = 'Misko';
14.
// , .. watch
15.
16.
expect(scope.greeting).toEqual(undefined);
17.
18.
scope.$digest(); // () watches
expect(scope.greeting).toEqual('Hello Misko!');
19. });
,
:
1. Scope([providers][, instanceCache]);
:
{Object} .
$apply(exp)
$apply()
1. function $apply(expr) {
2.
try {
3.
4.
return $eval(expr);
} catch (e) {
5.
6.
$exceptionHandler(e);
} finally {
7.
8.
$root.$digest();
}
9. }
$apply() :
1. $eval().
2.
$exceptionHandler.
3. watch
$digest().
:
string: .
function(scope):
.
:
{*} .
$broadcast(name, args)
name , (
), ,
ng.$rootScope.Scope#$on.
,
$broadcast. listeners name
.
,
. .
,
listeners $exceptionHandler.
:
name {string} .
args {...*} ,
.
:
{Object} , ng.$rootScope.Scope#$on
$destroy()
( )
. , $digest()
,
. ,
.
$destroy() , ngRepeat
.
$destroy
.
$destroy,
.
$digest()
watchers
. watcher , (
$digest()) $digest() watchers ,
. , .
' ',
10.
$digest() .
$apply()( ), $digest().
, $digest(),
watchExpression $watch() .
$digest() -,
.
:
1. var scope = ...;
2. scope.name = 'misko';
3. scope.counter = 0;
4.
5. expect(scope.counter).toEqual(0);
6. scope.$watch('name', function(newValue, oldValue) {
7.
scope.counter = scope.counter + 1;
8. });
9. expect(scope.counter).toEqual(0);
10.
11. scope.$digest();
12. // no variable change
13. expect(scope.counter).toEqual(0);
14.
15. scope.name = 'adam';
16. scope.$digest();
17. expect(scope.counter).toEqual(1);
$emit(name, args)
name ,
ng.$rootScope.Scope#$on .
, $emit.
listeners name
. ,
. ,
.
, listeners
$exceptionHandler .
:
name {string} .
args {...*} ,
.
:
{Object} , , ng.$rootScope.Scope#$on
$eval(expression)
expression
. , , ().
Angular.
:
1. var scope = ng.$rootScope.Scope();
2. scope.a = 1;
3. scope.b = 2;
4.
5. expect(scope.$eval('a+b')).toEqual(3);
6. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
string: , .
function(scope): ,
.
:
{*} .
$evalAsync(expression)
.
$evalAsync , , :
(
DOM).
$digest expression.
, ,
$exceptionHandler.
:
string: .
function(scope): ,
.
$new(isolate)
.
$digest() $digest().
$destroy().
$destroy() ,
, ,
, .
:
:
{Object} .
$on(name, listener)
. $emit
.
: function(event, args...).
event :
targetScope - {Scope}: , :
$emit $broadcast.
currentScope - {Scope}: ,
.
name - {string}: .
stopPropagation - {function=}: stopPropagation
(
$emit).
preventDefault - {function}: preventDefault
defaultPrevented true.
defaultPrevented - {boolean}: true preventDefault .
name {string} .
:
{function()} ,
.
listener,
watchExpression.
watchExpression $digest()
, .
( $digest() ,
watchExpression )
listener
watchExpression
( , ).
angular.equals. ,
, angular.copy.
, ,
.
listener ,
listener. ,
.
10, .
$digest,
watchExpression listener. (..
watchExpression $digest,
, .)
, listener
( $evalAsync) .
, .. watchExpression
. listener,
newVal oldVal. (===),
.
:
1. // , $rootScope
2. var scope = $rootScope;
3. scope.name = 'misko';
4. scope.counter = 0;
5.
6. expect(scope.counter).toEqual(0);
7. scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.coun
ter + 1; });
8. expect(scope.counter).toEqual(0);
9.
10. scope.$digest();
11. //
12. expect(scope.counter).toEqual(0);
13.
14. scope.name = 'adam';
15. scope.$digest();
16. expect(scope.counter).toEqual(1);
watchExpression {(function()|string)} ,
$digest.
, listener.
string:
function(scope): ,
.
listener(optional) {(function()|string)=} ,
watchExpression.
string:
function(newValue, oldValue, scope):
, .
objectEquality(optional) {boolean=} ,
.
:
{function()}
.
$id
:
{number} (
) .
$destroy
, ,
.
:
: ,
FormController
FormController ,
, valid/invalid dirty/pristine.
form FormController.
$pristine
True, .
$dirty
True, .
$valid
True,
( ).
$invalid
True,
( ).
$error
,
, :
NgModelController
Index.html
1. <!doctype html>
2. <html ng-app="customControl">
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<form name="myForm">
9.
10.
11.
12.
13.
<div contenteditable
name="myWidget" ng-model="userContent"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
14.
<textarea ng-model="userContent"></textarea>
15.
</form>
16. </body>
17. </html>
Style.css
1. [contenteditable] {
2.
3.
4.
min-height: 20px;
5. }
6.
7. .ng-invalid {
8.
border: 1px solid red;
9. }
Script.js
1. angular.module('customControl', []).
2.
directive('contenteditable', function() {
3.
4.
return {
restrict: 'A', // only activate on element attribute
5.
6.
7.
8.
9.
10.
11.
12.
};
13.
14.
15.
16.
17.
18.
});
read(); // initialize
19.
20.
21.
22.
function read() {
ngModel.$setViewValue(element.html());
element.html(ngModel.$viewValue || '');
23.
24.
25.
26.
}
}
};
});
2.
3.
4.
5.
expect(contentEditable.text()).toEqual('Change me!');
input('userContent').enter('');
6.
7.
expect(contentEditable.text()).toEqual('');
expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
8. });
$render()
.
ng-model.
$setValidity(validationErrorKey, isValid)
,
. ( ,
- invalid).
.
:
$setViewValue(value)
.
DOM.
input select .
formatters ,
.
:
value {string} .
$viewValue
$modelValue
, .
$parsers
DOM, /
.
$formatters
,
.
$error
, .
$pristine
True, .
$dirty
True, .
$valid
True, .
$invalid
True, .
API
angular.bind
, fn self (self
this fn). args .
function currying.
self {Object} , fn .
fn {function()} .
{function()} , fn
.
angular.bootstrap
angular.
: Bootstrap
1. angular.bootstrap(element[, modules]);
modules(optional) {Array<String|Function>=}
. : modules
{AUTO.$injector} .
angular.copy
source, .
destination,
.
, ( ) (
) , /
source.
source , .
: Angular.
ng.$filter Angular.
1. angular.copy(source[, destination]);
source {*} , .
, null undefined.
destination(optional) {(Object|Array)=} ,
source. , , source.
angular.element
jQuery jqLite,
DOMContentLoaded.
jqLite , API- jQuery , Angular
DOM. jqLite -
, jQuery API - ,
.
: , Angular jQuery
jqLite; DOM .
addClass()
after()
append()
attr()
bind() - Does not support namespaces
children() - Does not support selectors
clone()
contents()
css()
data()
eq()
find() - Limited to lookups by tag name
hasClass()
html()
next() - Does not support selectors
parent() - Does not support selectors
prepend()
prop()
ready()
remove()
removeAttr()
removeClass()
removeData()
replaceWith()
text()
toggleClass()
triggerHandler() - Doesn't pass native event objects to handlers.
unbind() - Does not support namespaces
val()
wrap()
, Angular
jQuery jQuery lite:
controller(name) .
, ngController.
name ,
(, 'ngModel').
injector() .
scope() .
1. angular.element(element);
{Object} jQuery .
angular.equals
, . ,
.
,
:
(===).
(=== ).
NaN. ( JavasScript, NaN == NaN => false. NaN
)
, function ,
$ - .
DOM Window (===).
1. angular.equals(o1, o2);
o1 {*} .
o2 {*} .
{boolean} True, .
angular.extend
dst src
dst. src.
1. angular.extend(dst, src);
dst {Object} .
src {...Object} .
angular.forEach
iterator obj,
. iterator iterator(value, key),
value , key
. context
.
: angular.foreach.
obj {Object|Array} .
iterator {Function} .
context(optional) {Object=} ,
( this).
{Object|Array} obj.
angular.fromJson
JSON.
1. angular.fromJson(json);
{Object|Array|Date|string|number} .
angular.identity
.
.
1. angular.identity();
angular.injector
,
( ).
1. angular.injector(modules);
modules {Array.<string|Function>} .
angular.module. ng .
{function()} . $injector.
:
1. //
2. var $injector = angular.injector(['ng']);
3.
4. //
5. //
6. $injector.invoke(function($rootScope, $compile, $document){
7.
8.
$compile($document)($rootScope);
$rootScope.$digest();
9. });
angular.isArray
, .
1. angular.isArray(value);
value {*} .
angular.isDate
, value .
1. angular.isDate(value);
value {*} .
angular.isDefined
, .
1. angular.isDefined(value);
value {*} .
angular.isElement
, DOM ( jQuery ).
1. angular.isElement(value);
value {*} .
angular.isFunction
, .
1. angular.isFunction(value);
value {*} .
angular.isNumber
, .
1. angular.isNumber(value);
value {*} .
angular.isObject
1. angular.isObject(value);
value {*} .
angular.isString
, .
1. angular.isString(value);
value {*} .
angular.isUndefined
, .
1. angular.isUndefined(value);
value {*} .
angular.lowercase
1. angular.lowercase(string);
string {string} .
{string} .
angular.mock
'angular-mocks.js'
.
angular.module
angular.module Angular .
( angular )
.
, , .
$injector.
1. //
2. var myModule = angular.module('myModule', []);
3.
4. //
5. myModule.value('appName', 'MyCoolApp');
6.
7. // .
8. myModule.config(function($locationProvider) {
9.
//
10. $locationProvider.hashPrefix('!');
11. });
, ::
, ngApp angular.bootstrap
.
1. angular.module(name[, requires], configFn);
name {!string} .
requires(optional) {Array.<string>=} ,
. , .
configFn {Function} .
Module#config().
angular.noop
().
.
1. function foo(callback) {
2.
var result = calculateResult();
3.
(callback || angular.noop)(result);
4. }
1. angular.noop();
angular.toJson
JSON.
1. angular.toJson(obj[, pretty]);
angular.uppercase
1. angular.uppercase(string);
string {string} .
{string} .
angular.version
, AngularJS.
:
full {string} , "0.9.18".
major {number} , "0".
minor {number} , "9".
dot {number} , "18".
codeName {string} , "jiggling-armfat".
1. angular.version
ng-mock
$exceptionHandler
ng.$exceptionHandler,
, . $exceptionHandlerProvider
.
1. describe('$exceptionHandlerProvider', function() {
2.
3.
4.
5.
module(function($exceptionHandlerProvider) {
6.
$exceptionHandlerProvider.mode('log');
7.
8.
});
9.
10.
11.
12.
13.
14.
expect($exceptionHandler.errors).toEqual([]);
expect($log.assertEmpty());
15.
16.
$timeout.flush();
expect($exceptionHandler.errors).toEqual(['banana peel']);
17.
18.
19. });
20. });
$httpBackend
HTTP, ,
$http.
: HTTP end-to-end
,
e2e $httpBackend mock.
,
, XHR JSONP
. , ,
, , ,
, ,
.
,
expect when apis , (expectGET, whenPOST, ..).
Angular - , $http,
$httpBackend.
$httpBackend ( API
$httpBackend) ,
.
() ,
http , :
$httpBackend.expect
$httpBackend.when
,
. , ,
.
,
, ,
, . ,
.
.expect(...).respond(...)
.when(...).respond(...)
(. )
, ,
.
,
.
,
, ,
. .
HTTP
$httpBackend .
,
, , .
, , .
$httpBackend flush(),
,
api , .
$httpBackend
1. //
$scope.user = data;
});
6.
7.
this.saveMessage = function(message) {
8.
$scope.status = 'Saving...';
9.
$http.post('/add-msg.py', message).success(function(response) {
10.
$scope.status = '';
11.
12.
13.
14.
}).error(function() {
$scope.status = 'ERROR!';
});
};
15. }
16.
17. //
18. var $httpBackend;
19.
20. beforeEach(inject(function($injector) {
21.
22.
$httpBackend = $injector.get('$httpBackend');
23.
24.
//
$httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx
'});
25. }));
26.
27.
28. afterEach(function() {
29. $httpBackend.verifyNoOutstandingExpectation();
30. $httpBackend.verifyNoOutstandingRequest();
31. });
32.
33.
34. it('should fetch authentication token', function() {
35. $httpBackend.expectGET('/auth.py');
36.
37.
38. });
39.
40.
41. it('should send msg to server', function() {
42.
43.
// ,
//
44.
45.
// $httpBackend ,
//
46.
47.
48.
49.
50.
51.
controller.saveMessage('message content');
expect(controller.status).toBe('Saving...');
52.
53.
$httpBackend.flush();
expect(controller.status).toBe('');
54. });
55.
56.
57. it('should send auth header', function() {
58.
59.
60.
61.
62.
}).respond(201, '');
63.
64.
65.
66.
controller.saveMessage('whatever');
$httpBackend.flush();
67. });
Methods
expect(method, url, data, headers)
.
:
:
{requestHandler} , respond,
.
expectDELETE(url, headers)
DELETE.
expect().
:
:
{requestHandler} respond,
.
expectGET(url, headers)
GET. expect().
:
:
{requestHandler} , respond,
.
expectHEAD(url, headers)
HEAD. expect().
:
:
{requestHandler} , respond,
.
expectJSONP(url)
JSONP. expect().
:
:
{requestHandler} , respond,
.
PATCH. expect().
:
:
{requestHandler} , respond,
.
POST. expect().
:
:
{requestHandler} , respond,
.
PUT. expect().
:
:
{requestHandler} , respond,
.
flush(count)
.
:
count(optional) {number=} (
). , .
, (
).
resetExpectations()
, . ,
resetExpectations ,
$httpBackend.
verifyNoOutstandingExpectation()
, , expect api, .
, verifyNoOutstandingExpectation .
, ,
"afterEach".
1. afterEach($httpBackend.verifyExpectations);
verifyNoOutstandingRequest()
.
, ,
"afterEach".
1. afterEach($httpBackend.verifyNoOutstandingRequest);
:
{requestHandler} , respond,
.
whenDELETE(url, headers)
DELETE.
when().
:
:
{requestHandler} , respond,
.
whenGET(url, headers)
GET.
when().
:
:
{requestHandler} , respond,
.
whenHEAD(url, headers)
HEAD.
when().
:
:
{requestHandler} , respond,
.
whenJSONP(url)
JSONP.
when().
:
:
{requestHandler} , respond,
.
POST.
when().
:
:
{requestHandler} , respond,
.
PUT.
when().
:
:
{requestHandler} , respond,
.
$log
ng.$log (
). logs
,
$log.error.logs.
assertEmpty()
, . ,
.
reset()
logs
$timeout
ng.$timeout "flush".
1. $timeout();
flush()
API
angular.mock.dump
: ,
.
angular ( , , ..)
, .
window,
.
1. angular.mock.dump(object);
object {*} .
{string} .
angular.mock.inject
: window .
: jasmine.
,
. inject() $injector ,
.
jasmine inject.
1. angular.module('myApplicationModule', [])
2.
.value('mode', 'app')
3.
4.
.value('version', 'v1.0.1');
5.
6. describe('MyApp', function() {
7.
8.
// , ,
// "ng".
beforeEach(module('myApplicationModule'));
9.
10.
11.
12.
// inject() -
it('should provide a version', inject(function(mode, version) {
13.
14.
15.
16.
expect(version).toEqual('v1.0.1');
expect(mode).toEqual('app');
17.
18.
}));
19.
20.
// inject module ,
// it beforeEach
it('should override a version and test the new version is injected', function()
21.
22.
{
23.
// module() ( )
24.
25.
module(function($provide) {
$provide.value('version', 'overridden'); //
26.
});
27.
28.
inject(function(version) {
29.
30.
expect(version).toEqual('overridden');
});
31. ));
32. });
1. angular.mock.inject(fns);
fns {...Function} ,
injector.
angular.mock.module
: , window.
: jasmine.
.
, inject.
inject .
1. angular.mock.module(fns);
fns {...(string|Function)} ,
.
. 'ng' 'ngMock'
.
angular.mock.TzDate
: , Date.
Date, .
, ,
,
.
1. TzDate(offset, timestamp);
offset {number} (
)
UTC
auto
$injector
$injector provider,
, .
:
JavaScript , .
. .
1. // ( / )
2. $injector.invoke(function(serviceA){});
3.
4. //
5. function explicit(serviceA) {};
6. explicit.$inject = ['serviceA'];
7. $injector.invoke(explicit);
8.
9. //
10. $injector.invoke(['serviceA', function(serviceA){}]);
JavaScript toString() .
. :
, .. .
$inject
$inject .
,
.
annotate(fn)
, . API
, .
, .
.
toString()
.
1. //
2. function MyController($scope, $route) {
3.
// ...
4. }
5.
6. //
7. expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
/ .
.
$inject
$inject ,
.
8. //
9. var MyController = function(obfuscatedScope, obfuscatedRoute) {
10. // ...
11. }
12. //
13. MyController.$inject = ['$scope', '$route'];
14.
15. //
16. expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
,
$inject .
, :
17. // ( minification / obfuscation)
18. injector.invoke(function($compile, $rootScope) {
19. // ...
20. });
21.
22. // $inject
23. var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
24. // ...
25. };
26. tmpFn.$inject = ['$compile', '$rootScope'];
27. injector.invoke(tmpFn);
28.
29. //
30. injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope)
{
31.
// ...
32. }]);
33.
34. //
35. expect(injector.annotate(
36.
['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
37. ).toEqual(['$compile', '$rootScope']);
fn {function|Array.<string|Function>} ,
, , .
:
{Array.<string>} , .
get(name)
.
:
name {string} .
:
{*} .
instantiate(Type, locals)
JS.
new, , .
:
Type {function} .
locals(optional) {Object=} . ,
, $injector,
.
:
{Object} .
$injector.
:
fn {!function} .
.
locals(optional) {Object=} . ,
$injector,
.
:
{*} , .
$provide
$provide $injector. ,
.
Provider.
$get(). $get
. ,
.
1. function GreetProvider() {
2.
3.
4.
5.
this.salutation = function(text) {
salutation = text;
6.
7.
};
8.
9.
this.$get = function() {
return function (name) {
10.
11.
12. };
13. }
14.
15. describe('Greeter', function(){
16.
17.
beforeEach(module(function($provide) {
18.
19.
$provide.provider('greet', GreetProvider);
}));
20.
21.
22.
23.
expect(greet('angular')).toEqual('Hello angular!');
}));
24.
25.
26.
27.
module(function(greetProvider) {
greetProvider.salutation('Ahoj');
28.
29.
});
inject(function(greet) {
30.
31.
expect(greet('angular')).toEqual('Ahoj angular!');
});
32.
});
constant(name, value)
, value
( ) can be injected into configuration function (other modules)
decorator.
:
name {string} .
value {*} .
:
{Object}
decorator(name, decorator)
, .
, ,
.
name {string} .
decorator {function()}
. injector.invoke
.
:
$delegate , api,
, , .
factory(name, $getFn)
, $get.
:
name {string} .
:
{Object}
provider(name, provider)
.
.
:
name {string} . :
name + 'Provider'.
provider {(Object|function())} :
:
{Object}
service(name, constructor)
.
:
name {string} .
constructor {Function} ( ),
.
:
{Object}
value(name, value)
, $get.
:
name {string} .
value {*} .
:
{Object}
ngCookie
$cookies
/ .
, ,
/ $eval.
$browser
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
</body>
9. </html>
Script.js
1. function ExampleController($cookies) {
2.
3.
//
var favoriteCookie = $cookies.myFavorite;
4.
5.
//
$cookies.myFavorite = 'oatmeal';
6. }
$cookieStore
- (-) , .
,
angular: toJson fromJson.
$cookies
get(key)
.
:
key {string} .
:
{Object} .
put(key, value)
.
:
key {string} .
value {Object} .
remove(key)
.
:
key {string} .
ngMockE2E
$httpBackend
: ,
unit-testing $httpBackend mock.
when api (whenGET, whenPOST, ..)
$httpBackend (,
).
, end-to-end , ,
, api ,
, (,
).
passThrough when respond.
, ,
. e2e $httpBackend
, XMLHttpRequest.
http ,
ngMockE2E :
//
6.
7.
$httpBackend.whenGET('/phones').respond(phones);
8.
9.
//
$httpBackend.whenPOST('/phones').respond(function(method, url, data) {
10.
11.
phones.push(angular.fromJSON(data));
});
12.
13.
$httpBackend.whenGET(/^\/templates\//).passThrough();
//...
14. });
, .
Methods
when(method, url, data, headers)
.
:
whenDELETE(url, headers)
DELETE.
when().
:
:
{requestHandler} , respond passThrough,
.
whenGET(url, headers)
GET.
when().
:
:
{requestHandler} , respond passThrough,
.
whenHEAD(url, headers)
HEAD.
when().
:
:
{requestHandler} , respond passThrough,
.
whenJSONP(url)
JSONP.
when().
:
:
{requestHandler} , respond passThrough,
.
PATCH.
when().
:
:
{requestHandler} , respond passThrough,
.
POST.
when().
:
:
{requestHandler} , respond passThrough,
.
PUT.
when().
:
ngResource
$resource
, ,
RESTful.
,
, $http.
$resource angular-resource.js
Angular. Google CDN,
code.angularjs.org.
:
angular.module('app', ['ngResource']);
!
$http
actions(optional) {Object.<Object>=}
, .
:
{action1: {method:?, params:?, isArray:?},
action2: {method:?, params:?, isArray:?},
...}
:
action {string} . ,
.
method {string} HTTP . : GET, POST, PUT, DELETE,
JSONP
params {object=} , .
isArray {boolean=} true,
, .
{Object}
. :
{ 'get':
{method:'GET'},
'save':
{method:'POST'},
'query':
{method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
ng.$http http ,
. ,
. save, remove delete , $.
CRUD (create, read, update, delete)
:
, $resource, (
isArray). ,
. , ..
, . ,
, , ,
. ,
.
1. // CreditCard
6.
7. //
8. var cards = CreditCard.query(function() {
9.
// GET: /user/123/card
10.
11.
12.
13.
14.
15.
16.
17.
// GET
card.$save();
18.
19.
20.
21.
22.
23.
//
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name
:'J. Smith'}
24. });
25.
26. //
27. var newCard = new CreditCard({number:'0123'});
28. newCard.name = "Mike Smith";
29. newCard.$save();
30. // POST: /user/123/card {number:'0123', name:'Mike Smith'}
31. // : {id:789, number:'01234', name: 'Mike Smith'};
32. expect(newCard.id).toEqual(789);
.
$http url method
params. ,
, -GET ,
$ . CRUD (create, read, update,
delete) .
user.abc = true;
user.$save();
5. });
, get, query ,
, ,
$http ,
:
u.$save(function(u, putResponseHeaders) {
//u =>
8. });
, , $resource:
Index.html
1. <!doctype html>
2. <html ng-app>
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="BuzzController">
9.
10.
<input ng-model="userId"/>
<button ng-click="fetch()">fetch</button>
11.
12.
<hr/>
<div ng-repeat="item in activities.data.items">
13.
14.
15.
16.
<a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a>
<a href ng-click="expandReplies(item)" style="float: right;">Expand repl
ies: {{item.links.replies[0].count}}</a>
17.
18.
</h3>
{{item.object.content | html}}
19.
20.
21.
22.
23.
24.
25.
</div>
</div>
</div>
</body>
26. </html>
Script.js
1. function BuzzController($resource) {
2.
this.userId = 'googlebuzz';
3.
4.
5.
6.
this.Activity = $resource(
'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId
/:comments',
{alt:'json', callback:'JSON_CALLBACK'},
{get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP',
params:{visibility:'@self', comments:'@comments'}}}
7.
);
8. }
9.
10. BuzzController.prototype = {
11.
12.
fetch: function() {
this.activities = this.Activity.get({userId:this.userId});
13.
14.
},
expandReplies: function(activity) {
15.
16. }
17. };
18. BuzzController.$inject = ['$resource'];
ngSanitize
ngBindHtml
, expression
$sanitize innerHTML .
$sanitize.
1. <ANY ng-bind-html="{expression}">
2.
...
3. </ANY>
ngBindHtml {expression} .
linky
html.
http/https/ftp/mailto email .
HTML
JavaScript
$filter('linky')(text)
text {string} .
{string} Html.
Index.html
1. <!doctype html>
2. <html ng-app="ngSanitize">
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="Ctrl">
9.
10.
11.
12.
<td>Filter</td>
13.
<td>Source</td>
14.
15.
<td>Rendered</td>
</tr>
16.
17.
<tr id="linky-filter">
<td>linky filter</td>
18.
19.
<td>
<pre><div ng-bind-html="snippet | linky"><br></div></pre>
20.
21.
</td>
<td>
22.
23.
24.
25.
</tr>
<tr id="escaped-html">
26.
27.
<td>no filter</td>
<td><pre><div ng-bind="snippet"><br></div></pre></td>
28.
29.
<td><div ng-bind="snippet"></div></td>
</tr>
30.
31.
</table>
</body>
32. </html>
Script.js
1. function Ctrl($scope) {
2.
$scope.snippet =
3.
4.
5.
6.
'mailto:us@somewhere.org,\n'+
'another@somewhere.org,\n'+
7.
8. }
5.
6.
'<a href="mailto:us@somewhere.org">us@somewhere.org</a>, ' +
'<a href="mailto:another@somewhere.org">another@somewhere.org</a>, '
+
7.
8. });
9.
10. it ('should not linkify snippet without the linky filter', function() {
11. expect(using('#escaped-html').binding('snippet')).
12.
13.
14.
15.
"another@somewhere.org,\n" +
16.
17. });
18.
19. it('should update', function() {
20. input('snippet').enter('new http://link.');
21.
22.
expect(using('#linky-filter').binding('snippet | linky')).
toBe('new <a href="http://link">http://link</a>.');
$sanitize
html. ( )
html. ,
, , ,
, , ,
HTML , .
1. $sanitize(html);
{string} html.
Index.html
1. <!doctype html>
2. <html ng-app="ngSanitize">
3.
4.
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5.
6.
<script src="script.js"></script>
</head>
7.
8.
<body>
<div ng-controller="Ctrl">
9.
10.
11.
12.
<tr>
<td>Filter</td>
13.
<td>Source</td>
14.
<td>Rendered</td>
15.
</tr>
16.
17.
<tr id="html-filter">
<td>html filter</td>
18.
19.
<td>
<pre><div ng-bind-html="snippet"><br/></div></pre>
20.
21.
</td>
<td>
22.
23.
<div ng-bind-html="snippet"></div>
</td>
24.
25.
</tr>
<tr id="escaped-html">
26.
27.
<td>no filter</td>
<td><pre><div ng-bind="snippet"><br/></div></pre></td>
28.
29.
<td><div ng-bind="snippet"></div></td>
</tr>
30.
31.
<tr id="html-unsafe-filter">
<td>unsafe html filter</td>
32.
<td><pre><div ng-bind-html-unsafe="snippet"><br/></div></p
re></td>
33.
34.
<td><div ng-bind-html-unsafe="snippet"></div></td>
</tr>
35.
36.
</table>
</div>
37. </body>
38. </html>
Script.js
1. function Ctrl($scope) {
2.
3.
$scope.snippet =
'<p style="color:blue">an html\n' +
4.
5.
6. }
expect(using('#html-filter').element('div').html()).
toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
4. });
5.
6. it('should escape snippet without any filter', function() {
7.
expect(using('#escaped-html').element('div').html()).
8.
9.
10.
11. });
"snippet</p>");
12.
13. it('should inline raw snippet if filtered as unsafe', function() {
14.
15.
expect(using('#html-unsafe-filter').element("div").html()).
toBe("<p style=\"color:blue\">an html\n" +
16.
17.
18. });
19.
20. it('should update', function() {
21. input('snippet').enter('new <b>text</b>');
22.
23.
expect(using('#html-filter').binding('snippet')).toBe('new <b>text</b>');
expect(using('#escaped-html').element('div').html()).toBe("new <b>text<
24.
/b>");
expect(using('#html-unsafe-filter').binding("snippet")).toBe('new <b>text</b>');
25. });