Вы находитесь на странице: 1из 168

API Angular

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.

userType: <input name="input" ng-model="userType" required>

10.

<span class="error" ng-show="myForm.input.$error.required">Required!</span><


br>

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. }

End to end test


1. it('should initialize to model', function() {
2.
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

HTML angular . HTML5


.

, 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.

User name: <input type="text" name="userName" ng-model="user.name" require


d>

11.
12.

<span class="error" ng-show="myForm.userName.$error.required">


Required!</span><br>

13.
14.

Last name: <input type="text" name="lastName" ng-model="user.last"


ng-minlength="3" ng-maxlength="10">

15.
16.

<span class="error" ng-show="myForm.lastName.$error.minlength">


Too short!</span>

17.
18.

<span class="error" ng-show="myForm.lastName.$error.maxlength">


Too long!</span><br>

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. }

End to end test


1. it('should initialize to model', function() {
2.
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
3.
4.

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.

input('user.last').enter('some ridiculously long name');


expect(binding('user'))

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.

Value1: <input type="checkbox" ng-model="value1"> <br/>


Value2: <input type="checkbox" ng-model="value2"

11.
12.

ng-true-value="YES" ng-false-value="NO"> <br/>


<tt>value1 = {{value1}}</tt><br/>

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. }

End to end test


1. it('should change state', function() {
2.
3.

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.

<form name="myForm" ng-controller="Ctrl">


Email: <input type="email" name="input" ng-model="text" required>

10.
11.

<span class="error" ng-show="myForm.input.$error.required">


Required!</span>

12.
13.

<span class="error" ng-show="myForm.input.$error.email">


Not valid email!</span>

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. }

End to end test


1. it('should initialize to model', function() {
2.
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.

min="0" max="99" required>


<span class="error" ng-show="myForm.list.$error.required">

12.
13.

Required!</span>
<span class="error" ng-show="myForm.list.$error.number">

14.
15.

Not valid number!</span>


<tt>value = {{value}}</tt><br/>

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. }

End to end test


1. it('should initialize to model', function() {
2.
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.

<input type="radio" ng-model="color" value="red"> Red <br/>


<input type="radio" ng-model="color" value="green"> Green <br/>

11.
12.

<input type="radio" ng-model="color" value="blue"> Blue <br/>


<tt>color = {{color}}</tt><br/>

13.
14.

</form>
</body>

15. </html>

Script.js
1. function Ctrl($scope) {
2.
$scope.color = 'blue';
3. }

End to end test


1. it('should change state', function() {
2.
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.

<form name="myForm" ng-controller="Ctrl">


Single word: <input type="text" name="input" ng-model="text"

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.

Single word only!</span>

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. }

End to end test


1. it('should initialize to model', function() {
2.
expect(binding('text')).toEqual('guest');
3.
expect(binding('myForm.input.$valid')).toEqual('true');
4. });
5.

6. it('should be invalid if empty', function() {


7.

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.

URL: <input type="url" name="input" ng-model="text" required>


<span class="error" ng-show="myForm.input.$error.required">

11.
12.

Required!</span>
<span class="error" ng-show="myForm.input.$error.url">

13.
14.

Not valid url!</span>


<tt>text = {{text}}</tt><br/>

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. }

End to end test


1. it('should initialize to model', function() {
2.
expect(binding('text')).toEqual('http://google.com');
3.
expect(binding('myForm.input.$valid')).toEqual('true');
4. });
5.
6. it('should be invalid if empty', function() {
7.
8.

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>

1. <ANY class="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>

1. <ANY class="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.

Hello <span ng-bind="name"></span>!


</div>

12. </body>
13. </html>

Script.js
1. function Ctrl($scope) {
2.
$scope.name = 'Whirled';
3. }

End to end test


1. it('should check ng-bind', function() {
2.
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
3.
4.

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>

1. <ANY class="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>

1. <ANY class="ng-bind-template: {string};">


2.
...
3. </ANY>

ngBindTemplate {string} {{ expression }} .

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.

<pre ng-bind-template="{{salutation}} {{name}}!"></pre>

12.

</div>

13. </body>
14. </html>

Script.js
1. function Ctrl($scope) {
2.
3.

$scope.salutation = 'Hello';
$scope.name = 'World';

4. }

End to end test


1. it('should check ng-bind', function() {
2.
3.

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.

<label for="ng-change-example2">Confirmed</label><br />


debug = {{confirmed}}<br />

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. }

End to end test


1. it('should evaluate the expression if changing from view', function() {
2.
3.

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>

ngChecked {expression} Angular .

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.

<input id="checkSlave" type="checkbox" ng-checked="master">


</body>

10. </html>

End to end test


1. it('should check both checkBoxes', function() {
2.
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
3.
4.

input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();

5. });

ngClass

ngClass CSS HTML ,


.
, .
, ,
.

1. <ANY ng-class="{expression}">
2.
...
3. </ANY>

1. <ANY class="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.

<input type="button" value="clear" ng-click="myVar=''">


<br>
<span ng-class="myVar">Sample Text</span>
</body>

12. </html>

Style.css
1. .my-class {
2.
color: red;
3. }

End to end test


1. it('should check ng-class', function() {
2.
expect(element('.doc-example-live span').prop('className')).not().
3.
4.

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

ngClassOdd ngClassEven , ngClass, ,


ngRepeat,
() .
ngRepeat.

1. <ANY ng-class-even="{expression}">
2.
...
3. </ANY>

1. <ANY class="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.

<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">


<li ng-repeat="name in names">

9.
10.

<span ng-class-odd="'odd'" ng-class-even="'even'">


{{name}} &nbsp; &nbsp; &nbsp;

11.
12.
13.
14.

</span>
</li>
</ol>
</body>

15. </html>

Style.css
1. .odd {

2.

color: red;

3. }
4. .even {
5.
color: blue;
6. }

End to end test


1. it('should check ng-class-odd and ng-class-even', function() {
2.
expect(element('.doc-example-live li:first span').prop('className')).
3.
4.

toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).

5.
toMatch(/even/);
6. });

ngClassOdd

ngClassOdd ngClassEven , ngClass, ,


ngRepeat,
() .
ngRepeat.

4. <ANY ng-class-odd="{expression}">
5.
...
6. </ANY>

4. <ANY class="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.

<li ng-repeat="name in names">


<span ng-class-odd="'odd'" ng-class-even="'even'">

25.
26.

{{name}} &nbsp; &nbsp; &nbsp;


</span>

27.
28.

</li>
</ol>

29. </body>
30. </html>

Style.css
7. .odd {
8.
color: red;
9. }
10. .even {
11. color: blue;
12. }

End to end test


7. it('should check ng-class-odd and ng-class-even', function() {
8.
9.

expect(element('.doc-example-live li:first span').prop('className')).


toMatch(/odd/);

10.
11.

expect(element('.doc-example-live li:last span').prop('className')).


toMatch(/even/);

12. });

ngClick

ngClick , ,
.

1. <ANY ng-click="{expression}">
2.
...
3. </ANY>

1. <ANY class="ng-click: {expression};">

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>

End to end test


1. it('should check ng-click', function() {
2.
expect(binding('count')).toBe('0');
3.
4.

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 :

1. [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {


2.
display: none;
3. }

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.

<div id="template1" ng-cloak>{{ 'hello' }}</div>


<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>

9.
</body>
10. </html>

End to end test


1. it('should remove the template directive and css class', function() {
2.
3.

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>

1. <ANY class="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.

Name: <input type="text" ng-model="name"/>


[ <a href="" ng-click="greet()">greet</a> ]<br/>

11.
12.

Contact:
<ul>

13.
14.

<li ng-repeat="contact in contacts">


<select ng-model="contact.type">

15.
16.

<option>phone</option>
<option>email</option>

17.
18.

</select>
<input type="text" ng-model="contact.value"/>

19.
20.

[ <a href="" ng-click="clearContact(contact)">clear</a>


| <a href="" ng-click="removeContact(contact)">X</a> ]

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.

$scope.name = "John Smith";


$scope.contacts = [

4.
5.

{type:'phone', value:'408 555 1212'},


{type:'email', value:'john.smith@example.org'} ];

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.

var index = this.contacts.indexOf(contactToRemove);


this.contacts.splice(index, 1);

18.
19.

};

20.
21.

$scope.clearContact = function(contact) {
contact.type = 'phone';

22.
23.

contact.value = '';
};

24. }

End to end test


1. it('should check controller', function() {
2.
3.

expect(element('.doc-example-live div>:input').val()).toBe('John Smith');


expect(element('.doc-example-live li:nth-child(1) input').val())

4.
5.

.toBe('408 555 1212');


expect(element('.doc-example-live li:nth-child(2) input').val())

6.
7.

.toBe('john.smith@example.org');

8.
9.

element('.doc-example-live li:first a:contains("clear")').click();


expect(element('.doc-example-live li:first input').val()).toBe('');

10.
11.

element('.doc-example-live li:last a:contains("add")').click();

12.
13.

expect(element('.doc-example-live li:nth-child(3) input').val())


.toBe('yourname@example.org');

14. });

ngCsp

CSP (Content Security Policy).


( <html> ,
ngApp).
, ,
.

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>

1. <ANY class="ng-dblclick: {expression};">


2.
...
3. </ANY>

ngDblclick {expression} dblclick. (


$event)

. ngClick

ngDisabled

Chrome/Firefox, IE8 IE:

1. <div ng-init="scope = { isDisabled: false }">


2. <button disabled="{{scope.isDisabled}}">Disabled</button>
3. </div>

HTML ,
disabled. ( true, false) angular
. ,
ngDisabled.

1. <INPUT ng-disabled="{expression}">
2.
...
3. </INPUT>

ngDisabled {expression} 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.

</head>
<body>

7.
8.

Click me to toggle: <input type="checkbox" ng-model="checked"><br/>


<button ng-model="button" ng-disabled="checked">Button</button>

9.
</body>
10. </html>

End to end test


1. it('should toggle button', function() {
2.
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
3.
4.

input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();

5. });

ngForm

form . HTML <form> .


, ,
.

, IE:

1. <ng-form
2.
[ngForm="{string}"]>
3. </ng-form>

1. <ANY ng-form
2.
[name="{string}"]>
3.
...
4. </ANY>

1. <ANY class="ng-form [name: {string};]">

2.

...

3. </ANY>

name|ngForm(optional) {string=} . ,
,
.

ngHide

ngHide ngShow DOM.

1. <ANY ng-hide="{expression}">
2.
...
3. </ANY>

1. <ANY class="ng-hide: {expression};">


2.
...
3. </ANY>

ngHide {expression} true,


, .

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.

Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <


br/>

9.
10.

Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>


</body>

11. </html>

End to end test


1. it('should check ng-show / ng-hide', function() {
2.
3.

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>

ngHref {template} , {{}}.

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.

<input ng-model="value" /><br />

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.

<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />

11.

<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't


reload)<br />

12.
13.

<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />


<a id="link-6" ng-href="{{value}}">link</a> (link, change location)

14. </body>
15. </html>

End to end test


1. it('should execute ng-click but not reload when href without value', function() {
2.
3.

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>

1. <ANY class="ng-include: {string}; [onload: {string};] [autoscroll: {string};]">


2.
...
3. </ANY>

ngInclude|src {string} angular , URL.


, ,
src="'myPartialTemplate.html'".

onload(optional) {string=} , ,
.

autoscroll(optional) {string=} ngInclude


$anchorScroll .

, .
, .
,
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.

<select ng-model="template" ng-options="t.name for t in templates">


<option value="">(blank)</option>

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.

[ { name: 'template1.html', url: 'template1.html'}

4.
5.

, { name: 'template2.html', url: 'template2.html'} ];


$scope.template = $scope.templates[0];

6. }

End to end test


1. it('should load template1.html', function() {
2. expect(element('.doc-example-live [ng-include]').text()).
3.
toMatch(/Content of template1.html/);
4. });
5. it('should load template2.html', function() {
6. select('template').option('1');
7.
8.

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>

1. <ANY class="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.

<div ng-init="greeting='Hello'; person='World'">


{{greeting}} {{person}}!

9.
10.

</div>
</body>

11. </html>

End to end test


1. it('should check greeting', function() {
2.
3.

expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');

4. });

ngList

, , .

1. <input ng-list="{string}">
2.
...
3. </input>

1. <input class="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.

List: <input name="namesInput" ng-model="names" ng-list required>


<span class="error" ng-show="myForm.list.$error.required">

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. }

End to end test


1. it('should initialize to model', function() {
2.
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>

1. <ANY class="ng-mousedown: {expression};">


2.
...
3. </ANY>

ngMousedown {expression}
mousedown. ( $event)

ngClick

ngMouseenter

mouseenter ( ).

1. <ANY ng-mouseenter="{expression}">
2.
...
3. </ANY>

1. <ANY class="ng-mouseenter: {expression};">


2.
...
3. </ANY>

ngMouseenter {expression} mouseenter. (


$event)

ngClick

ngMouseleave

mouseleave ( ).

1. <ANY ng-mouseleave="{expression}">
2.
...
3. </ANY>

1. <ANY class="ng-mouseleave: {expression};">


2.
...
3. </ANY>

ngMouseleave {expression} mouseleave. (


$event)

ngClick

ngMousemove

mousemove ( ).

1. <ANY ng-mousemove="{expression}">
2.
...
3. </ANY>

1. <ANY class="ng-mousemove: {expression};">


2.
...
3. </ANY>

ngMousemove {expression} mousemove. (


$event)

ngClick

ngMouseover

mouseover ( ).

1. <ANY ng-mouseover="{expression}">
2.

...

3. </ANY>

1. <ANY class="ng-mouseover: {expression};">


2.
...
3. </ANY>

ngMouseover {expression} mouseover. (


$event)

ngClick

ngMouseup

mouseup.

1. <ANY ng-mouseup="{expression}">
2.
...
3. </ANY>

1. <ANY class="ng-mouseup: {expression};">


2.
...
3. </ANY>

ngMouseup {expression} mouseup. (


$event)

ngClick

ngMultiple

HTML ,
multiple. ( true, false)
angular .
ngMultiple.

1. <SELECT ng-multiple="{expression}">
2.
...
3. </SELECT>

ngMultiple {expression} 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.

</head>
<body>

7.
8.

Check me check multiple: <input type="checkbox" ng-model="checked"><br/>


<select id="select" ng-multiple="checked">

9.
10.

<option>Misko</option>
<option>Igor</option>

11.
12.

<option>Vojta</option>
<option>Di</option>

13.
14.

</select>
</body>

15. </html>

End to end test


1. it('should toggle multiple', function() {
2.
expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
3.
4.

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.

<div ng-non-bindable>Ignored: {{1 + 2}}</div>


</body>

10. </html>

End to end test


1. it('should check ng-non-bindable', function() {
2.
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
3.
4.

expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);

5. });

ngPluralize

ngPluralize
en-US. angular.js
( Angular i18n ). ngPluralize
,
.

Angular , en-US: "one "


( ) "other " ( ).
( en-US,
"other" 1),
. , "3"
3.
.

ngPluralize

ngPluralize 2 : count when.


offset.
count
.

Angular,

when .
JSON, Angular .
ngPluralize:

1. <ng-pluralize count="personCount"
2.
when="{'0': 'Nobody is viewing.',
3.
4.

'one': '1 person is viewing.',


'other': '{} people are viewing.'}">

5. </ng-pluralize>

, "0: Nobody is viewing." .


, 0 "other" "0 people
are viewing" "Nobody is viewing". , , 12,
"12 people are viewing", "a dozen people are viewing".
({}), ,
. , Angular
{} {{personCount}}. {},
{{numberExpression}}.

ngPluralize offset

offset .
, "4 people are viewing this document",
"John, Kate and 2 others are viewing this document". offset
. :

1. <ng-pluralize count="personCount" offset=2


2.
when="{'0': 'Nobody is viewing.',
3.
'1': '{{person1}} is viewing.',
4.
5.

'2': '{{person1}} and {{person2}} are viewing.',


'one': '{{person1}}, {{person2}} and one other person are vie
wing.',

6.
ewing.'}">
7. </ng-pluralize>

'other': '{{person1}}, {{person2}} and {} other people are vi

(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.

<!--- Example with simple pluralization rules for en locale --->

14.
15.

Without Offset:
<ng-pluralize count="personCount"

16.
17.

when="{'0': 'Nobody is viewing.',


'one': '1 person is viewing.',

18.
19.

'other': '{} people are viewing.'}">


</ng-pluralize><br>

20.
21.

<!--- Example with offset --->

22.
23.

With Offset(2):
<ng-pluralize count="personCount" offset=2

24.
25.

when="{'0': 'Nobody is viewing.',


'1': '{{person1}} is viewing.',

26.
27.

'2': '{{person1}} and {{person2}} are viewing.',


'one': '{{person1}}, {{person2}} and one other person a
re viewing.',

28.
29.

'other': '{{person1}}, {{person2}} and {} other people


are viewing.'}">
</ng-pluralize>

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. }

End to end test


1. it('should show correct pluralized string', function() {
2.
3.

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.

toBe('Igor and Misko are viewing.');

18.
19.
20.

using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).

21.
22.

toBe('3 people are viewing.');


expect(element('.doc-example-live ng-pluralize:last').text()).

23.
24.

toBe('Igor, Misko and one other person are viewing.');

25.
26.

using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).

27.
28.

toBe('4 people are viewing.');


expect(element('.doc-example-live ng-pluralize:last').text()).

29.
30. });

toBe('Igor, Misko and 2 other people are viewing.');

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.

toBe('Igor, Misko and 2 other people are viewing.');

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>

expression {string} Angular .

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.

<input type="text" ng-readonly="checked" value="I'm Angular"/>

9.
</body>
10. </html>

End to end test


1. it('should toggle readonly attr', function() {
2.
3.

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
.
,
, :

$index {number} (0..length-1)


$first {boolean} true,
.
$middle {boolean} true,
.
$last {boolean} true,
.

1. <ANY ng-repeat="{repeat_expression}">
2.
...
3. </ANY>

1. <ANY class="ng-repeat: {repeat_expression};">


2.
...

3. </ANY>

.
1000.

ngRepeat {repeat_expression} ,
. :

variable in expression variable ,


expression
, .
: track in cd.tracks.

(key, value) in expression key value


, expression ,
.
: (name, age) in {'adam':10, 'amalie':12}.

,
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.

<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">


I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>

15. </body>
16. </html>

End to end test


1. it('should check ng-repeat', function() {
2.
var r = using('.doc-example-live').repeater('ul li');
3.
expect(r.count()).toBe(2);
4.

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>

expression {string} Angular .

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.

<option id="greet" ng-selected="selected">Greetings!</option>


</select>

12. </body>
13. </html>

End to end test


1. it('should select Greetings!', function() {
2.
3.

expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('selected').check();

4.
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
5. });

ngShow

ngShow ngHide DOM.

1. <ANY ng-show="{expression}">
2.
...
3. </ANY>

1. <ANY class="ng-show: {expression};">


2.
...
3. </ANY>

ngShow {expression} true, ,


.

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.

Show: <span ng-show="checked">I show up when your checkbox is checked.</span>


<br/>
Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span>
</body>

11. </html>

End to end test


1. it('should check ng-show / ng-hide', function() {
2.
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
3.
4.

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

Angular {{hash}} src :


, , URL
{{hash}} . 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>

ngSrc {template} , {{}}.

ngStyle

ngStyle CSS HTML


.

1. <ANY ng-style="{expression}">
2.
...
3. </ANY>

1. <ANY class="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.

<input type="button" value="set" ng-click="myStyle={color:'red'}">


<input type="button" value="clear" ng-click="myStyle={}">

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. }

End to end test


1. it('should check ng-style', function() {
2.
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
3.
4.

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>

1. <form class="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.

<form ng-submit="submit()" ng-controller="Ctrl">


Enter text and hit enter:

10.
11.

<input type="text" ng-model="text" name="text" />


<input type="submit" id="submit" value="Submit" />

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 = '';
}
};

End to end test


1. it('should check ng-submit', function() {
2.
3.

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>

ngSwitch|on {*} , ngswitch-when.

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.

<select ng-model="selection" ng-options="item for item in items">


</select>

11.
12.

<tt>selection={{selection}}</tt>
<hr/>

13.
14.

<div ng-switch on="selection" >


<div ng-switch-when="settings">Settings Div</div>

15.
16.

<span ng-switch-when="home">Home Span</span>


<span ng-switch-default>default</span>

17.
18.

</div>
</div>

19. </body>
20. </html>

Script.js
1. function Ctrl($scope) {
2.
3.

$scope.items = ['settings', 'home', 'other'];


$scope.selection = $scope.items[0];

4. }

End to end test


1. it('should start in settings', function() {
2. expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
3. });
4. it('should change to home', function() {
5. select('selection').option('home');
6. expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
7. });
8. it('should select deafault', function() {
9. select('selection').option('other');
10. expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
11. });

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.

$scope.title = 'Lorem Ipsum';


$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';

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.

'<div style="background-color: gray">{{title}}</div>' +


'<div ng-transclude></div>' +
'</div>'
};

18. });

End to end test


1. it('should have transcluded', function() {

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.

<a href="Book/Moby/ch/1">Moby: Ch1</a> |


<a href="Book/Gatsby">Gatsby</a> |

13.
14.

<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |


<a href="Book/Scarlet">Scarlet Letter</a><br/>

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.

// configure html5 to get links working on jsfiddle

12. $locationProvider.html5Mode(true);
13. });
14.
15. function MainCntl($scope, $route, $routeParams, $location) {
16.
17.

$scope.$route = $route;
$scope.$location = $location;

18. $scope.$routeParams = $routeParams;


19. }
20.
21. function BookCntl($scope, $routeParams) {
22.
23.

$scope.name = "BookCntl";
$scope.params = $routeParams;

24. }
25.
26. function ChapterCntl($scope, $routeParams) {
27. $scope.name = "ChapterCntl";
28. $scope.params = $routeParams;
29. }

End to end test


1. it('should load and compile correct template', function() {
2.
3.

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.

expect(content).toMatch(/Chapter Id\: 1/);

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>

type {'text/ng-template'} 'text/ng-template'

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.

Content of the template.


</body>

10. </html>

End to end test


1. it('should load template defined inside script tag', function() {
2.
element('#tpl-link').click();
3.
expect(element('#tpl-content').text()).toMatch(/Content of the template/);
4. });

select

HTML SELECT angular .

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>

ngModel {string} angular .

name(optional) {string=} ,
.

required(optional) {string=}
, .

ngRequired(optional) {string=} required


required , ngRequired true.
ngRequired required
required.

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.

Name: <input ng-model="color.name">


[<a href ng-click="colors.splice($index, 1)">X</a>]

13.
14.

</li>
<li>

15.
16.

[<a href ng-click="colors.push({})">add</a>]


</li>

17.
18.

</ul>
<hr/>

19.
20.

Color (null not allowed):


<select ng-model="color" ng-options="c.name for c in colors"></select><br>

21.
22.

Color (null allowed):

23.
24.

<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">

25.
26.

<option value="">-- chose color --</option>


</select>

27.
28.

</span><br/>

29.
30.

Color grouped by shade:


<select ng-model="color" ng-options="c.name group by c.shade for c in colors
">

31.

</select><br/>

32.
33.
34.
35.

Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>


<hr/>

36.
37.

Currently selected: {{ {selected_color:color} }}


<div style="border:solid 1px black; height:20px"

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. }

End to end test


1. it('should check ng-options', function() {
2.
expect(binding('{selected_color:color}')).toMatch('red');
3.
4.

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

HTML textarea angular .


, input .

, 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

ngModel {string} angular .


name(optional) {string=} ,
.

required(optional) {string=} required


, .

ngRequired(optional) {string=}
required required , ngRequired
true. ngRequired required
required.

ngMinlength(optional) {number=} minlength


, .

ngMaxlength(optional) {number=} maxlength


, .

ngPattern(optional) {string=} pattern



/regexp/ regexp
.

ngChange(optional) {string=} Angular ,


.

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.

<input type="number" ng-model="amount"> <br>

10.
11.

default currency symbol ($): {{amount | currency}}<br>


custom currency identifier (USD$): {{amount | currency:"USD$"}}

12.
13.

</div>
</body>

14. </html>

Script.js
1. function Ctrl($scope) {
2.
$scope.amount = 1234.56;
3. }

End to end test


1. it('should init with 1234.56', function() {
2.
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

.
:

'yyyy': 4 (, 1 => 0001, 2010 => 2010)


'yy': 2 (00-99). (, 2001 => 01, 2010 => 10)
'y': 1 (, 1 => 1, 199 => 199)
'MMMM': (January-December)
'MMM': (Jan-Dec)
'MM': , (01-12)
'M': , (1-12)
'dd': , (01-31)
'd': , (1-31)
'EEEE': ,(Sunday-Saturday)
'EEE': , (Sun-Sat)
'HH': , (00-23)
'H': (0-23)
'hh': , 12- (01-12)
'h': 12- (1-12)
'mm': (00-59)
'm': (0-59)

'ss': (00-59)
's': (0-59)
'a': am/pm 12- .
'Z': 4 ( ), ( ) (-1200+1200)

'medium': 'MMM d, y h:mm:ss a' en_US (, Sep 3, 2010


12:05:08 pm)
'short': 'M/d/yy h:mm a' en_US (, 9/3/10 12:05 pm)
'fullDate': 'EEEE, MMMM d,y' en_US (, Friday,
September 3, 2010)
'longDate': 'MMMM d, y' en_US (, September 3, 2010)
'mediumDate': 'MMM d, y' en_US (, Sep 3, 2010)
'shortDate': 'M/d/yy' en_US (, 9/3/10)
'mediumTime': 'h:mm:ss a' en_US (, 12:05:08 pm)
'shortTime': 'h:mm a' en_US ( 12:05 pm)

.
(, "h 'in the morning'").
, (, "h
o''clock").

HTML

{{ date_expression | date[:format] }}

JavaScript

$filter('date')(date[, format])

date {(Date|number|string)} : Date,


( ) ISO
8601 (, yyyy-MM-ddTHH:mm:ss.SSSZ yyyy-MM-ddTHH:mmZ, yyyyMM-dd yyyyMMddTHHmmssZ). ( )
, .

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.

<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:


{{1288323623006 | date:'medium'}}<br>

9.
10.

<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:


{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>

11.
12.

<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:


{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>

13. </body>
14. </html>

End to end test


1. it('should format date', function() {
2.
3.

expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);

4.
5.

expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).


toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);

6.
7.

expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).


toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);

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.

<div ng-init="friends = [{name:'John', phone:'555-1276'},


{name:'Mary', phone:'800-BIG-MARY'},

9.
10.

{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},

11.
12.

{name:'Julie', phone:'555-8765'}]"></div>

13.
14.
15.
16.

Search: <input ng-model="searchText">


<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText">

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.

Name only <input ng-model="search.name"><br>


Phone only <input ng-model="search.phone"><br>

25.
26.

<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>

27.
28.

<tr ng-repeat="friend in friends | filter:search">


<td>{{friend.name}}</td>

29.
30.

<td>{{friend.phone}}</td>
</tr>

31.
32.

</table>
</body>

33. </html>

End to end test


1. it('should search across all fields when filtering with a string', function() {
2.
3.

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.

expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.nam


e')).

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)

object {*} JavaScript ( )


.

{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.

<pre>{{ {'name':'value'} | json }}</pre>


</body>

9. </html>

End to end test


1. it('should jsonify filtered objects', function() {
2.
expect(binding("{'name':'value'}")).toMatch(/\{\n

"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.

<p>Output: {{ numbers | limitTo:limit }}</p>


</div>

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. }

End to end test


1. it('should limit the numer array to first three items', function() {
2.
3.

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.

Enter number: <input ng-model='val'><br>


Default formatting: {{val | number}}<br>

11.
12.

No fractions: {{val | number:0}}<br>


Negative number: {{-val | number:4}}

13.
14.

</div>
</body>

15. </html>

Script.js
1. function Ctrl($scope) {
2.
$scope.val = 1234.56789;
3. }

End to end test


1. it('should format numbers', function() {
2.
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.

1. filter:orderBy(array, expression[, reverse]);

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.

<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>


<hr/>

11.
12.

[ <a href="" ng-click="predicate=''">unsorted</a> ]


<table class="friend">

13.
14.

<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>

15.
16.

(<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th>


<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Nu

17.

mber</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></t
h>

18.

</tr>

19.
20.

<tr ng-repeat="friend in friends | orderBy:predicate:reverse">


<td>{{friend.name}}</td>

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.

{name:'Mary', phone:'555-9876', age:19},


{name:'Mike', phone:'555-4321', age:21},

6.
7.

{name:'Adam', phone:'555-5678', age:35},


{name:'Julie', phone:'555-8765', age:29}]

8.
$scope.predicate = '-age';
9. }

End to end test


1. it('should be reverse ordered by aged', function() {
2.

expect(binding('predicate')).toBe('-age');

3.

expect(repeater('table.friend', 'friend in friends').column('friend.age')).

4.

toEqual(['35', '29', '21', '19', '10']);

5.
6.

expect(repeater('table.friend', 'friend in friends').column('friend.name')).


toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);

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.

expect(repeater('table.friend', 'friend in friends').column('friend.name')).


toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);

13.
14.

expect(repeater('table.friend', 'friend in friends').column('friend.age')).


toEqual(['35', '10', '29', '19', '21']);

15.
16.

element('.doc-example-live a:contains("Phone")').click();

17.
18.

expect(repeater('table.friend', 'friend in friends').column('friend.phone')).


toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);

19.
20.

expect(repeater('table.friend', 'friend in friends').column('friend.name')).


toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);

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=} ,
. :

{number=} capacity LRU.

{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.

<input ng-model="name"> <br>


<textarea ng-model="html"></textarea> <br>

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}}';

End to end test


1. it('should auto compile', function() {
2.
3.

expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');

4.
expect(element('div[compile]').text()).toBe('Angular!');
5. });

1. $compile(element, transclude, maxPriority);

element {string|DOMElement} HTML


.

transclude {function(angular.Scope[, cloneAttachFn]}


.

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

jQuery (lite)-, window.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.

1. $http({method: 'GET', url: '/someUrl'}).


2.
success(function(data, status, headers, config) {
3.
4.
5.
6.
7.
8.
9.

//
//
}).
error(function(data, status, headers, config) {
// ,
//
});

$http promise,
then ,
. API
.
200 299 ,
success. ,
, XMLHttpRequest ,
error .

$http HTTP URL,


POST/PUT ,
:

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 , ,
, .

, $q and deferred/promise APIs.


, ,
,
http , ,
. promise apis
, .
, $httpProvider
$httpProvider.responseInterceptors.
( ) promise
promise.
1. //
2. $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
3.
4.

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.

Cross Site Request Forgery (XSRF)


XSRF ,
. Angular XSRF.
XHR , $http XSRF-TOKEN
HTTP X-XSRF-TOKEN. JavaScript,
, , XHR JavaScript
.

,
JavaScript XSRF-TOKEN HTTP GET .
XHR , HTTP
X-XSRF-TOKEN, .
( ,
JavaScript ).
.

$httpBackend
$browser
$cacheFactory
$rootScope
$q
$injector

1. $http(config);

config {object} .
:

method {string} HTTP (, 'GET', 'POST', ..)


url {string} URL
.
params {Object.<string|Object>} ,
?key1=value1&key2=value2 url. ,
JSON.
data {string|Object} .
headers {Object} , HTTP ,
.
transformRequest {function(data, headersGetter)|Array.<function(data,
headersGetter)>} .
http (
) .
transformResponse {function(data, headersGetter)|Array.<function(data,
headersGetter)>} .
http (
) .
cache {boolean|Cache} true, $http
GET ,
$cacheFactory, .
timeout {number} .
withCredentials - {boolean} withCredentials
XHR .

{HttpPromise} promise then


:success error. then ,
, ,
, . success error
,
.
then. :

data {string|Object}
.
status {number} HTTP .
headers {function([headerName])} .
config {Object} ,
.

delete(url, config)

DELETE.
:

url {string} URL

config(optional) {Object=}

:
{HttpPromise}

get(url, config)

GET.
:

url {string} URL

config(optional) {Object=}

:
{HttpPromise}

head(url, config)

HEAD.
:

url {string} URL

config(optional) {Object=}

:
{HttpPromise}

jsonp(url, config)

JSONP.
:

url {string} URL


. JSON_CALLBACK.

config(optional) {Object=}

:
{HttpPromise}

post(url, data, config)

POST.
:

url {string} URL

data {*}

config(optional) {Object=}

{HttpPromise} Future object

put(url, data, config)

PUT.
:

url {string} URL


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.

<input type="text" ng-model="url" size="80"/>


<button ng-click="fetch()">fetch</button><br>

15.
16.

<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>


<button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callb

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.

<pre>http response data: {{data}}</pre>

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.

$http({method: $scope.method, url: $scope.url, cache: $templateCache}).

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.

$scope.updateModel = function(method, url) {


$scope.method = method;

22.
23.

$scope.url = url;
};

24. }

End to end test


1. it('should make an xhr GET request', function() {
2.
element(':button:contains("Sample GET")').click();
3.
4.

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} .

mustHaveExpression(optional) {boolean=} true,


, .
, ,
null.

{function(context)} ,
. :

context: , .

endSymbol()

, . }}.
$interpolateProvider#endSymbol .
:
{string} .

startSymbol()

, . {{.
$interpolateProvider#startSymbol .
:
{string} .

$locale

$locale Angular.
api:

id {string} (, en-us)

$location

$location URL ( window.location)


URL . URL
$location $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>=} ,

paramValue(optional) {string=} search ,


paramValue .
null, .

:
{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.

<input type="text" ng-model="message"/>


<button ng-click="$log.log(message)">log</button>

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.

CommonJS Promise promise ,


,
.
, deferred promise API
try, catch throw .
1. // , `$q` `scope`,
2. // (
).
3.
4. function asyncGreet(name) {
5.
6.

var deferred = $q.defer();

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);

19. return deferred.promise;


20. }
21.
22. var promise = asyncGreet('Robin Hood');
23. promise.then(function(greeting) {
24. alert('Success: ' + greeting);
25. }, function(reason) {
26. alert('Failed: ' + reason);
27. });

, .
promise deferred API.
promise api ,
(CPS) .
Q ,
promise.

Deferred API
deferred $q.defer().

deferred Promise
.

resolve(value) promise value. value


$q.reject, promise .
reject(reason) promise reason.
$q.reject.

promise {Promise} promise deferred.

Promise API
promise
deferred.promise.
promise
(deferred) , .

then(successCallback, errorCallback) , promise


, ,
.
.
promise,
successCallback errorCallback.

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 ,
.

1. it('should simulate promise', inject(function($q, $rootScope) {


2.
3.

var deferred = $q.defer();


var promise = deferred.promise;

4.
5.

var resolvedValue;

6.
7.

promise.then(function(value) { resolvedValue = value; });


expect(resolvedValue).toBeUndefined();

8.
9.

// promise

10.
11.

deferred.resolve(123);
// , 'then' .

12.
13.

// , promise API ,
// .

14.
15.

expect(resolvedValue).toBeUndefined();

16.
17.

// promise 'then' $apply().


$rootScope.$apply();

18. expect(resolvedValue).toEqual(123);
19. });

$rootScope

all(promises)

promise promise, promise


.
:

promises {Array.<Promise>} promise.

{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 , .
:

value {*} promise

{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} .

rejection {Route} promise. promise.

$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.

<a href="Book/Scarlet">Scarlet Letter</a><br/>

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.

// I will cause a 1 second delay


delay: function($q, $timeout) {

8.
9.

var delay = $q.defer();


$timeout(delay.resolve, 1000);

10.
11.

return delay.promise;
}

12.
13.

}
});

14.
15.

$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',

16.
17.

controller: ChapterCntl
});

18.
19.

// configure html5 to get links working on jsfiddle

20. $locationProvider.html5Mode(true);
21. });
22.
23. function MainCntl($scope, $route, $routeParams, $location) {
24.
25.

$scope.$route = $route;
$scope.$location = $location;

26. $scope.$routeParams = $routeParams;


27. }
28.
29. function BookCntl($scope, $routeParams) {
30.
31.

$scope.name = "BookCntl";
$scope.params = $routeParams;

32. }
33.
34. function ChapterCntl($scope, $routeParams) {
35. $scope.name = "ChapterCntl";
36. $scope.params = $routeParams;
37. }

End to end test


1. it('should load and compile correct template', function() {
2.
3.

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.

expect(content).toMatch(/Chapter Id\: 1/);

8.
9.

element('a:contains("Scarlet")').click();
sleep(2); // promises are not part of scenario waiting

10.

content = element('.doc-example-live [ng-view]').text();

11.

expect(content).toMatch(/controller\: BookCntl/);

12. expect(content).toMatch(/Book Id\: Scarlet/);


13. });

$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

1. $timeout(fn[, delay][, invokeApply]);

Parameters

fn {function()} .

delay(optional=0) {number=} .

invokeApply(optional=true) {boolean=} false


, fn $apply.

{Promise} Promise . promise


fn.

Methods
cancel(promise)

, promise. promise
.
:

promise(optional) {Promise=} Promise $timeout.

:
{boolean} true, .

$window

window. window JavaScript,


, ..
. angular $window, ..
, .
,
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.

<input ng-init="$window = $service('$window'); greeting='Hello World!'" type="


text" ng-model="greeting" />
<button ng-click="$window.alert(greeting)">ALERT</button>
</body>

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. var parent = $rootScope;


2. var child = parent.$new();
3.
4. parent.salutation = "Hello";
5. child.name = "World";
6. expect(child.salutation).toEqual('Hello');
7.
8. child.salutation = "Welcome";
9. expect(child.salutation).toEqual('Welcome');
10. expect(parent.salutation).toEqual('Hello');

1. Scope([providers][, instanceCache]);

providers(optional) {Object.<string, function()>=}


, .
ng.

instanceCache(optional) {Object.<string, *>=}


, / ,
providers. -,
.

:
{Object} .

$apply(exp)

$apply() angular angular .


( , DOM , setTimeout, XHR ).
angular ,
, ,
.

$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().
:

exp(optional) {(string|function())=} angular .

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);

expression(optional) {(string|function())=} angular,


.

string: , .
function(scope): ,
.

:
{*} .

$evalAsync(expression)

.
$evalAsync , , :

(
DOM).
$digest expression.

, ,
$exceptionHandler.
:

expression(optional) {(string|function())=} angular


.

string: .
function(scope): ,
.

$new(isolate)

.
$digest() $digest().
$destroy().
$destroy() ,
, ,
, .
:

isolate {boolean} true,


.
.
, ,
.

:
{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} .

listener {function(event, args...)} .

:
{function()} ,
.

$watch(watchExpression, listener, objectEquality)

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

,
, :

, ( ) required, url email),


, ,
.

NgModelController

NgModelController API ng-model.


, , CSS, .
DOM DOM.
NgModelController ,
DOM, NgModelController .
NgModelController
. ,
(contenteditable, ng-model, required)
.

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.

border: 1px solid black;


background-color: white;

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.

require: '?ngModel', // get a hold of NgModelController


link: function(scope, element, attrs, ngModel) {

7.
8.

if(!ngModel) return; // do nothing if no ng-model

9.
10.

// Specify how UI should be updated


ngModel.$render = function() {

11.
12.

};

13.
14.

// Listen for change events to enable binding

15.
16.

element.bind('blur keyup change', function() {


scope.$apply(read);

17.
18.

});
read(); // initialize

19.
20.

// Write data to the model

21.
22.

function read() {
ngModel.$setViewValue(element.html());

element.html(ngModel.$viewValue || '');

23.
24.
25.
26.

}
}
};
});

End to end test


1. it('should data-bind and become invalid', function() {

2.

var contentEditable = element('[contenteditable]');

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).

.
:

validationErrorKey {string} . validationErrorKey


$error[validationErrorKey]=isValid,
. validationErrorKey
, CSS.
: myError ng-valid-my-error ng-invalid-my-error
, {{someForm.someControl.$error.myError}} .

isValid {boolean} true, valid, false 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.

1. angular.bind(self, fn, args);

self {Object} , fn .

fn {function()} .

args {...*} , fn.

{function()} , fn
.

angular.bootstrap

angular.

: Bootstrap

1. angular.bootstrap(element[, modules]);

element {Element} DOM , angular.

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.

{*} destination, destination .

angular.element

DOM HTML jQuery. angular.element


jQuery, jQuery , ,
Angular jQuery ( jqLite).

jQuery jqLite,
DOMContentLoaded.
jqLite , API- jQuery , Angular
DOM. jqLite -
, jQuery API - ,
.
: , Angular jQuery
jqLite; DOM .

Angular jQuery lite :

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() .

inheritedData() , data(), DOM


.

1. angular.element(element);

element {string|DOMElement} HTML DOM ,


jQuery.

{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.

1. var values = {name: 'misko', gender: 'male'};


2. var log = [];
3. angular.forEach(values, function(value, key){
4.
this.push(key + ': ' + value);
5. }, log);
6. expect(log).toEqual(['name: misko', 'gender:male']);

1. angular.forEach(obj, iterator[, context]);

obj {Object|Array} .

iterator {Function} .

context(optional) {Object=} ,
( this).

{Object|Array} obj.

angular.fromJson

JSON.


1. angular.fromJson(json);

json {string} JSON .

{Object|Array|Date|string|number} .

angular.identity

.
.

1. function transformer(transformationFn, value) {


2.
return (transformationFn || identity)(value);
3. };

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 {*} .

{boolean} True, value .

angular.isDate

, value .

1. angular.isDate(value);

value {*} .

{boolean} True, value .

angular.isDefined

, .

1. angular.isDefined(value);

value {*} .

{boolean} True, value .

angular.isElement

, DOM ( jQuery ).

1. angular.isElement(value);

value {*} .

{boolean} True, value DOM ( jQuery ).

angular.isFunction

, .

1. angular.isFunction(value);

value {*} .

{boolean} True, value .

angular.isNumber

, .

1. angular.isNumber(value);

value {*} .

{boolean} True, value .

angular.isObject

, . typeof JavaScript, null


.

1. angular.isObject(value);

value {*} .

{boolean} True, value , null.

angular.isString

, .

1. angular.isString(value);

value {*} .

{boolean} True, value .

angular.isUndefined

, .

1. angular.isUndefined(value);

value {*} .

{boolean} True, 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. });

, ::

1. var injector = angular.injector(['ng', 'MyModule'])

, ngApp angular.bootstrap
.


1. angular.module(name[, requires], configFn);

name {!string} .

requires(optional) {Array.<string>=} ,
. , .

configFn {Function} .
Module#config().

{module} angular.Module api.

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]);

obj {Object|Array|Date|string|number} JSON.

pretty(optional) {boolean=} true, JSON


.

{string} JSON, obj.

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.

it('should capture log messages and exceptions', function() {

5.

module(function($exceptionHandlerProvider) {

6.

$exceptionHandlerProvider.mode('log');

7.
8.

});

9.
10.

inject(function($log, $exceptionHandler, $timeout) {


$timeout(function() { $log.log(1); });

11.
12.

$timeout(function() { $log.log(2); throw 'banana peel'; });


$timeout(function() { $log.log(3); });

13.
14.

expect($exceptionHandler.errors).toEqual([]);
expect($log.assertEmpty());

15.
16.

$timeout.flush();
expect($exceptionHandler.errors).toEqual(['banana peel']);

17.
18.

expect($log.log.logs).toEqual([[1], [2], [3]]);


});

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(...)

strict unit tests

loose (black-box) unit testing

(. )

, ,
.
,
.
,
, ,
. .

HTTP

$httpBackend .
,
, , .
, , .
$httpBackend flush(),
,
api , .

$httpBackend
1. //

2. function MyController($scope, $http) {


3.
$http.get('/auth.py').success(function(data) {
4.
5.

$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.

var controller = scope.$new(MyController);


$httpBackend.flush();

38. });
39.
40.
41. it('should send msg to server', function() {
42.
43.

// ,
//

44.
45.

// $httpBackend ,
//

46.
47.

$httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');

48.
49.

var controller = scope.$new(MyController);


$httpBackend.flush();

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.

$httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {


// , ,
//

61.

return headers['Authorization'] == 'xxx';

62.

}).respond(201, '');

63.
64.

var controller = scope.$new(MyController);

65.
66.

controller.saveMessage('whatever');
$httpBackend.flush();

67. });

Methods
expect(method, url, data, headers)

.
:

method {string} HTTP .

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {(Object|function(Object))=} HTTP


http true
.

:
{requestHandler} , respond,
.

respond {function([status,] data[, headers])|function(function(method,


url, data, headers)} respond
, , ,
(), () ().

expectDELETE(url, headers)

DELETE.
expect().
:

url {string|RegExp} HTTP url.

headers(optional) {Object=} HTTP .

:
{requestHandler} respond,
.

expectGET(url, headers)

GET. expect().
:

url {string|RegExp} HTTP url.

headers(optional) {Object=} HTTP .

:
{requestHandler} , respond,
.

expectHEAD(url, headers)

HEAD. expect().
:

url {string|RegExp} HTTP url.

headers(optional) {Object=} HTTP .

:
{requestHandler} , respond,
.

expectJSONP(url)

JSONP. expect().
:

url {string|RegExp} HTTP url.

:
{requestHandler} , respond,
.

expectPATCH(url, data, headers)

PATCH. expect().
:

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {Object=} HTTP .

:
{requestHandler} , respond,
.

expectPOST(url, data, headers)

POST. expect().
:

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {Object=} HTTP .

:
{requestHandler} , respond,
.

expectPUT(url, data, headers)

PUT. expect().
:

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {Object=} HTTP .

:
{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);

when(method, url, data, headers)

method {string} HTTP .

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {(Object|function(Object))=} HTTP


http true,
.

:
{requestHandler} , respond,
.

respond {function([status,] data[, headers])|function(function(method,


url, data, headers)} respond
,
(), () ().

whenDELETE(url, headers)

DELETE.
when().
:

url {string|RegExp} HTTP url.

headers(optional) {(Object|function(Object))=} HTTP .

:
{requestHandler} , respond,
.

whenGET(url, headers)

GET.
when().
:

url {string|RegExp} HTTP url.

headers(optional) {(Object|function(Object))=} HTTP .

:
{requestHandler} , respond,
.

whenHEAD(url, headers)

HEAD.
when().
:

url {string|RegExp} HTTP url.

headers(optional) {(Object|function(Object))=} HTTP .

:
{requestHandler} , respond,
.

whenJSONP(url)

JSONP.
when().
:

url {string|RegExp} HTTP url.

:
{requestHandler} , respond,
.

whenPOST(url, data, headers)

POST.
when().
:

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {(Object|function(Object))=} HTTP .

:
{requestHandler} , respond,
.

whenPUT(url, data, headers)

PUT.
when().
:

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {(Object|function(Object))=} HTTP .

:
{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} (
)

timestamp {(number|string)} UNIX

UTC

!!!! !!!!! Date


, . , TzDate Date
.
, , ..
, .
: "Date.prototype.foo
Object".

1. var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');


2. newYearInBratislava.getTimezoneOffset() => -60;
3. newYearInBratislava.getFullYear() => 2010;
4. newYearInBratislava.getMonth() => 0;
5. newYearInBratislava.getDate() => 1;
6. newYearInBratislava.getHours() => 0;
7. newYearInBratislava.getMinutes() => 0;

auto

$injector

$injector provider,
, .
:

1. var $injector = angular.injector();


2. expect($injector.get('$injector')).toBe($injector);
3. expect($injector.invoke(function($injector){
4.
return $injector;
5. }).toBe($injector);

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} .

invoke(fn, self, locals)

$injector.
:

fn {!function} .
.

self(optional) {Object=} this .

locals(optional) {Object=} . ,
$injector,
.

:
{*} , .

$provide

$provide $injector. ,
.
Provider.
$get(). $get
. ,
.

1. function GreetProvider() {

2.

var salutation = 'Hello';

3.
4.
5.

this.salutation = function(text) {
salutation = text;

6.
7.

};

8.
9.

this.$get = function() {
return function (name) {

10.
11.

return salutation + ' ' + name + '!';


};

12. };
13. }
14.
15. describe('Greeter', function(){
16.
17.

beforeEach(module(function($provide) {

18.
19.

$provide.provider('greet', GreetProvider);
}));

20.
21.

it('should greet', inject(function(greet) {

22.
23.

expect(greet('angular')).toEqual('Hello angular!');
}));

24.
25.

it('should allow configuration of salutation', function() {

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} .

$getFn {function()} $getFn .


$provide.provider(name, {$get: $getFn}).

:
{Object}

provider(name, provider)

.
.
:

name {string} . :
name + 'Provider'.

provider {(Object|function())} :

Object: $get. $get


$injector.invoke(), .
Constructor:
$injector.instantiate(), object.

:
{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

HTTP end-to-end backend-less


$http.

: ,
unit-testing $httpBackend mock.

when api (whenGET, whenPOST, ..)
$httpBackend (,
).
, end-to-end , ,
, api ,
, (,
).
passThrough when respond.
, ,
. e2e $httpBackend
, XMLHttpRequest.
http ,
ngMockE2E :

1. myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);


2. myAppDev.run(function($httpBackend) {
3.
phones = [{name: 'phone1'}, {name: 'phone2'}];
4.
5.

//

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)

.
:

method {string} HTTP .

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {(Object|function(Object))=} HTTP


http true,
.

{requestHandler} , respond passThrough,


.

respond {function([status,] data[, headers])|function(function(method,


url, data, headers)}
, , (),
() ().
passThrough {function()} ,
passThrough, ( XHR
).

whenDELETE(url, headers)

DELETE.
when().
:

url {string|RegExp} HTTP url.

headers(optional) {(Object|function(Object))=} HTTP .

:
{requestHandler} , respond passThrough,
.

whenGET(url, headers)

GET.
when().
:

url {string|RegExp} HTTP url.

headers(optional) {(Object|function(Object))=} HTTP .

:
{requestHandler} , respond passThrough,
.

whenHEAD(url, headers)

HEAD.
when().
:

url {string|RegExp} HTTP url.

headers(optional) {(Object|function(Object))=} HTTP .

:
{requestHandler} , respond passThrough,
.

whenJSONP(url)

JSONP.
when().
:

url {string|RegExp} HTTP url.

:
{requestHandler} , respond passThrough,
.

whenPATCH(url, data, headers)

PATCH.
when().
:

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {(Object|function(Object))=} HTTP .

:
{requestHandler} , respond passThrough,
.

whenPOST(url, data, headers)

POST.
when().
:

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {(Object|function(Object))=} HTTP .

:
{requestHandler} , respond passThrough,
.

whenPUT(url, data, headers)

PUT.
when().
:

url {string|RegExp} HTTP url.

data(optional) {(string|RegExp)=} HTTP .

headers(optional) {(Object|function(Object))=} HTTP .

{requestHandler} , respond passThrough,


.

ngResource

$resource

, ,
RESTful.
,
, $http.

$resource angular-resource.js
Angular. Google CDN,
code.angularjs.org.
:
angular.module('app', ['ngResource']);
!

$http

1. $resource(url[, paramDefaults][, actions]);

url {string} URL


:, /user/:username. URL
(, http://example.com:8080/api),
, : $resource('http://example.com\\:8080/api').

paramDefaults(optional) {Object=} url.


.
url, - url
?, url .
/path/:verb {verb:'greet', salutation:'Hello'}
URL /path/greet?salutation=Hello. @,
( GET
).

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)
:

1. var User = $resource('/user/:userId', {userId:'@id'});


2. var user = User.get({userId:123}, function() {
3.
user.abc = true;
4.
user.$save();
5. });

, $resource, (
isArray). ,
. , ..
, . ,
, , ,
. ,
.

HTTP GET "" : Resource.([parameters], [success], [error])


-GET "" : Resource.([parameters], postData, [success],
[error])
-GET : .$action([parameters], [success],
[error])


1. // CreditCard

2. var CreditCard = $resource('/user/:userId/card/:cardId',


3. {userId:123, cardId:'@id'}, {
4.
5.

charge: {method:'POST', params:{charge:true}}


});

6.
7. //
8. var cards = CreditCard.query(function() {
9.
// GET: /user/123/card
10.
11.

// : [ {id:456, number:'1234', name:'Smith'} ];

12.
13.

var card = cards[0];


// CreditCard

14.
15.

expect(card instanceof CreditCard).toEqual(true);


card.name = "J. Smith";

16.
17.

// GET
card.$save();

18.
19.

// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}


// : {id:456, number:'1234', name: 'J. Smith'};

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) .

1. var User = $resource('/user/:userId', {userId:'@id'});


2. var user = User.get({userId:123}, function() {
3.
4.

user.abc = true;
user.$save();

5. });

, get, query ,
, ,
$http ,
:

1. var User = $resource('/user/:userId', {userId:'@id'});


2. User.get({userId:123}, function(u, getResponseHeaders){
3.
u.abc = true;
4.
5.
6.
7.

u.$save(function(u, putResponseHeaders) {
//u =>

//putResponseHeaders => $http


});

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.

<h1 style="font-size: 15px;">


<img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:
30px;"/>

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.

<div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px


;">

20.

<img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width


:30px;"/>

21.

<a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.c


ontent | html}}

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.

activity.replies = this.Activity.replies({userId:this.userId, activityId:activ


ity.id});

16. }
17. };
18. BuzzController.$inject = ['$resource'];

ngSanitize

ngBindHtml

, expression
$sanitize innerHTML .
$sanitize.

1. <ANY ng-bind-html="{expression}">

2.

...

3. </ANY>

1. <ANY class="ng-bind-html: {expression};">


2.
...
3. </ANY>

ngBindHtml {expression} .

linky

html.
http/https/ftp/mailto email .

HTML

<span ng-bind-html="linky_expression | linky"></span>

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.

Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>


<table>
<tr>

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>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>

20.
21.

</td>
<td>

22.
23.

<div ng-bind-html="snippet | linky"></div>


</td>

24.
25.

</tr>
<tr id="escaped-html">

26.
27.

<td>no filter</td>
<td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</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.

'Pretty text with some links:\n'+


'http://angularjs.org/,\n'+

5.
6.

'mailto:us@somewhere.org,\n'+
'another@somewhere.org,\n'+

7.
8. }

'and one more: ftp://127.0.0.1/.';

End to end test


1. it('should linkify the snippet with urls', function() {
2.
expect(using('#linky-filter').binding('snippet | linky')).
3.
4.

toBe('Pretty text with some links:&#10;' +


'<a href="http://angularjs.org/">http://angularjs.org/</a>,&#10;' +

5.
6.

'<a href="mailto:us@somewhere.org">us@somewhere.org</a>,&#10;' +
'<a href="mailto:another@somewhere.org">another@somewhere.org</a>,&#10;'
+

7.

'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.');

8. });
9.
10. it ('should not linkify snippet without the linky filter', function() {
11. expect(using('#escaped-html').binding('snippet')).
12.
13.
14.

toBe("Pretty text with some links:\n" +


"http://angularjs.org/,\n" +
"mailto:us@somewhere.org,\n" +

15.

"another@somewhere.org,\n" +

16.

"and one more: ftp://127.0.0.1/.");

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>.');

23. expect(using('#escaped-html').binding('snippet')).toBe('new http://link.');


24. });

$sanitize

html. ( )
html. ,
, , ,
, , ,
HTML , .

1. $sanitize(html);

html {string} 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.

Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>


<table>

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>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</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>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</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>&lt;div ng-bind-html-unsafe="snippet"&gt;<br/>&lt;/div&gt;</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.

'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +


'snippet</p>';

6. }

End to end test


1. it('should sanitize the html snippet ', function() {
2.
3.

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.

toBe("&lt;p style=\"color:blue\"&gt;an html\n" +


"&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt
;\n" +

10.
11. });

"snippet&lt;/p&gt;");

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.

"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +


"snippet</p>");

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 &lt;b&gt;text&lt;

24.

/b&gt;");
expect(using('#html-unsafe-filter').binding("snippet")).toBe('new <b>text</b>');

25. });

Вам также может понравиться