Sei sulla pagina 1di 95

1

Angular Developer Guide


Downloaded from http://docs.angularjs.org/guide
may 25, 2013
1 Introducton...................................................................................................................6
1.1 Single-page / Round-trip Applications.......................................................................................................... 6
2 What Is Angular?........................................................................................................... 6
2.1 End-to-end solution............................................................................................................................................... 7
2.2 Angular Sweet Spot................................................................................................................................................ 7
2.3 An Introductory Angular Exaple................................................................................................................... 7
1.1.1 Source......................................................................................................................................................................... 8
1.1.2 Demo........................................................................................................................................................................... 8
2.! "#e $en o% Angular................................................................................................................................................. &
2.' (atc# a )resentation A*out Angular........................................................................................................... 1+
3 Bootstrap.....................................................................................................................10
3.1 Angular ,script- "ag.......................................................................................................................................... 1+
3.2 Autoatic Initiali.ation..................................................................................................................................... 11
3.3 /anual Initiali.ation........................................................................................................................................... 11
4 HTML o!p"l#r............................................................................................................ 12
!.1 0opiler.................................................................................................................................................................. 12
!.2 1irecti2e................................................................................................................................................................... 12
!.3 3nderstanding 4iew........................................................................................................................................... 13
$ onc#ptual o%#r%"#&................................................................................................... 14
'.1 Startup...................................................................................................................................................................... 1!
'.2 Runtie................................................................................................................................................................... 16
'.3 Scope......................................................................................................................................................................... 17
'.! 0ontroller................................................................................................................................................................ 15
'.' /odel........................................................................................................................................................................ 1&
'.6 4iew........................................................................................................................................................................... 1&
'.7 1irecti2es................................................................................................................................................................. 2+
1.1.3 Source...................................................................................................................................................................... 21
'.5 6ilters........................................................................................................................................................................ 21
1.2 /odules and t#e In7ector.................................................................................................................................. 22
'.& Angular 8aespace............................................................................................................................................ 23
6 In%o'"ng d"r#ct%#s (ro! HTML.....................................................................................23
6.1 String interpolation............................................................................................................................................. 2!
6.2 0opilation process9 and directi2e atc#ing........................................................................................... 2!
6.2.1 Reasons behind the compile/link separation......................................................................................... 25
6.3 (riting directi2es :s#ort 2ersion;................................................................................................................. 26
6.! (riting directi2es :long 2ersion;................................................................................................................... 26
6.4.1 Factor method................................................................................................................................................... 2!
6.4.2 Directi"e De#inition $b%ect............................................................................................................................. 2!
1
2
6.4.3 &ompile 'unction................................................................................................................................................. 2(
6.4.4 )inkin* 'unction.................................................................................................................................................. 3+
6.4.5 ,ttributes............................................................................................................................................................... 3+
6.' 3nderstanding "ransclusion and Scopes................................................................................................... 31
6.6 0reating 0oponents......................................................................................................................................... 32
) *+pr#ss"ons.................................................................................................................. 33
7.1 Angular Expressions 2s. <S Expressions...................................................................................................... 33
7.2 Exaple................................................................................................................................................................... 33
7.3 )roperty E2aluation............................................................................................................................................ 3!
!.3.1 For*i"in*................................................................................................................................................................ 35
!.3.2 -o &ontrol Flo. Statements.......................................................................................................................... 35
!.3.3 Filters....................................................................................................................................................................... 35
7.! "#e =.......................................................................................................................................................................... 3'
, -or!s...........................................................................................................................36
5.1 Siple %or............................................................................................................................................................ 36
5.2 3sing 0SS classes.................................................................................................................................................. 36
5.3 >inding to %or and control state................................................................................................................. 37
5.! 0usto 4alidation................................................................................................................................................ 3&
5.' Ipleenting custo %or controls :usingng/odel;.......................................................................... !+
. I1,n and L10n "n Angular/0...........................................................................................41
&.1 )ro2iding locale rules to Angular.................................................................................................................. !1
&.2 ?@otc#as?................................................................................................................................................................. !2
10 Int#rn#t *+plor#r co!pat1"l"t2.................................................................................. 42
1+.1 S#ort 4ersion....................................................................................................................................................... !2
1+.2 Aong 4ersion........................................................................................................................................................ !3
1+.2.1 /he 0ood -e.s.................................................................................................................................................. 44
1+.2.2 1hat happens i' 2 'ail to do this3............................................................................................................... 44
1+.3 0SS Styling o% 0usto "ag 8aes............................................................................................................... !!
11 What "s a Modul#?..................................................................................................... 4$
11.1 "#e >asics............................................................................................................................................................. !'
11.2 Recoended Setup....................................................................................................................................... !6
11.3 /odule Aoading B 1ependencies............................................................................................................... !6
11.3.1 &on#i*uration 4locks...................................................................................................................................... 4!
11.3.2 Run 4locks........................................................................................................................................................... 4!
11.3.3 Dependencies..................................................................................................................................................... 4!
11.3.4 ,snchronous )oadin*.................................................................................................................................. 48
11.! 3nit "esting.......................................................................................................................................................... !5
12 What ar# 0cop#s?.......................................................................................................4.
12.1 Scope c#aracteristics....................................................................................................................................... !&
12.2 Scope as 1ata-/odel........................................................................................................................................ !&
12.3 Scope Cierarc#ies.............................................................................................................................................. '+
12.! Retrie2ing Scopes %ro t#e 1D/................................................................................................................ '1
12.' Scope E2ents )ropagation.............................................................................................................................. '2
12.6 Scope Ai%e 0ycle.................................................................................................................................................. '2
2
3
12.6.1 Scopes and Directi"es..................................................................................................................................... 53
12.6.2 Directi"es that &reate Scopes..................................................................................................................... 53
12.6.3 &ontrollers and Scopes.................................................................................................................................. 54
12.6.4 Scope 5.atch 6er'ormance &onsiderations......................................................................................... 54
13 3#p#nd#nc2 In4#cton................................................................................................ $4
13.1 1I in a nuts#ell.................................................................................................................................................... '!
13.2 1ependency Annotation................................................................................................................................. ''
13.3 In%erring 1ependencies.................................................................................................................................. '6
13.! =in7ect Annotation............................................................................................................................................. '6
13.' Inline Annotation.............................................................................................................................................. '6
13.6 (#ere can I use 1IE.......................................................................................................................................... '7
13.6.1 D2 in controllers................................................................................................................................................ 5!
13.6.2 Factor methods............................................................................................................................................... 5!
14 A1out M5 "n Angular................................................................................................$)
1$ 6nd#rstand"ng th# !od#l co!pon#nt........................................................................$,
16 6nd#rstand"ng th# ontroll#r co!pon#nt.................................................................. $.
16.1 Setting up t#e initial state o% a scope o*7ect........................................................................................... '&
16.2 Adding >e#a2ior to a Scope D*7ect............................................................................................................ 6+
16.3 3sing 0ontrollers 0orrectly........................................................................................................................... 6+
16.! Associating 0ontrollers wit# Angular Scope D*7ects.......................................................................... 6+
16.4.1 &ontroller &onstructor and 7ethods 89ample.................................................................................... 6+
16.4.2 , Spic &ontroller 89ample......................................................................................................................... 6+
16.4.3 &ontroller 7ethod ,r*uments 89ample................................................................................................ 61
16.4.4 &ontroller 2nheritance 89ample................................................................................................................ 62
16.4.5 /estin* &ontrollers.......................................................................................................................................... 62
1) 6nd#rstand"ng th# 5"#& co!pon#nt.......................................................................... 63
1, *2* t#stng................................................................................................................. 64
15.1 D2er2iew............................................................................................................................................................... 6!
15.2 A)I........................................................................................................................................................................... 6'
1.3 sleep:seconds;...................................................................................................................................................... 6'
1.! *rowser:;.na2igate"o:url;............................................................................................................................... 66
1.' *rowser:;.na2igate"o:url9 %n;......................................................................................................................... 66
1.6 *rowser:;.reload:;............................................................................................................................................... 66
1.7 *rowser:;.window:;.#re%:;.............................................................................................................................. 66
1.5 *rowser:;.window:;.pat#:;............................................................................................................................. 66
1.& *rowser:;.window:;.searc#:;......................................................................................................................... 66
1.1+ *rowser:;.window:;.#as#:;.......................................................................................................................... 66
1.11 *rowser:;.location:;.url:;.............................................................................................................................. 66
1.12 *rowser:;.location:;.pat#:;........................................................................................................................... 66
1.13 *rowser:;.location:;.searc#:;...................................................................................................................... 66
1.1! *rowser:;.location:;.#as#:;.......................................................................................................................... 66
1.1' expect:%uture;.Fatc#erG............................................................................................................................... 66
1.16 expect:%uture;.not:;.Fatc#erG.................................................................................................................... 66
1.17 using:selector9 la*el;........................................................................................................................................ 66
3
4
1.15 *inding:nae;.................................................................................................................................................... 67
1.1& input:nae;.enter:2alue;.............................................................................................................................. 67
1.2+ input:nae;.c#ecH:;........................................................................................................................................ 67
1.21 input:nae;.select:2alue;............................................................................................................................. 67
1.22 input:nae;.2al:;.............................................................................................................................................. 67
1.23 repeater:selector9 la*el;.count:;................................................................................................................. 67
1.2! repeater:selector9 la*el;.row:index;.......................................................................................................... 67
1.2' repeater:selector9 la*el;.colun:*inding;.............................................................................................. 67
1.26 select:nae;.option:2alue;........................................................................................................................... 67
1.27 select:nae;.option:2alue19 2alue2...;..................................................................................................... 67
1.25 eleent:selector9 la*el;.count:;.................................................................................................................. 67
1.2& eleent:selector9 la*el;.clicH:;.................................................................................................................... 67
1.3+ eleent:selector9 la*el;.Iuery:%n;.............................................................................................................. 67
1.31 eleent:selector9 la*el;.Fet#odG:;.......................................................................................................... 65
1.32 eleent:selector9 la*el;.Fet#odG:2alue;............................................................................................... 65
1.33 eleent:selector9 la*el;.Fet#odG:Hey;................................................................................................... 65
1.3! eleent:selector9 la*el;.Fet#odG:Hey9 2alue;....................................................................................... 65
15.3 /atc#ers............................................................................................................................................................... 65
15.! Exaple................................................................................................................................................................. 6&
18.4.1 &onditional actions .ith element:...;.<uer:'n;.................................................................................. 6(
1. 6nd#rstand"ng Angular T#!plat#s..............................................................................)0
20 Wor'"ng &"th 00 "n Angular...................................................................................... )1
2+.1 0SS classes used *y angular.......................................................................................................................... 71
21 3ata B"nd"ng "n Angular..............................................................................................)1
21.1 1ata >inding in 0lassical "eplate Systes........................................................................................... 71
21.2 1ata >inding in Angular "eplates........................................................................................................... 72
22 6nd#rstand"ng Angular -"lt#rs.................................................................................... )2
23 r#atng Angular -"lt#rs..............................................................................................)2
24 6s"ng Angular -"lt#rs.................................................................................................. )3
2$ Angular 0#r%"c#s.........................................................................................................)4
26 6nd#rstand"ng Angular 0#r%"c#s.................................................................................)4
2) 6s"ng 7locaton.......................................................................................................... )$
27.1 (#at does it doE................................................................................................................................................ 7'
2!.1.1 &omparin* 5location to .indo..location............................................................................................. !5
2!.1.2 1hen should 2 use 5location3..................................................................................................................... !5
2!.1.3 1hat does it not do3....................................................................................................................................... !5
27.2 @eneral o2er2iew o% t#e A)I.......................................................................................................................... 76
2!.2.1 5location ser"ice con#i*uration................................................................................................................. !6
1.34.1 89ample con#i*uration.................................................................................................................................. !6
2!.2.2 0etter and setter methods............................................................................................................................ !6
27.3 Cas#*ang and C"/A' /odes...................................................................................................................... 77
2!.3.1 =ashban* mode :de'ault mode;................................................................................................................ !8
4
5
28 &ra.lin* our app.................................................................................................................................................. !8
28.1.1 =/7)5 mode...................................................................................................................................................... !8
25.2 0a2eats................................................................................................................................................................... 51
28.2.1 6a*e reload na"i*ation................................................................................................................................. 81
28.2.2 >sin* 5location outside o' the scope li'e?ccle.................................................................................... 82
28.2.3 5location.path:; and @ or / pre#i9es.......................................................................................................... 82
25.3 "esting wit# t#e =location ser2ice.............................................................................................................. 52
25.! /igrating %ro earlier Angular<S releases.............................................................................................. 52
28.4.1 &han*es to our code..................................................................................................................................... 82
28.4.2 /.o?.a bindin* to 5location................................................................................................................... 83
2. TML3"r#ct r#atng s#r%"c#s....................................................................................... ,4
2&.1 Registering Ser2ices......................................................................................................................................... 5!
2&.2 1ependencies...................................................................................................................................................... 5!
2&.3 Instantiating Angular Ser2ices..................................................................................................................... 5'
2&.! Ser2ices as singletons...................................................................................................................................... 5'
30 In4#ctng 0#r%"c#s "nto ontroll#r................................................................................,$
3+.1 Iplicit 1ependency In7ection..................................................................................................................... 56
31 Manag"ng 0#r%"c# 3#p#ndanc"#s................................................................................ ,)
32 T#stng Angular 0#r%"c#s.............................................................................................,,
33 6n"t T#stng................................................................................................................,.
33.1 It is all a*out 8D" ixing concerns........................................................................................................... 5&
33.1.1 1ith *reat po.er comes *reat responsibilit..................................................................................... (+
33.1.2 Dependenc 2n%ection..................................................................................................................................... (+
33.1.3 &ontrollers.......................................................................................................................................................... (2
33.1.4 Filters.................................................................................................................................................................... (3
33.1.5 Directi"es............................................................................................................................................................. (3
33.1.6 7ocks.................................................................................................................................................................... (4
33.1.! 0lobal State 2solation..................................................................................................................................... (4
33.2 )re%erred way o% "esting................................................................................................................................. &!
33.2.1 Aa"aScript/estDri"er...................................................................................................................................... (4
33.2.2 Aasmine................................................................................................................................................................. (4
33.2.3 Sample pro%ect.................................................................................................................................................. (4
Welcome to the angular Developer Guide. If you are here to learn the detail of how to ue
angular to develop we! app, you"ve come to the right place.
If you are completely or relatively unfamiliar with angular, you may want to chec# out one or
!oth of the following document !efore returning here to the Developer Guide$
Getting %tarted
&ngular 'utorial
5
6
1 Introduction
&ngular i pure client(ide technology, written entirely in )ava%cript. It wor# with the long(
eta!lihed technologie of the we! *+',-, .%%, and )ava%cript/ to ma#e the development
of we! app eaier and fater than ever !efore.
0ne important way that &ngular impli1e we! development i !y increaing the level of
a!traction !etween the developer and mot low(level we! app development ta#. &ngular
automatically ta#e care of many of thee ta#, including$
D0, ,anipulation
%etting 2p -itener and 3oti1er
Input 4alidation
5ecaue &ngular handle much of the wor# involved in thee ta#, developer can
concentrate more on application logic and le on repetitive, error(prone, lower(level coding.
&t the ame time that &ngular impli1e the development of we! app, it !ring relatively
ophiticated techni6ue to the client(ide, including$
%eparation of data, application logic, and preentation component
Data 5inding !etween data and preentation component
%ervice *common we! app operation, implemented a u!tituta!le o!7ect/
Dependency In7ection *ued primarily for wiring together ervice/
&n e8teni!le +',- compiler *written entirely in )ava%cript/
9ae of 'eting
'hee techni6ue have !een for the mot part a!ent from the client(ide for far too long.
1.1 Single-page / Round-trip Applications
:ou can ue &ngular to develop !oth ingle(page and round(trip app, !ut &ngular i
deigned primarily for developing ingle(page app. &ngular upport !rower hitory,
forward and !ac# !utton, and !oo#mar#ing in ingle(page app.
:ou normally wouldn"t want to load &ngular with every page change, a would !e the cae
with uing &ngular in a round(trip app. +owever, it would ma#e ene to do o if you were
adding a u!et of &ngular" feature *for e8ample, template to leverage angular" data(
!inding feature/ to an e8iting round(trip app. :ou might follow thi coure of action if you
were migrating an older app to a ingle(page &ngular app.
2 What Is Angular?
&ngular)% i a tructural framewor# for dynamic we! app. It let you ue +',- a your
template language and let you e8tend +',-" ynta8 to e8pre your application"
component clearly and uccinctly. 0ut of the !o8, it eliminate much of the code you
currently write through data !inding and dependency in7ection. &nd it all happen in
)ava%cript within the !rower ma#ing it an ideal partner with any erver technology.
&ngular i what +',- would have !een had it !een deigned for application. +',- i a
great declarative language for tatic document. It doe not contain much in the way of
creating application, and a a reult !uilding we! application i an e8ercie in what do I
have to do, so that I trick the browser in to doing what I want.
'he impedance mimatch !etween dynamic application and tatic document i often
olved a$
6
7
li!rary ( a collection of function which are ueful when writing we! app. :our code
i in charge and it call into the li!rary when it ee 1t. 9.g., jQuery.
framewor# ( a particular implementation of a we! application, where your code 1ll
in the detail. 'he framewor# i in charge and it call into your code when it need
omething app peci1c. 9.g., knockout, sproutcore, etc.
&ngular ta#e another approach. It attempt to minimi;e the impedance mimatch !etween
document centric +',- and what an application need !y creating new +',- contruct.
&ngular teache the !rower new ynta8 through a contruct we call directive. 98ample
include$
Data !inding a in {{}}.
D0, control tructure for repeating<hiding D0, fragment.
%upport for form and form validation.
&ttaching code(!ehind to D0, element.
Grouping of +',- into reua!le component.
2.1 End-to-end solution
&ngular trie to !e an end(to(end olution, when !uilding a we! application. 'hi mean it i
not a ingle piece in an overall pu;;le of !uilding a we! application, !ut an end(to(end
olution. 'hi ma#e &ngular opinionated a!out how a .=2D application hould !e !uilt.
5ut while it i opinionated, it alo trie to ma#e ure that it opinion i 7ut a tarting point,
which you can eaily change. &ngular come with the following out(of(the(!o8$
9verything you need to !uild a .=2D app in a coheive et$ data(!inding, !aic
templating directive, form validation, routing, deep(lin#ing, reua!le component,
dependency in7ection.
'eta!ility tory$ unit(teting, end(to(end teting, moc#, tet harnee.
%eed application with directory layout and tet cript a a tarting point.
2.2 Angular Sweet Spot
&ngular impli1e application development !y preenting a higher level of a!traction to the
developer. -i#e any a!traction, it come at a cot of >e8i!ility. In other word not every app
i a good 1t for &ngular. &ngular wa !uilt for the .=2D application in mind. -uc#ily .=2D
application repreent at leat ?0@ of the we! application. 5ut to undertand what
&ngular i good at one alo ha to undertand when an app i not a good 1t for &ngular.
Game, and G2I editor are e8ample of very intenive and tric#y D0, manipulation. 'hee
#ind of app are different from .=2D app, and a a reult are not a good 1t for &ngular. In
thee cae uing omething cloer to !are metal uch a jQuery may !e a !etter 1t.
2.3 An Introductory Angular Ea!ple
5elow i a typical .=2D application which contain a form. 'he form value are validated,
and are ued to compute the total, which i formatted to a particular locale. 'hee are ome
common concept which the application developer may face$
attaching data(model to the 2I.
writing, reading and validating uer input.
computing new value !aed on the model.
formatting output in a uer peci1c locale.
7
8
1.1.1 Source
9dit
inde8.html
cript.7
9nd to end tet
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. </head>
7. <ody>
8. <di! ng-controller=""n!oice#ntl">
9. <>"n!oice:</>
10. <r>
11. <r>
12. <tale>
13. <tr><td>$uantity</td><td>#ost</td></tr>
14. <tr>
15. <td><input type="numer" ng-pattern="/%d&/" step="1"
min="0" ng-model="'ty" re'uired ></td>
16. <td><input type="numer" ng-model="cost" re'uired
></td>
17. </tr>
18. </tale>
19. <hr>
20. <>(otal:</> ))'ty * cost + currency,,
21. </di!>
22. </ody>
23. </html>
1.1.2 "e!o
Invoice:
Quantity Cost

!"#irect

!"#irect
Total: A1?.?5
'ry out the -ive Breview a!ove, and then let" wal# through the e8ample and decri!e
what" going on.
In the <html> tag, we pecify that it i an &ngular application with the ng-app directive.
'he ng-app will caue &ngular to auto initiali;e your application.
<html ng-app>
We load &ngular uing the <script> tag$
8
$
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/?.?.?/angular.m
in.js"></script>
Crom the ng-model attri!ute of the <input> tag, &ngular automatically et up two(way
data !inding, and we alo demontrate ome eay input validation$
Quantity: <input type="number" ng-pattern="/\d+/" step="1" min="0"
ng-model="qty" required > Cost: <input type="number" ng-model="cost"
required >
'hee input widget loo# normal enough, !ut conider thee point$
When thi page loaded, &ngular !ound the name of the input widget
*qty and cost/ to varia!le of the ame name. 'hin# of thoe varia!le a the D,odelD
component of the ,odel(4iew(.ontroller deign pattern.
3ote that the +',- widget input ha pecial power. 'he input invalidate itelf !y
turning red when you enter invalid data or leave the the input 1eld !lan#. 'hee new
widget !ehavior ma#e it eaier to implement 1eld validation common in .=2D
application.
&nd 1nally, the myteriou {{ double curly braces }}$
Total: {{qty * cost | currency}}
'hi notation, {{ _expression_ }}, i &ngular mar#up for data(!inding. 'he e8preion
itelf can !e a com!ination of !oth an e8preion and a 1lter$ {{ expression |
filter }}. &ngular provide 1lter for formatting diplay data.
In the e8ample a!ove, the e8preion in dou!le(curly !race direct &ngular to D!ind the
data we got from the input widget to the diplay, multiply them together, and format the
reulting num!er into output that loo# li#e money.D
3otice that we achieved thi application !ehavior not !y calling &ngular method, nor !y
implementing application peci1c !ehavior a a framewor#. We achieved the !ehavior
!ecaue the !rower !ehaved more in line with what i needed for a dynamic we!
application rather then what i needed for a tatic document. &ngular ha lowered the
impedance mimatch to the point where no li!rary<framewor# call are needed.
2.# $he %en o& Angular
&ngular i !uilt around the !elief that declarative code i !etter than imperative when it
come to !uilding 2I and wiring oftware component together, while imperative code i
e8cellent for e8preing !uine logic.
It i a very good idea to decouple D0, manipulation from app logic. 'hi
dramatically improve the teta!ility of the code.
It i a really, really good idea to regard app teting a e6ual in importance to app
writing. 'eting dif1culty i dramatically affected !y the way the code i tructured.
It i an e8cellent idea to decouple the client ide of an app from the erver ide. 'hi
allow development wor# to progre in parallel, and allow for reue of !oth ide.
It i very helpful indeed if the framewor# guide developer through the entire
7ourney of !uilding an app$ from deigning the 2I, through writing the !uine logic, to
teting.
It i alway good to ma#e common ta# trivial and dif1cult ta# poi!le.
&ngular free you from the following pain$
=egitering call!ac#$ =egitering call!ac# clutter your code, ma#ing it hard to ee
the foret for the tree. =emoving common !oilerplate code uch a call!ac# i a good
thing. It vatly reduce the amount of )ava%cript coding you have to do, and it ma#e it
eaier to ee what your application doe.
$
1%
,anipulating +',- D0, programmatically$ ,anipulating +',- D0, i a
cornertone of &)&E application, !ut it" cum!erome and error(prone. 5y declaratively
decri!ing how the 2I hould change a your application tate change, you are freed
from low level D0, manipulation ta#. ,ot application written with &ngular never
have to programmatically manipulate the D0,, although you can if you want to.
,arhaling data to and from the 2I$ .=2D operation ma#e up the ma7ority of &)&E
application. 'he >ow of marhaling data from the erver to an internal o!7ect to an +',-
form, allowing uer to modify the form, validating the form, diplaying validation error,
returning to an internal model, and then !ac# to the erver, create a lot of !oilerplate
code. &ngular eliminate almot all of thi !oilerplate, leaving code that decri!e the
overall >ow of the application rather than all of the implementation detail.
Writing ton of initiali;ation code 7ut to get tarted$ 'ypically you need to write a lot
of plum!ing 7ut to get a !aic D+ello WorldD &)&E app wor#ing. With &ngular you can
!oottrap your app eaily uing ervice, which are auto(in7ected into your application in
a Guice(li#e dependency(in7ection tyle. 'hi allow you to get tarted developing
feature 6uic#ly. & a !onu, you get full control over the initiali;ation proce in
automated tet.
2.' Watch a (resentation A)out Angular
+ere i a preentation on &ngular from ,ay 2012. 'he correponding lide are alo
availa!le.
3 *ootstrap
'hi page e8plain the &ngular initiali;ation proce and how you can manually initiali;e
&ngular if neceary.
3.1 Angular <script> $ag
'hi e8ample how the recommended path for integrating &ngular with what we call
automatic initiali;ation.
1. <!doctype html>
2. <html -mlns:ng="http://angularjs.org" ng-app>
3. <ody>
4. ...
5. <script src="angular.js">
6. </ody>
7. </html>
Blace the script tag at the !ottom of the page. Blacing cript tag at the end of the
page improve app load time !ecaue the +',- loading i not !loc#ed !y loading of
the angular.js cript. :ou can get the latet !it fromhttp$<<code.angular7.org. Bleae
don"t lin# your production code to thi 2=-, a it will e8poe a ecurity hole on your ite.
Cor e8perimental development lin#ing to our ite i 1ne.
.hooe$ angular-[version].js for a human(reada!le 1le, uita!le for
development and de!ugging.
.hooe$ angular-[version].min.js for a compreed and o!fucated
1le, uita!le for ue in production.
Blace ng-app to the root of your application, typically on the <html> tag if you want
angular to auto(!oottrap your application.
<html ng-app>
1%
11
If I9F upport i re6uired add id="ng-app"
<html ng-app id="ng-app">
If you chooe to ue the old tyle directive ynta8 ng: then include 8ml(namepace
in html to ma#e I9 happy. *'hi i here for hitorical reaon, and we no longer
recommend ue of ng:./
<html xmlns:ng="http://angularjs.org">
3.2 Auto!atic Initiali+ation
&ngular initiali;e automatically upon DOMContentLoaded event, at which point &ngular
loo# for the ng-app directive which deignate your application root. If the ng-app directive i
found then &ngular will$
load the module aociated with the directive.
create the application injector
compile the D0, treating the ng&app directive a the root of the compilation. 'hi
allow you to tell it to treat only a portion of the D0, a an &ngular application.
1. <!doctype html>
2. <html ng-app="optional.odule/ame">
3. <ody>
4. " can add: )) 1&0 ,,.
5. <script src="angular.js"></script>
6. </ody>
7. </html>
3.3 ,anual Initiali+ation
If you need to have more control over the initiali;ation proce, you can ue a manual
!oottrapping method intead. 98ample of when you"d need to do thi include uing cript
loader or the need to perform an operation !efore &ngular compile a page.
+ere i an e8ample of manually initiali;ing &ngular. 'he e8ample i e6uivalent to uing
the ng-app directive.
1. <!doctype html>
2. <html -mlns:ng="http://angularjs.org">
3. <ody>
4. 1ello ))23orld2,,!
5. <script
src="http://code.angularjs.org/angular.js"></script>
6. <script>
7. angular.element4document5.ready46unction45 )
8. angular.ootstrap4document57
9. ,57
10. </script>
11. </ody>
12. </html>
'hi i the e6uence that your code hould follow$
1. &fter the page and all of the code i loaded, 1nd the root of the +',- template,
which i typically the root of the document.
2. .all api/angular.bootstrap to compile the template into an e8ecuta!le, !i(directionally
!ound application.
11
12
# -$,. /o!piler
&ngular" HTML compiler allow the developer to teach the !rower new +',- ynta8. 'he
compiler allow you to attach !ehavior to any +',- element or attri!ute and even create
new +',- element or attri!ute with cutom !ehavior. &ngular call thee !ehavior
e8tenion directives.
+',- ha a lot of contruct for formatting the +',- for tatic document in a declarative
fahion. Cor e8ample if omething need to !e centered, there i no need to provide
intruction to the !rower how the window i;e need to !e divided in half o that center i
found, and that thi center need to !e aligned with the te8t" center. %imply
addalign="center" attri!ute to any element to achieve the deired !ehavior. %uch i the
power of declarative language.
5ut the declarative language i alo limited, ince it doe not allow you to teach the !rower
new ynta8. Cor e8ample there i no eay way to get the !rower to align the te8t at 1<3 the
poition intead of 1<2. What i needed i a way to teach !rower new +',- ynta8.
&ngular come pre(!undled with common directive which are ueful for !uilding any app.
We alo e8pect that you will create directive that are peci1c to your app. 'hee e8tenion
!ecome a Domain %peci1c -anguage for !uilding your application.
&ll of thi compilation ta#e place in the we! !rowerG no erver ide or pre(compilation
tep i involved.
#.1 /o!piler
.ompiler i an angular ervice which travere the D0, loo#ing for attri!ute. 'he
compilation proce happen in two phae.
1. .ompile$ travere the D0, and collect all of the directive. 'he reult i a lin#ing
function.
2. -in#$ com!ine the directive with a cope and produce a live view. &ny change in
the cope model are re>ected in the view, and any uer interaction with the view are
re>ected in the cope model. 'hi ma#e the cope model the ingle ource of truth.
%ome directive uch ng-repeat clone D0, element once for each item in collection. +aving
a compile and lin# phae improve performance ince the cloned template only need to !e
compiled once, and then lin#ed once for each clone intance.
#.2 "irecti0e
& directive i a !ehavior which hould !e triggered when peci1c +',- contruct are
encountered in the compilation proce. 'he directive can !e placed in element name,
attri!ute, cla name, a well a comment. +ere are ome e6uivalent e8ample of
invo#ing the ng-bind directive.
1. <span ng-ind="e-p"></span>
2. <span class="ng-ind: e-p7"></span>
3. <ng-ind></ng-ind>
4. <!-- directi!e: ng-ind e-p -->
& directive i 7ut a function which e8ecute when the compiler encounter it in the D0,.
%ee directive API for in(depth documentation on how to write directive.
+ere i a directive which ma#e any element dragga!le. 3otice the draggable attri!ute on
the <span> element.
Source
9dit
12
13
inde8.html
cript.7
1. <!doctype html>
2. <html ng-app="drag">
3. <head>
4. <script
src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <span draggale>8rag .9</span>
9. </ody>
10. </html>
Demo
Drag ,9
'he preence of the draggable attri!ute on any element give the element new !ehavior.
'he !eauty of thi approach i that we have taught the !rower a new tric#. We have
e8tended the voca!ulary of what the !rower undertand in a way which i natural to
anyone who i familiar with +',- principle.
#.3 1nderstanding 2iew
'here are many templating ytem out there. ,ot of them conume a tatic tring
template and com!ine it with data, reulting in a new tring. 'he reulting te8t i
then innerHTMLed into an element.
'hi mean that any change to the data need to !e re(merged with the template and
then innerHTMLed into the D0,. %ome of the iue with thi approach are$ reading uer
input and merging it with data, clo!!ering uer input !y overwriting it, managing the whole
update proce, and lac# of !ehavior e8preivene.
&ngular i different. 'he &ngular compiler conume the D0, with directive, not tring
template. 'he reult i a lin#ing function, which when com!ined with a cope model reult
in a live view. 'he view and cope model !inding are tranparent. 3o action from the
developer i needed to update the view. &nd !ecaue no innerHTML i ued there are no
iue of clo!!ering uer input. Curthermore, &ngular directive can contain not 7ut te8t
!inding, !ut !ehavioral contruct a well.
13
14
'he &ngular approach produce a ta!le D0,. 'hi mean that the D0, element intance
!ound to a model item intance doe not change for the lifetime of the !inding. 'hi mean
that the code can get hold of the element and regiter event handler and #now that the
reference will not !e detroyed !y template data merge.
' /onceptual o0er0iew
'hi document give a 6uic# overview of the main angular component and how they wor#
together. 'hee are$
tartup ( !ring up hello world
runtime ( overview of angular runtime
cope ( the glue !etween the view and the controller
controller ( application !ehavior
model ( your application data
view ( what the uer ee
directive ( e8tend +',- voca!ulary
1lter ( format the data in uer locale
in7ector ( aem!le your application
module ( con1gure the in7ector
' ( angular namepace
'.1 Startup
'hi i how we get the !all rolling *refer to the diagram and
e8ample !elow/$
1. 'he !rower load the +',- and pare it into a
D0,
2. 'he !rower load angular.js cript
3. &ngular wait for DOMContentLoaded event
4. &ngular loo# for ng&app directive, which deignate
the application !oundary
5. 'he ,odule peci1ed in ng&app *if any/ i ued to
con1gure the 'injector
6. 'he 'injector i ued to create the 'co(pileervice
a well a 'root)cope
7. 'he 'co(pile ervice i ued to compile the D0,
and lin# it with 'root)cope
14
15
8. 'he ng&init directive aign World to thename property on the cope
$. 'he {{name}} interpolates the e8preion toHello World!
Source
9dit
inde8.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. </head>
6. <ody>
7. <p ng-init=" name=23orld2 ">1ello ))name,,!</p>
8. </ody>
9. </html>
Demo
+ello WorldH
15
16
'.2 Runti!e
'he diagram and the e8ample !elow decri!e how &ngular interact with the !rower"
event loop.
1. 'he !rower" event(loop wait for an event to arrive. &n event i a uer interaction,
timer event, or networ# event *repone from a erver/.
2. 'he event" call!ac# get e8ecuted. 'hi enter the )ava%cript conte8t. 'he call!ac#
can modify the D0, tructure.
3. 0nce the call!ac# e8ecute, the !rower leave the )ava%cript conte8t and re(
render the view !aed on D0, change.
&ngular modi1e the normal )ava%cript >ow !y providing it own event proceing loop.
'hi plit the )ava%cript into claical and &ngular e8ecution conte8t. 0nly operation
which are applied in &ngular e8ecution conte8t will !ene1t from &ngular data(!inding,
e8ception handling, property watching, etc... :ou can alo ue Aapply*/ to enter &ngular
e8ecution conte8t from )ava%cript. Ieep in mind that in mot place *controller, ervice/
Aapply ha already !een called for you !y the directive which i handling the event. &n
e8plicit call to Aapply i needed only when implementing cutom event call!ac#, or when
wor#ing with third(party li!rary call!ac#.
1. 9nter &ngular e8ecution conte8t !y calling cope.'apply(stimulusFn).
Where stimulusFn i the wor# you wih to do in &ngular e8ecution conte8t.
2. &ngular e8ecute the stimulusFn(), which typically modi1e application tate.
3. &ngular enter the 'digest loop. 'he loop i made up of two maller loop which
proce 'e*al+sync 6ueue and the ',atch lit. 'he 'digest loop #eep iterating until the
model ta!ili;e, which mean that the 'e*al+sync6ueue i empty and the ',atch lit
doe not detect any change.
4. 'he 'e*al+sync 6ueue i ued to chedule wor# which need to occur outide of
current tac# frame, !ut !efore the !rower" view render. 'hi i uually done
with setTimeout(0), !ut the setTimeout(0) approach uffer from lowne and
may caue view >ic#ering ince the !rower render the view after each event.
5. 'he ',atch lit i a et of e8preion which may have changed ince lat iteration. If
a change i detected then the$watch function i called which typically update the
D0, with the new value.
6. 0nce the &ngular 'digest loop 1nihe the e8ecution leave the &ngular and
)ava%cript conte8t. 'hi i followed !y the !rower re(rendering the D0, to re>ect any
change.
+ere i the e8planation of how the Hello world e8ample achieve the data(!inding effect
when the uer enter te8t into the te8t 1eld.
1. During the compilation phae$
1. the ng&(odel and input directive et up a keydown litener on
the <input> control.
2. the --na(e.. interpolation et up a ',atch to !e noti1ed of name change.
2. During the runtime phae$
1. Breing an "X" #ey caue the !rower to emit a keydown event on the input
control.
2. 'he input directive capture the change to the input" value and
call 'apply("name = 'X';") to update the application model inide the &ngular
e8ecution conte8t.
16
17
3. &ngular applie the name = 'X'; to the model.
4. 'he 'digest loop !egin
5. 'he ',atch lit detect a change on the name property and noti1e
the --na(e.. interpolation, which in turn update the D0,.
6. &ngular e8it the e8ecution conte8t, which in turn e8it the keydown event
and with it the )ava%cript e8ecution conte8t.
7. 'he !rower re(render the view with update te8t.
Source
9dit
inde8.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. </head>
6. <ody>
7. <input ng-model="name">
8. <p>1ello ))name,,!</p>
9. </ody>
10. </html>
Demo
',-Direct
+ello H
'.3 Scope
'he cope i reponi!le for detecting change to the model ection and provide the
e8ecution conte8t for e8preion. 'he cope are neted in a hierarchical tructure which
cloely follow the D0, tructure. *%ee individual directive documentation to ee which
directive caue a creation of new cope./
'he following e8ample demontrate how the name e8preion will evaluate into a different
value depending on which cope it i evaluated in. 'he e8ample i followed !y a diagram
depicting the cope !oundarie.
Source
9dit
inde8.html
tyle.c
cript.7
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. </head>
7. <ody>
8. <di! ng-controller=":reet#trl">
9. 1ello ))name,,!
10. </di!>
11. <di! ng-controller=";ist#trl">
12. <ol>
13. <li ng-repeat="name in names">))name,,</li>
17
18
14. </ol>
15. </di!>
16. </ody>
17. </html>
Demo
+ello WorldH
1. Igor
2. ,i#o
3. 4o7ta
'.# /ontroller
& controller i the code !ehind the view. It
7o! i to contruct the model and
pu!lih it to the view along with
call!ac# method. 'he view i a
pro7ection of the cope onto the
template *the +',-/. 'he cope i the glue
which marhal the model to the view and
forward the event to the controller.
'he eparation of the controller and the view
i important !ecaue$
'he controller i written in )ava%cript. )ava%cript i imperative. Imperative i a good
1t for pecifying application !ehavior. 'he controller hould not contain any rendering
information *D0, reference or +',- fragment/.
'he view template i written in +',-. +',- i declarative. Declarative i a good 1t
for pecifying 2I. 'he 4iew hould not contain any !ehavior.
%ince the controller i unaware of the view, there could !e many view for the ame
controller. 'hi i important for re(#inning, device peci1c view *i.e. mo!ile v de#top/,
and teta!ility.
Source
9dit
18
1$
inde8.html
cript.7
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. </head>
7. <ody>
8. <di! ng-controller=".y#trl">
9. 1ello ))name,,!
10. <utton ng-clic<="action45">
11. =>
12. </utton>
13. </di!>
14. </ody>
15. </html>
Demo
+ello WorldH 0I
'.' ,odel
'he model i the data which i merged with the
template to produce the view. 'o !e a!le to render the
model into the view, the model ha to !e a!le to !e
referenced from the cope. 2nli#e many other
framewor# &ngular ma#e no retriction or
re6uirement on the model. 'here are no clae to
inherit from or pecial acceor method for
acceing or changing the model. 'he model can !e
primitive, o!7ect hah, or a full o!7ect 'ype. In hort
the model i a plain )ava%cript o!7ect.
'.3 2iew
'he view i what the uer ee. 'he
view !egin it life a a template, i
merged with the model and 1nally
rendered into the !rower D0,.
&ngular ta#e a very different
approach to rendering the view
compared to mot other templating
ytem.
0ther ( ,ot templating ytem
!egin a an +',- tring with
pecial templating mar#up. 0ften
the template mar#up !rea# the
+',- ynta8 which mean that
the template can not !e edited !y
an +',- editor. 'he template
tring i then pared !y the
template engine, and merged
1$
2%
with the data. 'he reult of the merge i an +',- tring. 'he +',- tring i then written
to the !rower uing the.innerHTML, which caue the !rower to render the +',-.
When the model change the whole proce need to !e repeated. 'he granularity of the
template i the granularity of the D0, update. 'he #ey here i that the templating
ytem manipulate tring.
&ngular ( &ngular i different, ince it templating ytem wor# on D0, o!7ect not
on tring. 'he template i till written in an +',- tring, !ut it i +',- *not +',- with
template prin#led in./ 'he !rower pare the +',- into the D0,, and the D0,
!ecome the input to the template engine #nown a the co(piler. 'he compiler loo#
fordirective which in turn et up ,atches on the model. 'he reult i a continuouly
updating view which doe not need template model re(merging. :our model !ecome
the ingle ource(of(truth for your view.
Source
9dit
inde8.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. </head>
6. <ody>
7. <di! ng-init="list = ?2#hrome2@ 2Aa6ari2@ 2Bire6o-2@ 2"92C ">
8. <input ng-model="list" ng-list> <r>
9. <input ng-model="list" ng-list> <r>
10. <pre>list=))list,,</pre> <r>
11. <ol>
12. <li ng-repeat="item in list">
13. ))item,,
14. </li>
15. </ol>
16. </di!>
17. </ody>
18. </html>
Demo
',-Direct
',-Direct
list=?"#hrome"@"Aa6ari"@"Bire6o-"@""9"C
1. .hrome
2. %afari
3. Cirefo8
4. I9
'.4 "irecti0es
& directive i a !ehavior or D0, tranformation which i triggered !y the preence of a
cutom attri!ute, element name, or a cla name. & directive allow you to e8tend the
+',- voca!ulary in a declarative fahion. Collowing i an e8ample which ena!le data(
!inding for the contenteditable in +',-.
2%
21
1.1.3 Source
9dit
inde8.html
tyle.c
cript.7
1. <!doctype html>
2. <html ng-app="directi!e">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di! content9ditale="true" ng-model="content">9dit .e</di!>
9. <pre>model = ))content,,</pre>
10. </ody>
11. </html>
Demo
9dit ,e
model = 9dit .e
'.5 6ilters
Filters perform data tranformation. 'ypically they are ued in con7unction with the locale to
format the data in locale peci1c output. 'hey follow the pirit of 23IE 1lter and ue imilar
ynta8 | *pipe/.
Source
9dit
inde8.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. </head>
6. <ody>
7. <di! ng-init="list = ?2#hrome2@ 2Aa6ari2@ 2Bire6o-2@ 2"92C ">
8. /umer 6ormatting: )) 10DEF6GHI0 + numer ,, <r>
9. array 6iltering <input ng-model="predicate">
10. )) list + 6ilter:predicate + json ,,
11. </di!>
12. </ody>
13. </html>
Demo
3um!er formatting$ 1,23J,5KF,L?0
array 1ltering ',-Direct M D.hromeD, D%afariD, DCirefo8D, DI9D N
21
22
1.2 ,odules and the In7ector
'he injector i a ervice locator. 'here i a ingleinjector per &ngular application.
'he injectorprovide a way to loo# up an o!7ect intance !y it name. 'he in7ector #eep an
internal cache of all o!7ect o that repeated call to get the ame o!7ect name reult in the
ame intance. If the o!7ect doe not e8it, then
theinjector a# the intance factory to create a
new intance.
& module i a way to con1gure the in7ector"
intance factory, #nown a a provider.
1. // #reate a module
2. !ar my.odule = angular.module42my.odule2@ ?C5
3.
4. // #on6igure the injector
5. my.odule.6actory42ser!iceJ2@ 6unction45 )
6. return )
7. // instead o6 ),@ put your oject creation here
8. ,7
9. ,57
10.
11. // create an injector and con6igure it 6rom 2my.odule2
12. !ar Kinjector = angular.injector4?2my.odule2C57
13.
14. // retrie!e an oject 6rom the injector y name
15. !ar ser!iceJ = Kinjector.get42ser!iceJ257
16.
17. // alLays true ecause o6 instance cache
18. Kinjector.get42ser!iceJ25 === Kinjector.get42ser!iceJ257
5ut the real magic of the injector i that it can !e ued to call method and instantiate type.
'hi u!tle feature i what allow the method and type to a# for their dependencie
intead of having to loo# for them.
1. // Mou Lrite 6unctions such as this one.
2. 6unction doAomething4ser!iceJ@ ser!iceN5 )
3. // do something here.
4. ,
5.
6. // Jngular pro!ides the injector 6or your application
7. !ar Kinjector = ...7
8.
9. ///////////////////////////////////////////////
10. // the old-school Lay o6 getting dependencies.
11. !ar ser!iceJ = Kinjector.get42ser!iceJ257
12. !ar ser!iceN = Kinjector.get42ser!iceN257
13.
14. // noL call the 6unction
15. doAomething4ser!iceJ@ ser!iceN57
16.
17. ///////////////////////////////////////////////
18. // the cool Lay o6 getting dependencies.
19. // the Kinjector Lill supply the arguments to the 6unction automatically
20. Kinjector.in!o<e4doAomething57 // (his is hoL the 6rameLor< calls your 6unctions
22
23
3otice that the only thing you needed to write wa the function, and lit the dependencie in
the function argument. When angular call the function, it will ue the call which will
automatically 1ll the function argument.
98amine the ClockCtrl !elow, and notice how it lit the dependencie in the contructor.
When the ng-controllerintantiate the controller it automatically provide the dependencie.
'here i no need to create dependencie, loo# for dependencie, or even get a reference to
the in7ector.
Source
9dit
inde8.html
cript.7
1. <!doctype html>
2. <html ng-app="time9-ample.odule">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di! ng-controller="#loc<#trl">
9. #urrent time is: )) time.noL ,,
10. </di!>
11. </ody>
12. </html>
Demo
.urrent time i$ %at ,ay 25 2013 12$51$11 G,'O0200 *.9%'/
'.8 Angular 9a!espace
'o prevent accidental name colliion, &ngular pre18e name of o!7ect which could
potentially collide with $. Bleae do not ue the $ pre18 in your code a it may accidentally
collide with &ngular code.
Directive are a way to teach +',- new tric#. During D0, compilation directive are
matched againt the +',- and e8ecuted. 'hi allow directive to regiter !ehavior, or
tranform the D0,.
&ngular come with a !uilt in et of directive which are ueful for !uilding we! application
!ut can !e e8tended uch that +',- can !e turned into a declarative domain peci1c
language *D%-/.
3 In0o:ing directi0es &ro! -$,.
Directive have camel caed name uch a ngBind. 'he directive can !e invo#ed !y
tranlating the camel cae name into na#e cae with thee pecial character :, -, or _.
0ptionally the directive can !e pre18ed with x-, or data- to ma#e it +',- validator
compliant. +ere i a lit of ome of the poi!le directive name$ ng:bind, ng-
bind, ng_bind,x-ng-bind and data-ng-bind.
'he directive can !e placed in element name, attri!ute, cla name, a well a
comment. +ere are ome e6uivalent e8ample of invo#ing myDir. *+owever, mot
directive are retricted to attri!ute only./
1. <span my-dir="e-p"></span>
2. <span class="my-dir: e-p7"></span>
3. <my-dir></my-dir>
4. <!-- directi!e: my-dir e-p -->
23
24
Directive can !e invo#ed in many different way, !ut are e6uivalent in the end reult a
hown in the following e8ample.
Source
9dit
inde8.html
cript.7
9nd to end tet
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. </head>
7. <ody>
8. <di! ng-controller="#trl1">
9. 1ello <input ng-model=2name2> <hr/>
10. Olt7span ng:ind="name"Ogt7 <span ng:ind="name"></span> <r/>
11. Olt7span ngPind="name"Ogt7 <span ngPind="name"></span> <r/>
12. Olt7span ng-ind="name"Ogt7 <span ng-ind="name"></span> <r/>
13. Olt7span data-ng-ind="name"Ogt7 <span data-ng-ind="name"></span> <r/>
14. Olt7span --ng-ind="name"Ogt7 <span --ng-ind="name"></span> <r/>
15. </di!>
16. </ody>
17. </html>
Demo
+ello ',-Direct
Ppan ng$!indQDnameDR angular
Ppan ngS!indQDnameDR angular
Ppan ng(!indQDnameDR angular
Ppan data(ng(!indQDnameDR angular
Ppan 8(ng(!indQDnameDR angular
3.1 String interpolation
During the compilation proce the compiler matche te8t and attri!ute uing
the $interpolate ervice to ee if they contain em!edded e8preion. 'hee e8preion are
regitered a watches and will update a part of normaldigest cycle. &n e8ample of
interpolation i hown here$
1. <a hre6="img/))username,,.jpg">1ello ))username,,!</a>
3.2 /o!pilation process; and directi0e !atching
.ompilation of +',- happen in three phae$
1. Cirt the +',- i pared into D0, uing the tandard !rower &BI. 'hi i important
to reali;e !ecaue the template mut !e para!le +',-. 'hi i in contrat to mot
templating ytem that operate on tring, rather than on D0, element.
2. 'he compilation of the D0, i performed !y the call to the $compile() method. 'he
method travere the D0, and matche the directive. If a match i found it i added to
the lit of directive aociated with the given D0, element. 0nce all directive for a
given D0, element have !een identi1ed they are orted !y priority and
theircompile() function are e8ecuted. 'he directive compile function ha a chance to
24
25
modify the D0, tructure and i reponi!le for producing a link() function e8plained
ne8t. 'he $compile() method return a com!ined lin#ing function, which i a collection of
all of the lin#ing function returned from the individual directive compile function.
3. -in# the template with cope !y calling the lin#ing function returned from the
previou tep. 'hi in turn will call the lin#ing function of the individual directive allowing
them to regiter any litener on the element and et up anywatches with the scope. 'he
reult of thi i a live !inding !etween the cope and the D0,. & change in the cope i
re>ected in the D0,.
1. !ar Kcompile = ...7 // injected into your code
2. !ar scope = ...7
3.
4. !ar html = 2<di! ng-ind="e-p"></di!>27
5.
6. // Atep 1: parse 1(.; into 8=. element
7. !ar template = angular.element4html57
8.
9. // Atep 0: compile the template
10. !ar lin<Bn = Kcompile4template57
11.
12. // Atep D: lin< the compiled template Lith the scope.
13. lin<Bn4scope57
3.2.1 Reasons )ehind the co!pile/lin: separation
&t thi point you may wonder why the compile proce i !ro#en down to a compile and lin#
phae. 'o undertand thi, let" loo# at a real world e8ample with a repeater$
1. 1ello ))user,,@ you ha!e these actions:
2. <ul>
3. <li ng-repeat="action in user.actions">
4. ))action.description,,
5. </li>
6. </ul>
'he hort anwer i that compile and lin# eparation i needed any time a change in model
caue a change in D0, tructure uch a in repeater.
When the a!ove e8ample i compiled, the compiler viit every node and loo# for
directive. 'he {{user}} i an e8ample of an interpolation directive. ngRepeat i another
directive. 5ut ngRepeat ha a dilemma. It need to !e a!le to 6uic#ly tamp out new li for
every action in user.actions. 'hi mean that it need to ave a clean copy of
the li element for cloning purpoe and a new action are inerted, the
template li element need to !e cloned and inerted into ul. 5ut cloning the li element i
not enough. It alo need to compile the li o that it directive uch
a{{action.description}} evaluate againt the right scope. & naive method would !e
to imply inert a copy of theli element and then compile it. 5ut compiling on
every li element clone would !e low, ince the compilation re6uire that we travere the
D0, tree and loo# for directive and e8ecute them. If we put the compilation inide a
repeater which need to unroll 100 item we would 6uic#ly run into performance pro!lem.
'he olution i to !rea# the compilation proce into two phaeG the compile phae where
all of the directive are identi1ed and orted !y priority, and a lin#ing phae where any wor#
which lin# a peci1c intance of the scope and the peci1c intance of an li i performed.
ngRepeat wor# !y preventing the compilation proce from decending into the li element.
Intead the ngRepeatdirective compile li eparately. 'he reult of the li element
compilation i a lin#ing function which contain all of the directive contained in
the li element, ready to !e attached to a peci1c clone of the li element. &t runtime
thengRepeat watche the e8preion and a item are added to the array it clone
25
26
the li element, create a new scopefor the cloned li element and call the lin# function on
the cloned li.
%ummary$
compile function ( 'he compile function i relatively rare in directive, ince mot
directive are concerned with wor#ing with a peci1c D0, element intance rather than
tranforming the template D0, element. &ny operation which can !e hared among the
intance of directive hould !e moved to the compile function for performance reaon.
link function ( It i rare for the directive not to have a lin# function. & lin# function
allow the directive to regiter litener to the peci1c cloned D0, element intance a
well a to copy content into the D0, from the cope.
3.3 Writing directi0es <short 0ersion=
In thi e8ample we will !uild a directive that diplay the current time.
Source
9dit
inde8.html
cript.7
1. <!doctype html>
2. <html ng-app="time">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di! ng-controller="#trl0">
9. 8ate 6ormat: <input ng-model="6ormat"> <hr/>
10. #urrent time is: <span my-current-time="6ormat"></span>
11. </di!>
12. </ody>
13. </html>
Demo
Date format$ ',-Direct
.urrent time i$ 5<25<13 12$5L$25 B,
3.# Writing directi0es <long 0ersion=
'here are different way to declare a directive. 'he difference reide in the return value of
the factory function. :ou can either return a Directive De1nition 0!7ect *ee !elow/ that
de1ne the directive propertie, or 7ut the pot-in# function of uch an o!7ect *all other
propertie will have the default value/.
+ere" an e8ample directive declared with a Directive De1nition 0!7ect$
1. !ar my.odule = angular.module4...57
2.
3. my.odule.directi!e42directi!e/ame2@ 6unction 6actory4injectales5 )
4. !ar directi!e8e6inition=ject = )
5. priority: 0@
6. template: 2<di!></di!>2@
7. templateQrl: 2directi!e.html2@
8. replace: 6alse@
9. transclude: 6alse@
26
27
10. restrict: 2J2@
11. scope: 6alse@
12. controller: 6unction4Kscope@ Kelement@ Kattrs@ Ktransclude@ other"njectales5 )
... ,@
13. compile: 6unction compile4t9lement@ tJttrs@ transclude5 )
14. return )
15. pre: 6unction pre;in<4scope@ i9lement@ iJttrs@ controller5 ) ... ,@
16. post: 6unction post;in<4scope@ i9lement@ iJttrs@ controller5 ) ... ,
17. ,
18. ,@
19. lin<: 6unction post;in<4scope@ i9lement@ iJttrs5 ) ... ,
20. ,7
21. return directi!e8e6inition=ject7
22. ,57
In mot cae you will not need uch 1ne control and o the a!ove can !e impli1ed. :ou
can till return a Directive De1nition 0!7ect, !ut only etting the "compile" function property
of the 0!7ect, and rely on the default value for other propertie.
'herefore the a!ove can !e impli1ed a$
1. !ar my.odule = angular.module4...57
2.
3. my.odule.directi!e42directi!e/ame2@ 6unction 6actory4injectales5 )
4. !ar directi!e8e6inition=ject = )
5. compile: 6unction compile4t9lement@ tJttrs5 )
6. return 6unction post;in<4scope@ i9lement@ iJttrs5 ) ... ,
7. ,
8. ,7
9. return directi!e8e6inition=ject7
10. ,57
Cinally, mot directive concern themelve only with intance, not with template
tranformation, allowing further impli1cation.
+ere we only de1ne the pot-in# function$
1. !ar my.odule = angular.module4...57
2.
3. my.odule.directi!e42directi!e/ame2@ 6unction 6actory4injectales5 )
4. return 6unction post;in<4scope@ i9lement@ iJttrs5 ) ... ,
5. ,57
3.#.1 6actory !ethod
'he factory method i reponi!le for creating the directive. It i invo#ed only once, when
the compiler matche the directive for the 1rt time. :ou can perform any initiali;ation wor#
here. 'he method i invo#ed uing the$injector.invoke which ma#e it in7ecta!le following all
of the rule of in7ection annotation.
3.#.2 "irecti0e "e&inition >)7ect
'he directive de1nition o!7ect provide intruction to the compiler. 'he attri!ute are$
name ( 3ame of the current cope. 0ptional and default to the name at regitration.
priority ( When there are multiple directive de1ned on a ingle D0, element,
ometime it i neceary to pecify the order in which the directive are applied.
'he priority i ued to ort the directive !efore theircompile function get called.
Briority i de1ned a a num!er. Directive with greater numerical priority are
compiled 1rt. 'he order of directive with the ame priority i unde1ned. 'he default
priority i 0.
27
28
terminal ( If et to true then the current priority will !e the lat et of directive
which will e8ecute *any directive at the current priority will till e8ecute a the order of
e8ecution on ame priority i unde1ned/.
scope ( If et to$
true ( then a new cope will !e created for thi directive. If multiple
directive on the ame element re6uet a new cope, only one new cope i created.
'he new cope rule doe not apply for the root of the template ince the root of the
template alway get a new cope.
{} *o!7ect hah/ ( then a new "iolate" cope i created. 'he "iolate" cope
differ from normal cope in that it doe not prototypically inherit from the parent
cope. 'hi i ueful when creating reua!le component, which hould not
accidentally read or modify data in the parent cope.
'he "iolate" cope ta#e an o!7ect hah which de1ne a et of local cope propertie
derived from the parent cope. 'hee local propertie are ueful for aliaing value
for template. -ocal de1nition i a hah of local cope property to it ource$
@ or @attr ( !ind a local cope property to the value of D0,
attri!ute. 'he reult i alway a tring ince D0, attri!ute are tring. If
no attr name i peci1ed then the attri!ute name i aumed to !e the ame a
the local name. Given <widget my-attr="hello {{name}}"> and widget
de1nition of scope: { localName:'@myAttr' }, then widget cope
property localName will re>ect the interpolated value ofhello {{name}}. &
the name attri!ute change o will the localName property on the widget cope.
'he name i read from the parent cope *not component cope/.
= or =attr ( et up !i(directional !inding !etween a local cope
property and the parent cope property of name de1ned via the value of
the attr attri!ute. If no attr name i peci1ed then the attri!ute name i
aumed to !e the ame a the local name. Given <widget my-
attr="parentModel"> and widget de1nition of scope:
{ localModel:'=myAttr' }, then widget cope property localModel will
re>ect the value of parentModel on the parent cope. &ny change
to parentModel will !e re>ected inlocalModel and any change
in localModel will re>ect in parentModel.
& or &attr ( provide a way to e8ecute an e8preion in the conte8t
of the parent cope. If no attr name i peci1ed then the attri!ute name i
aumed to !e the ame a the local name. Given <widget my-attr="count
= count + value"> and widget de1nition of scope:
{ localFn:'&myAttr' }, then iolate cope property localFn will point to a
function wrapper for the count = count + valuee8preion. 0ften it"
deira!le to pa data from the iolated cope via an e8preion and to the parent
cope, thi can !e done !y paing a map of local varia!le name and value into
the e8preion wrapper fn. Cor e8ample, if the e8preion
i increment(amount) then we can pecify the amount value !y calling
the localFn a localFn({amount: 22}).
controller ( .ontroller contructor function. 'he controller i intantiated !efore
the pre(lin#ing phae and it i hared with other directive if they re6uet it !y name
*ee require attri!ute/. 'hi allow the directive to communicate with each other and
augment each other" !ehavior. 'he controller i in7ecta!le with the following local$
$scope ( .urrent cope aociated with the element
$element ( .urrent element
$attrs ( .urrent attri!ute o!7ect for the element
28
2$
$transclude ( & tranclude lin#ing function pre(!ound to the correct
trancluion cope$function(cloneLinkingFn).
'o avoid error after mini1cation the !rac#et notation hould !e ued$
controller: ?2Kscope2@ 2Kelement2@ 2Kattrs2@ 2Ktransclude2@ 6unction4Kscope@ Kelement@
Kattrs@ Ktransclude5 ) ... ,C
2. require ( =e6uire another controller !e paed into current directive lin#ing function.
'he require ta#e a name of the directive controller to pa in. If no uch controller can
!e found an error i raied. 'he name can !e pre18ed with$
? ( Don"t raie an error. 'hi ma#e the re6uire dependency optional.
^ ( -oo# for the controller on parent element a well.
restrict ( %tring of u!et of EACM which retrict the directive to a
peci1c directive declaration tyle. If omitted directive are allowed on attri!ute only.
E ( 9lement name$ <my-directive></my-directive>
A ( &ttri!ute$ <div my-directive="exp"> </div>
C ( .la$ <div class="my-directive: exp;"></div>
M ( .omment$ <!-- directive: my-directive exp -->
template ( replace the current element with the content of the +',-. 'he
replacement proce migrate all of the attri!ute < clae from the old element to the
new one. %ee the .reating .omponent ection !elow for more information.
templateUrl ( %ame a template !ut the template i loaded from the
peci1ed 2=-. 5ecaue the template loading i aynchronou the compilation<lin#ing i
upended until the template i loaded.
replace ( if et to true then the template will replace the current element,
rather than append the template to the element.
transclude ( compile the content of the element and ma#e it availa!le to
the directive. 'ypically ued withngTransclude. 'he advantage of trancluion i that the
lin#ing function receive a trancluion function which i pre(!ound to the correct cope.
In a typical etup the widget create an isolate cope, !ut the trancluion i not a
child, !ut a i!ling of the isolate cope. 'hi ma#e it poi!le for the widget to have
private tate, and the trancluion to !e !ound to the parent *pre(isolate/ cope.
true ( tranclude the content of the directive.
'element' ( tranclude the whole element including any directive de1ned
at lower priority.
compile$ 'hi i the compile function decri!ed in the ection !elow.
link$ 'hi i the lin# function decri!ed in the ection !elow. 'hi property i
ued only if the compile property i not de1ned.
3.#.3 /o!pile &unction
1. 6unction compile4t9lement@ tJttrs@ transclude5 ) ... ,
'he compile function deal with tranforming the template D0,. %ince mot directive do
not do template tranformation, it i not ued often. 98ample that re6uire compile function
are directive that tranform template D0,, uch angRepeat, or load the content
aynchronouly, uch a ngView. 'he compile function ta#e the following argument.
tElement ( template element ( 'he element where the directive ha !een declared.
It i afe to do template tranformation on the element and child element only.
tAttrs ( template attri!ute ( 3ormali;ed lit of attri!ute declared on thi element
hared !etween all directive compile function. %ee &ttri!ute.
2$
3%
transclude ( & tranclude lin#ing function$ function(scope,
cloneLinkingFn).
30'9$ 'he template intance and the lin# intance may not !e the ame o!7ect if the
template ha !een cloned. Cor thi reaon it i not afe in the compile function to do
anything other than D0, tranformation that applie to all D0, clone. %peci1cally, D0,
litener regitration hould !e done in a lin#ing function rather than in a compile function.
& compile function can have a return value which can !e either a function or an o!7ect.
returning a *pot(lin#/ function ( i e6uivalent to regitering the lin#ing function via
the link property of the con1g o!7ect when the compile function i empty.
returning an o!7ect with function*/ regitered via pre and post propertie ( allow
you to control when a lin#ing function hould !e called during the lin#ing phae. %ee info
a!out pre(lin#ing and pot(lin#ing function !elow.
3.#.# .in:ing &unction
1. 6unction lin<4scope@ i9lement@ iJttrs@ controller5 ) ... ,
'he lin# function i reponi!le for regitering D0, litener a well a updating the D0,. It
i e8ecuted after the template ha !een cloned. 'hi i where mot of the directive logic will
!e put.
scope ( Scope ( 'he cope to !e ued !y the directive for regitering watches.
iElement ( intance element ( 'he element where the directive i to !e ued. It i
afe to manipulate the children of the element only in postLink function ince the
children have already !een lin#ed.
iAttrs ( intance attri!ute ( 3ormali;ed lit of attri!ute declared on thi element
hared !etween all directive lin#ing function. %ee &ttri!ute.
controller ( a controller intance ( & controller intance if at leat one directive on
the element de1ne a controller. 'he controller i hared among all the directive, which
allow the directive to ue the controller a a communication channel.
6.4.4.1 Pre-linking function
98ecuted !efore the child element are lin#ed. 3ot afe to do D0, tranformation ince the
compiler lin#ing function will fail to locate the correct element for lin#ing.
6.4.4.2 Post-linking function
98ecuted after the child element are lin#ed. It i afe to do D0, tranformation in the pot(
lin#ing function.
3.#.' Attri)utes
'he Attributes o!7ect ( paed a a parameter in the lin#*/ or compile*/ function ( i a way of
acceing$
normalized attribute names: %ince a directive uch a "ng5ind" can !e e8preed in
many way uch a "ng$!ind", or "8(ng(!ind", the attri!ute o!7ect allow for normali;ed
acceed to the attri!ute.
directive inter-communication: &ll directive hare the ame intance of the attri!ute
o!7ect which allow the directive to ue the attri!ute o!7ect a inter directive
communication.
supports interpolation: Interpolation attri!ute are aigned to the attri!ute o!7ect
allowing other directive to read the interpolated value.
observing interpolated attributes: 2e $observe to o!erve the value change of
attri!ute that contain interpolation *e.g. src="{{bar}}"/. 3ot only i thi very ef1cient
3%
31
!ut it" alo the only way to eaily get the actual value !ecaue during the lin#ing phae
the interpolation han"t !een evaluated yet and o the value i at thi time et
toundefined.
1. 6unction lin<ingBn4scope@ elm@ attrs@ ctrl5 )
2. // get the attriute !alue
3. console.log4attrs.ng.odel57
4.
5. // change the attriute
6. attrs.Kset42ng.odel2@ 2neL !alue257
7.
8. // oser!e changes to interpolated attriute
9. attrs.Koser!e42ng.odel2@ 6unction4!alue5 )
10. console.log42ng.odel has changed !alue to 2 & !alue57
11. ,57
12. ,
3.' 1nderstanding $ransclusion and Scopes
It i often deira!le to have reua!le component. 5elow i a peudo code howing how a
impli1ed dialog component may wor#.
1. <di!>
2. <utton ng-clic<="shoL=true">shoL</utton>
3. <dialog title="1ello ))username,,."
4. !isile="shoL"
5. on-cancel="shoL = 6alse"
6. on-o<="shoL = 6alse7 doAomething45">
7. Nody goes here: ))username,, is ))title,,.
8. </dialog>
9. </di!>
.lic#ing on the DhowD !utton will open the dialog. 'he dialog will have a title, which i data
!ound to username, and it will alo have a !ody which we would li#e to tranclude into the
dialog.
+ere i an e8ample of what the template de1nition for the dialog widget may loo# li#e.
1. <di! ng-shoL="!isile">
2. <hD>))title,,</hD>
3. <di! class="ody" ng-transclude></di!>
4. <di! class="6ooter">
5. <utton ng-clic<="on=<45">Aa!e changes</utton>
6. <utton ng-clic<="on#ancel45">#lose</utton>
7. </di!>
8. </di!>
'hi will not render properly, unle we do ome cope magic.
'he 1rt iue we have to olve i that the dialog !o8 template e8pect title to !e
de1ned, !ut the place of intantiation would li#e to !ind to username. Curthermore the
!utton e8pect the onOk and onCancel function to !e preent in the cope. 'hi limit the
uefulne of the widget. 'o olve the mapping iue we ue the locals to create local
varia!le which the template e8pect a follow$
1. scope: )
2. title: 2R2@ // the title uses the data-inding 6rom the parent scope
3. on=<: 2O2@ // create a delegate on=< 6unction
4. on#ancel: 2O2@ // create a delegate on#ancel 6unction
5. !isile: 2=2 // set up !isile to accept data-inding
6. ,
.reating local propertie on widget cope create two pro!lem$
31
32
1. iolation ( if the uer forget to et title attri!ute of the dialog widget the dialog
template will !ind to parent cope property. 'hi i unpredicta!le and undeira!le.
2. trancluion ( the trancluded D0, can ee the widget local, which may overwrite
the propertie which the trancluion need for data(!inding. In our e8ample
the title property of the widget clo!!er the title property of the trancluion.
'o olve the iue of lac# of iolation, the directive declare a new isolated cope. &n
iolated cope doe not prototypically inherit from the child cope, and therefore we don"t
have to worry a!out accidentally clo!!ering any propertie.
+owever isolated cope create a new pro!lem$ if a trancluded D0, i a child of the
widget iolated cope then it will not !e a!le to !ind to anything. Cor thi reaon the
trancluded cope i a child of the original cope, !efore the widget created an iolated
cope for it local varia!le. 'hi ma#e the trancluded and widget iolated cope i!ling.
'hi may eem to !e une8pected comple8ity, !ut it give the widget uer and developer the
leat urprie.
'herefore the 1nal directive de1nition loo# omething li#e thi$
1. transclude: true@
2. scope: )
3. title: 2R2@ // the title uses the data-inding 6rom the parent scope
4. on=<: 2O2@ // create a delegate on=< 6unction
5. on#ancel: 2O2@ // create a delegate on#ancel 6unction
6. !isile: 2=2 // set up !isile to accept data-inding
7. ,@
8. restrict: 292@
9. replace: true
3.3 /reating /o!ponents
It i often deira!le to replace a ingle directive with a more comple8 D0, tructure. 'hi
allow the directive to !ecome a hort hand for reua!le component from which
application can !e !uilt.
Collowing i an e8ample of !uilding a reua!le widget.
Source
9dit
inde8.html
tyle.c
cript.7
9nd to end tet
1. <!doctype html>
2. <html ng-app="Sippy.odule">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di! ng-controller="#trlD">
9. (itle: <input ng-model="title"> <r>
10. (e-t: <te-tarea ng-model="te-t"></te-tarea>
11. <hr>
12. <di! class="Sippy" Sippy-title="8etails: ))title,,...">))te-t,,</di!>
13. </di!>
14. </ody>
15. </html>
Demo
32
33
'itle$ ',-Direct
'e8t$ ',-Direct
Detail$ -orem Ipum...
4 Epressions
98preion are )ava%cript(li#e code nippet that are uually placed in !inding uch
a {{ expression }}. 98preion are proceed !y the $parse ervice.
Cor e8ample, thee are all valid e8preion in angular$
1+2
3*10 | currency
user.name
4.1 Angular Epressions 0s. ?S Epressions
It might !e tempting to thin# of &ngular view e8preion a )ava%cript e8preion, !ut
that i not entirely correct, ince &ngular doe not ue a )ava%cript eval() to evaluate
e8preion. :ou can thin# of &ngular e8preion a )ava%cript e8preion with following
difference$
&ttri!ute 9valuation$ evaluation of all propertie are againt the cope, doing the
evaluation, unli#e in )ava%cript where the e8preion are evaluated againt the
glo!al window.
Corgiving$ e8preion evaluation i forgiving to unde1ned and null, unli#e in
)ava%cript, where uch evaluation generate NullPointerExceptions.
3o .ontrol Clow %tatement$ you cannot do any of the following in angular
e8preion$ conditional, loop, or throw.
Cilter$ you can pa reult of e8preion evaluation through 1lter chain. Cor
e8ample to convert date o!7ect into a local peci1c human(reada!le format.
If, on the other hand, you do want to run ar!itrary )ava%cript code, you hould ma#e it a
controller method and call the method. If you want to eval() an angular e8preion from
)ava%cript, ue the $eval() method.
4.2 Ea!ple
Source
9dit
inde8.html
9nd to end tet
1. <!doctype html>
2. <html ng-app>
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. </head>
6. <ody>
7. 1&0=))1&0,,
8. </ody>
9. </html>
Demo
1O2Q3
33
34
:ou can try evaluating different e8preion here$
Source
9dit
inde8.html
cript.7
9nd to end tet
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. </head>
7. <ody>
8. <di! ng-controller="#ntl0" class="e-pressions">
9. 9-pression:
10. <input type=2te-t2 ng-model="e-pr" siSe="H0"/>
11. <utton ng-clic<="add9-p4e-pr5">9!aluate</utton>
12. <ul>
13. <li ng-repeat="e-pr in e-prs">
14. ? <a hre6="" ng-clic<="remo!e9-p4Kinde-5">T</a> C
15. <tt>))e-pr,,</tt> => <span ng-ind="Kparent.Ke!al4e-pr5"></span>
16. </li>
17. </ul>
18. </di!>
19. </ody>
20. </html>
Demo
98preion$
',-Direct 9valuate
4.3 (roperty E0aluation
9valuation of all propertie ta#e place againt a cope. 2nli#e )ava%cript, where name
default to glo!al window propertie, &ngular e8preion have to ue $window to refer to the
glo!al window o!7ect. Cor e8ample, if you want to call alert(), which i de1ned
on window, in an e8preion you mut ue $window.alert(). 'hi i done intentionally to
prevent accidental acce to the glo!al tate *a common ource of u!tle !ug/.
Source
9dit
inde8.html
cript.7
9nd to end tet
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. </head>
7. <ody>
8. <di! class="e-ample0" ng-controller="#ntl1">
9. /ame: <input ng-model="name" type="te-t"/>
10. <utton ng-clic<="greet45">:reet</utton>
34
35
11. </di!>
12. </ody>
13. </html>
Demo
3ame$ ',-Direct Greet
4.3.1 6orgi0ing
98preion evaluation i forgiving to unde1ned and null. In )ava%cript,
evaluating a.b.c throw an e8ception if a i not an o!7ect. While thi ma#e ene for a
general purpoe language, the e8preion evaluation are primarily ued for data !inding,
which often loo# li#e thi$
{{a.b.c}}
It ma#e more ene to how nothing than to throw an e8ception if a i unde1ned *perhap
we are waiting for the erver repone, and it will !ecome de1ned oon/. If e8preion
evaluation wan"t forgiving we"d have to write !inding that clutter the code, for
e8ample$ {{((a||{}).b||{}).c}}
%imilarly, invo#ing a function a.b.c() on unde1ned or null imply return unde1ned.
4.3.2 9o /ontrol 6low State!ents
:ou cannot write a control >ow tatement in an e8preion. 'he reaon !ehind thi i core to
the &ngular philoophy that application logic hould !e in controller, not in the view. If you
need a conditional, loop, or to throw from a view e8preion, delegate to a )ava%cript
method intead.
4.3.3 6ilters
When preenting data to the uer, you might need to convert the data from it raw format to
a uer(friendly format. Cor e8ample, you might have a data o!7ect that need to !e
formatted according to the locale !efore diplaying it to the uer. :ou can pa e8preion
through a chain of 1lter li#e thi$
name | uppercase
'he e8preion evaluator imply pae the value of name to uppercase 1lter.
.hain 1lter uing thi ynta8$
value | filter1 | filter2
:ou can alo pa colon(delimited argument to 1lter, for e8ample, to diplay the num!er
123 with 2 decimal point$
123 | number:2
4.# $he @
:ou might !e wondering, what i the igni1cance of the A pre18T It i imply a pre18 that
angular ue, to differentiate it &BI name from other. If angular didn"t ue A, then
evaluating a.length() would return unde1ned !ecaue neither a nor angular de1ne uch
a property.
.onider that in a future verion of &ngular we might chooe to add a length method, in
which cae the !ehavior of the e8preion would change. Wore yet, you, the developer,
could create a length property and then we would have a colliion. 'hi pro!lem e8it
!ecaue &ngular augment e8iting o!7ect with additional !ehavior. 5y pre18ing it
addition with A we are reerving our namepace o that angular developer and developer
who ue &ngular can develop in harmony without colliion.
35
36
5 6or!s
.ontrol *input, select, textarea/ are a way for uer to enter data. Corm i a collection
of control for the purpoe of grouping related control together.
Corm and control provide validation ervice, o that the uer can !e noti1ed of invalid
input. 'hi provide a !etter uer e8perience, !ecaue the uer get intant feed!ac# on
how to correct the error. Ieep in mind that while client(ide validation play an important
role in providing good uer e8perience, it can eaily !e circumvented and thu can not !e
truted. %erver(ide validation i till neceary for a ecure application.
5.1 Si!ple &or!
'he #ey directive in undertanding two(way data(!inding i ngModel. 'he ngModel directive
provide the two(way data(!inding !y ynchroni;ing the model to the view, a well a view
to the model. In addition it provide an API for other directive to augment it !ehavior.
Source
9dit
inde8.html
cript.7
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. </head>
7. <ody>
8. <di! ng-controller="#ontroller">
9. <6orm no!alidate class="simple-6orm">
10. /ame: <input type="te-t" ng-model="user.name" /><r />
11. 9-mail: <input type="email" ng-model="user.email" /><r />
12. :ender: <input type="radio" ng-model="user.gender" !alue="male" />male
13. <input type="radio" ng-model="user.gender" !alue="6emale" />6emale<r />
14. <utton ng-clic<="reset45">U9A9(</utton>
15. <utton ng-clic<="update4user5">AJV9</utton>
16. </6orm>
17. <pre>6orm = ))user + json,,</pre>
18. <pre>master = ))master + json,,</pre>
19. </di!>
20. </ody>
21. </html>
Demo
3ame$ ',-Direct
9(mail$ ',-Direct
Gender$ ',-Direct male ',-Direct female
=9%9' %&49
6orm = ),
master = ),
3ote that novalidate i ued to dia!le !rower" native form validation.
5.2 1sing /SS classes
'o allow tyling of form a well a control, ngModel add thee .%% clae$
36
37
ng-valid
ng-invalid
ng-pristine
ng-dirty
'he following e8ample ue the .%% to diplay validity of each form control. In the e8ample
!oth user.name anduser.email are re6uired, !ut are rendered with red !ac#ground only
when they are dirty. 'hi enure that the uer i not ditracted with an error until after
interacting with the control, and failing to atify it validity.
Source
9dit
inde8.html
cript.7
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. </head>
7. <ody>
8. <di! ng-controller="#ontroller">
9. <6orm no!alidate class="css-6orm">
10. /ame:
11. <input type="te-t" ng-model="user.name" re'uired /><r />
12. 9-mail: <input type="email" ng-model="user.email" re'uired /><r />
13. :ender: <input type="radio" ng-model="user.gender" !alue="male" />male
14. <input type="radio" ng-model="user.gender" !alue="6emale" />6emale<r />
15. <utton ng-clic<="reset45">U9A9(</utton>
16. <utton ng-clic<="update4user5">AJV9</utton>
17. </6orm>
18. </di!>
19.
20. <style type="te-t/css">
21. .css-6orm input.ng-in!alid.ng-dirty )
22. ac<ground-color: WBJGHG97
23. ,
24.
25. .css-6orm input.ng-!alid.ng-dirty )
26. ac<ground-color: WGHBJHI7
27. ,
28. </style>
29. </ody>
30. </html>
Demo
3ame$ ',-Direct
9(mail$ ',-Direct
Gender$ ',-Direct male ',-Direct female
=9%9' %&49
5.3 *inding to &or! and control state
& form i an intance of FormController. 'he form intance can optionally !e pu!lihed into
the cope uing the nameattri!ute. %imilarly control i an intance of NgModelController. 'he
37
38
control intance can imilarly !e pu!lihed into the form intance uing the name attri!ute.
'hi implie that the internal tate of !oth the form and the control i availa!le for !inding in
the view uing the tandard !inding primitive.
'hi allow u to e8tend the a!ove e8ample with thee feature$
=9%9' !utton i ena!led only if form ha ome change
%&49 !utton i ena!led only if form ha ome change and i valid
cutom error meage for user.email and user.agree
Source
9dit
inde8.html
cript.7
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. </head>
7. <ody>
8. <di! ng-controller="#ontroller">
9. <6orm name="6orm" class="css-6orm" no!alidate>
10. /ame:
11. <input type="te-t" ng-model="user.name" name="u/ame" re'uired /><r />
12. 9-mail:
13. <input type="email" ng-model="user.email" name="u9mail" re'uired/><r />
14. <di! ng-shoL="6orm.u9mail.Kdirty OO 6orm.u9mail.Kin!alid">"n!alid:
15. <span ng-shoL="6orm.u9mail.Kerror.re'uired">(ell us your email.</span>
16. <span ng-shoL="6orm.u9mail.Kerror.email">(his is not a !alid email.</span>
17. </di!>
18.
19. :ender: <input type="radio" ng-model="user.gender" !alue="male" />male
20. <input type="radio" ng-model="user.gender" !alue="6emale" />6emale<r />
21.
22. <input type="chec<o-" ng-model="user.agree" name="userJgree" re'uired />
23. " agree: <input ng-shoL="user.agree" type="te-t" ng-model="user.agreeAign"
24. re'uired /><r />
25. <di! ng-shoL="!user.agree ++ !user.agreeAign">Xlease agree and sign.</di!>
26.
27. <utton ng-clic<="reset45" ng-disaled="isQnchanged4user5">U9A9(</utton>
28. <utton ng-clic<="update4user5"
29. ng-disaled="6orm.Kin!alid ++ isQnchanged4user5">AJV9</utton>
30. </6orm>
31. </di!>
32. </ody>
33. </html>
Demo
3ame$ ',-Direct
9(mail$ ',-Direct
Gender$ ',-Direct male ',-Direct female
',-Direct I agree$
Bleae agree and ign.
=9%9' %&49
38
3$
5.# /usto! 2alidation
&ngular provide !aic implementation for mot common html5 input type$
*text, number, url, email, radio,checkbox/, a well a ome directive for validation
*required, pattern, minlength, maxlength, min, max/.
De1ning your own validator can !e done !y de1ning your own directive which add a
cutom validation function to thengModel controller. 'o get a hold of the controller the
directive peci1e a dependency a hown in the e8ample !elow. 'he validation can occur
in two place$
,odel to 4iew update ( Whenever the !ound model change, all function
inNgModelController#$formatters array are pipe(lined, o that each of thee function ha
an opportunity to format the value and change validity tate of the form control
through NgModelController#$setValidity.
4iew to ,odel update ( In a imilar way, whenever a uer interact with a control it
callNgModelController#$setViewValue. 'hi in turn pipeline all function in
theNgModelController#$parsers array, o that each of thee function ha an opportunity
to convert the value and change validity tate of the form control
through NgModelController#$setValidity.
In the following e8ample we create two directive.
'he 1rt one i integer and it validate whether the input i a valid integer. Cor
e8ample 1.23 i an invalid value, ince it contain a fraction. 3ote that we unhift the
array intead of puhing. 'hi i !ecaue we want to !e 1rt parer and conume the
control tring value, a we need to e8ecute the validation function !efore a converion to
num!er occur.
'he econd directive i a smart-float. It pare !oth 1.2 and 1,2 into a valid
>oat num!er 1.2. 3ote that we can"t ue input type number here a +',-5 !rower
would not allow the uer to type what it would conider an invalid num!er uch a 1,2.
Source
9dit
inde8.html
cript.7
1. <!doctype html>
2. <html ng-app="6orm-e-ample1">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di! ng-controller="#ontroller">
9. <6orm name="6orm" class="css-6orm" no!alidate>
10. <di!>
11. AiSe 4integer 0 - 105:
12. <input type="numer" ng-model="siSe" name="siSe"
13. min="0" ma-="10" integer />))siSe,,<r />
14. <span ng-shoL="6orm.siSe.Kerror.integer">(his is not !alid integer!</span>
15. <span ng-shoL="6orm.siSe.Kerror.min ++ 6orm.siSe.Kerror.ma-">
16. (he !alue must e in range 0 to 10!</span>
17. </di!>
18.
19. <di!>
20. ;ength 46loat5:
21. <input type="te-t" ng-model="length" name="length" smart-6loat />
3$
4%
22. ))length,,<r />
23. <span ng-shoL="6orm.length.Kerror.6loat">
24. (his is not a !alid 6loat numer!</span>
25. </di!>
26. </6orm>
27. </di!>
28. </ody>
29. </html>
Demo
%i;e *integer 0 ( 10/$ ',-Direct
-ength *>oat/$ ',-Direct
5.' I!ple!enting custo! &or! controls <usingngModel=
&ngular implement all of the !aic +',- form control *input, select, textarea/, which hould
!e uf1cient for mot cae. +owever, if you need more >e8i!ility, you can write your own
form control a a directive.
In order for cutom control to wor# with ngModel and to achieve two(way data(!inding it
need to$
implement $render method, which i reponi!le for rendering the data after it
paed the/g!odelController0'1or(atters,
call $setViewValue method, whenever the uer interact with the control and
model need to !e updated. 'hi i uually done inide a D0, 9vent litener.
%ee AcompileBrovider.directive for more info.
'he following e8ample how how to add two(way data(!inding to content9dita!le
element.
Source
9dit
inde8.html
cript.7
1. <!doctype html>
2. <html ng-app="6orm-e-ample0">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di! content9ditale="true" ng-model="content" title="#lic< to edit">Aome</di!>
9. <pre>model = ))content,,</pre>
10.
11. <style type="te-t/css">
12. di!?content9ditaleC )
13. cursor: pointer7
14. ac<ground-color: W8080807
15. ,
16. </style>
17. </ody>
18. </html>
Demo
%ome
model = Aome
4%
41
8 I15n and .1An in Angular?S
What i i1Ln and l10nT
Internationali;ation, a!!reviated i1Ln, i the proce of developing product in uch a way
that they can !e locali;ed for language and culture eaily. -ocali;ation, a!!reviated l10n,
i the proce of adapting application and te8t to ena!le their ua!ility in a particular
cultural or linguitic mar#et. Cor application developer, internationali;ing an application
mean a!tracting all of the tring and other locale(peci1c !it *uch a date or currency
format/ out of the application. -ocali;ing an application mean providing tranlation and
locali;ed format for the a!tracted !it.
What level of upport for i1Ln<l10n i currently in &ngularT
.urrently, &ngular upport i1Ln<l10n for datetime, num!er and currency 1lter.
&dditionally, &ngular upport locali;a!le plurali;ation upport provided !y the ngPluralize
directive.
&ll locali;a!le &ngular component depend on locale(peci1c rule et managed !y
the $locale service.
Cor reader who want to 7ump traight into e8ample, we have a few we! page that
howcae how to ue &ngular 1lter with variou locale rule et. :ou can 1nd thee
e8ample either on Githu! or in the i1Ln<e2e folder of &ngular development pac#age.
What i a locale idT
& locale i a peci1c geographical, political, or cultural region. 'he mot commonly ued
locale ID conit of two part$ language code and country code. Cor e8ample, en(2%, en(
&2, ;h(.3 are all valid locale ID that have !oth language code and country code.
5ecaue pecifying a country code in locale ID i optional, locale ID uch a en, ;h, and #
are alo valid. %ee the I.2 we!ite for more information a!out uing locale ID.
%upported locale in &ngular &ngular eparate num!er and datetime format rule et into
different 1le, each 1le for a particular locale. :ou can 1nd a lit of currently upported
locale here
8.1 (ro0iding locale rules to Angular
'here are two approache to providing locale rule to &ngular$
1. Bre(!undled rule et
:ou can pre(!undle the deired locale 1le with &ngular !y concatenating the content of the
locale(peci1c 1le to the end of angular.js or angular.min.js 1le.
Cor e8ample on Uni8, to create an angular.7 1le that contain locali;ation rule for german
locale, you can do the following$
cat angular.js i18n/angular-locale_de-ge.js > angular_de-ge.js
When the application containing angular_de-ge.js cript intead of the generic
angular.7 cript tart, &ngular i automatically pre(con1gured with locali;ation rule for the
german locale.
2. Including locale 7 cript in inde8.html page
:ou can alo include the locale peci1c 7 1le in the inde8.html page. Cor e8ample, if one
client re6uire German locale, you would erve inde8Sde(ge.html which will loo# omething
li#e thi$
1. <html ng-app>
2. <head>
3. Y.
41
42
4. <script src="angular.js"></script>
5. <script src="i1Hn/angular-localePde-ge.js"></script>
6. Y.
7. </head>
8. </html>
.omparion of the two approache 5oth approache decri!ed a!ove re6uire you to
prepare different inde8.html page or 7 1le for each locale that your app may !e locali;ed
into. :ou alo need to con1gure your erver to erve the correct 1le that correpond to the
deired locale.
+owever, the econd approach *Including locale 7 cript in inde8.html page/ i li#ely to !e
lower !ecaue an e8tra cript need to !e loaded.
8.2 BCotchasB
.urrency ym!ol DgotchaD
&ngular" currency 1lter allow you to ue the default currency ym!ol from the locale
service, or you can provide the 1lter with a cutom currency ym!ol. If your app will !e ued
only in one locale, it i 1ne to rely on the default currency ym!ol. +owever, if you anticipate
that viewer in other locale might ue your app, you hould provide your own currency
ym!ol to ma#e ure the actual value i undertood.
Cor e8ample, if you want to diplay account !alance of 1000 dollar with the following
!inding containing currency 1lter${{ 1000 | currency }}, and your app i currently in
en(2% locale. "A1000.00" will !e hown. +owever, if omeone in a different local *ay, )apan/
view your app, her !rower will pecify the locale a 7a, and the !alance of "V1000.00" will
!e hown intead. 'hi will really upet your client.
In thi cae, you need to override the default currency ym!ol !y providing the currency
1lter with a currency ym!ol a a parameter when you con1gure the 1lter, for e8ample,
2%DA1,000.00. 'hi way, &ngular will alway how a !alance of "2%DA1000" and diregard
any locale change.
'ranlation length DgotchaD
Ieep in mind that tranlated tring<datetime format can vary greatly in length. Cor
e8ample, June 3, 1977 will !e tranlated to %panih a 3 de junio de 1977. 'here
are !ound to !e other more e8treme cae. +ence, when internationali;ing your app, you
need to apply .%% rule accordingly and do thorough teting to ma#e ure 2I component
do not overlap.
'ime;one
Ieep in mind that &ngular datetime 1lter ue the time ;one etting of the !rower. %o the
ame application will how different time information depending on the time ;one etting of
the computer that the application i running on. 3either )avacript nor &ngular currently
upport diplaying the date with a time;one peci1ed !y the developer.
1A Internet Eplorer co!pati)ility
'hi document decri!e the Internet 98plorer *I9/ idioyncraie when dealing with cutom
+',- attri!ute and tag. =ead thi document if you are planning on deploying your
&ngular application on I9 vL.0 or earlier.
1A.1 Short 2ersion
'o ma#e your &ngular application wor# on I9 pleae ma#e ure that$
1. :ou poly1ll )%03.tringify if neceary *I9F will need thi/. :ou can
ue )%032 or )%033 poly1ll for thi.
42
43
1. <!doctype html>
2. <html -mlns:ng="http://angularjs.org">
3. <head>
4. <!--?i6 lte "9 HC>
5. <script src="/path/to/json0.js"></script>
6. <!?endi6C-->
7. </head>
8. <ody>
9. ...
10. </ody>
11. </html>
2. add id="ng-app" to the root element in con7unction with ng-app attri!ute
1. <!doctype html>
2. <html -mlns:ng="http://angularjs.org" id="ng-app" ng-app="optional.odule/ame">
3. ...
4. </html>
3. you do not ue cutom element tag uch a <ng:view> *ue the attri!ute
verion <div ng-view> intead/, or
4. if you do ue cutom element tag, then you mut ta#e thee tep to ma#e I9
happy$
1. <!doctype html>
2. <html -mlns:ng="http://angularjs.org" id="ng-app" ng-app="optional.odule/ame">
3. <head>
4. <!--?i6 lte "9 HC>
5. <script>
6. document.create9lement42ng-include257
7. document.create9lement42ng-pluraliSe257
8. document.create9lement42ng-!ieL257
9.
10. // =ptionally these 6or #AA
11. document.create9lement42ng:include257
12. document.create9lement42ng:pluraliSe257
13. document.create9lement42ng:!ieL257
14. </script>
15. <!?endi6C-->
16. </head>
17. <ody>
18. ...
19. </ody>
20. </html>
'he important part are$
xmlns:ng ( namespace ( you need one namepace for each cutom tag you are
planning on uing.
document.createElement(yourTagName) ( creation of custom tag names (
%ince thi i an iue only for older verion of I9 you need to load it conditionally. Cor
each tag which doe not have namepace and which i not de1ned in +',- you need to
pre(declare it to ma#e I9 happy.
1A.2 .ong 2ersion
I9 ha iue with element tag name which are not tandard +',- tag name. 'hee fall
into two categorie, and each category ha it own 18.
If the tag name tart with my: pre18 than it i conidered an E,- namepace and
mut have correponding namepace declaration on <html xmlns:my="ignored">
43
44
If the tag ha no : !ut it i not a tandard +',- tag, then it mut !e pre(created
uingdocument.createElement('my-tag')
If you are planning on tyling the cutom tag with .%% elector, then it mut !e pre(
created uingdocument.createElement('my-tag') regardle of E,- namepace.
1A.2.1 $he Cood 9ews
'he good new i that thee retriction only apply to element tag name, and not to
element attri!ute name. %o thi re6uire no pecial handling in I9$ <div my-tag
your:tag> </div>.
1A.2.2 What happens i& I &ail to do this?
%uppoe you have +',- with un#nown tag mytag *thi could alo !e my:tag or my-
tag with ame reult/$
1. <html>
2. <ody>
3. <mytag>some te-t</mytag>
4. </ody>
5. </html>
It hould pare into the following D0,$
1. Wdocument
2. &- 1(.;
3. &- N=8M
4. &- mytag
5. &- Wte-t: some te-t
'he e8pected !ehavior i that the BODY element ha a child element mytag, which in turn
ha the te8t some text.
5ut thi i not what I9 doe *if the a!ove 18e are not included/$
1. Wdocument
2. &- 1(.;
3. &- N=8M
4. &- mytag
5. &- Wte-t: some te-t
6. &- /mytag
In I9, the !ehavior i that the BODY element ha three children$
1. & elf cloing mytag. 98ample of elf cloing tag i <br/>. 'he trailing / i optional,
!ut the <br> tag i not allowed to have any children, and !rower conider <br>some
text</br> a three i!ling not a <br> with some texta child.
2. & te8t node with some text. 'hi hould have !een a child of mytag a!ove, not a
i!ling.
3. & corrupt elf cloing /mytag. 'hi i corrupt ince element name are not allowed
to have the / character. Curthermore thi cloing element hould not !e part of the D0,
ince it i only ued to delineate the tructure of the D0,.
1A.3 /SS Styling o& /usto! $ag 9a!es
'o ma#e .%% elector wor# with cutom element, the cutom element name mut !e pre(
created withdocument.createElement('my-tag') regardle of E,- namepace.
1. <html -mlns:ng="needed 6or ng: namespace">
2. <head>
3. <!--?i6 lte "9 HC>
4. <script>
5. // needed to ma<e ng-include parse properly
44
45
6. document.create9lement42ng-include257
7.
8. // needed to enale #AA re6erence
9. document.create9lement42ng:!ieL257
10. </script>
11. <!?endi6C-->
12. <style>
13. ng%%:!ieL )
14. display: loc<7
15. order: 1p- solid red7
16. ,
17.
18. ng-include )
19. display: loc<7
20. order: 1p- solid lue7
21. ,
22. </style>
23. </head>
24. <ody>
25. <ng:!ieL></ng:!ieL>
26. <ng-include></ng-include>
27. ...
28. </ody>
11 What is a ,odule?
,ot application have a main method which intantiate, wire, and !oottrap the
application. &ngular app don"t have a main method. Intead module declaratively pecify
how an application hould !e !oottrapped. 'here are everal advantage to thi approach$
'he proce i more declarative which i eaier to undertand
In unit(teting there i no need to load all module, which may aid in writing unit(
tet.
&dditional module can !e loaded in cenario tet, which can override ome of the
con1guration and help end(to(end tet the application
'hird party code can !e pac#aged a reua!le module.
'he module can !e loaded in any<parallel order *due to delayed nature of module
e8ecution/.
11.1 $he *asics
0#, I"m in a hurry. +ow do I get a +ello World module wor#ingT
Important thing to notice$
!odule &BI
3otice the reference to the myApp module in the <html ng-app="myApp">, it i
what !oottrap the app uing your module.
Source
9dit
inde8.html
cript.7
1. <!doctype html>
2. <html ng-app="myJpp">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
45
46
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di!>
9. )) 23orld2 + greet ,,
10. </di!>
11. </ody>
12. </html>
Demo
+ello, WorldH
11.2 Reco!!ended Setup
While the e8ample a!ove i imple, it will not cale to large application. Intead we
recommend that you !rea# your application to multiple module li#e thi$
& ervice module, for ervice declaration
& directive module, for directive declaration
& 1lter module, for 1lter declaration
&nd an application level module which depend on the a!ove module, and which
ha initiali;ation code.
'he reaon for thi !rea#up i that in your tet, it i often neceary to ignore the
initiali;ation code, which tend to !e dif1cult to tet. 5y putting it into a eparate module it
can !e eaily ignored in tet. 'he tet can alo !e more focued !y only loading the
module that are relevant to tet.
'he a!ove i only a uggetion, o feel free to tailor it to your need.
Source
9dit
inde8.html
cript.7
1. <!doctype html>
2. <html ng-app="-mpl">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di! ng-controller="Tmpl#ontroller">
9. )) greeting ,,!
10. </di!>
11. </ody>
12. </html>
Demo
5on7our WorldHH
11.3 ,odule .oading D "ependencies
& module i a collection of con1guration and run !loc# which get applied to the application
during the !oottrap proce. In it implet form the module conit of collection of two
#ind of !loc#$
1. .on1guration !loc# ( get e8ecuted during the provider regitration and
con1guration phae. 0nly provider and contant can !e in7ected into con1guration
46
47
!loc#. 'hi i to prevent accidental intantiation of ervice !efore they have !een fully
con1gured.
2. =un !loc# ( get e8ecuted after the in7ector i created and are ued to #ic#tart the
application. 0nly intance and contant can !e in7ected into run !loc#. 'hi i to
prevent further ytem con1guration during application run time.
1. angular.module42my.odule2@ ?C5.
2. con6ig46unction4injectales5 ) // pro!ider-injector
3. // (his is an e-ample o6 con6ig loc<.
4. // Mou can ha!e as many o6 these as you Lant.
5. // Mou can only inject Xro!iders 4not instances5
6. // into the con6ig loc<s.
7. ,5.
8. run46unction4injectales5 ) // instance-injector
9. // (his is an e-ample o6 a run loc<.
10. // Mou can ha!e as many o6 these as you Lant.
11. // Mou can only inject instances 4not Xro!iders5
12. // into the run loc<s
13. ,57
11.3.1 /on&iguration *loc:s
'here are ome convenience method on the module which are e6uivalent to the con1g
!loc#. Cor e8ample$
1. angular.module42my.odule2@ ?C5.
2. !alue42a2@ 10D5.
3. 6actory42a2@ 6unction45 ) return 10D7 ,5.
4. directi!e42directi!e/ame2@ ...5.
5. 6ilter426ilter/ame2@ ...57
6.
7. // is same as
8.
9. angular.module42my.odule2@ ?C5.
10. con6ig46unction4Kpro!ide@ KcompileXro!ider@ K6ilterXro!ider5 )
11. Kpro!ide.!alue42a2@ 10D57
12. Kpro!ide.6actory42a2@ 6unction45 ) return 10D7 ,57
13. KcompileXro!ider.directi!e42directi!e/ame2@ ...57
14. K6ilterXro!ider.register426ilter/ame2@ ...57
15. ,57
'he con1guration !loc# get applied in the order in which they are regitered. 'he only
e8ception to it are contant de1nition, which are placed at the !eginning of all
con1guration !loc#.
11.3.2 Run *loc:s
=un !loc# are the cloet thing in &ngular to the main method. & run !loc# i the code
which need to run to #ic#tart the application. It i e8ecuted after all of the ervice have
!een con1gured and the in7ector ha !een created. =un !loc# typically contain code which
i hard to unit(tet, and for thi reaon hould !e declared in iolated module, o that they
can !e ignored in the unit(tet.
11.3.3 "ependencies
,odule can lit other module a their dependencie. Depending on a module implie that
re6uired module need to !e loaded !efore the re6uiring module i loaded. In other word
the con1guration !loc# of the re6uired module e8ecute !efore the con1guration !loc# of
the re6uiring module. 'he ame i true for the run !loc#. 9ach module can only !e loaded
once, even if multiple other module re6uire it.
47
48
11.3.# Asynchronous .oading
,odule are a way of managing Ain7ector con1guration, and have nothing to do with loading
of cript into a 4,. 'here are e8iting pro7ect which deal with cript loading, which may
!e ued with &ngular. 5ecaue module do nothing at load time they can !e loaded into the
4, in any order and thu cript loader can ta#e advantage of thi property and paralleli;e
the loading proce.
11.# 1nit $esting
In it implet form a unit tet i a way of intantiating a u!et of the application in tet and
then applying a timulu to it. It i important to reali;e that each module can only !e loaded
once per in7ector. 'ypically an app ha only one in7ector. 5ut in tet, each tet ha it own
in7ector, which mean that the module are loaded multiple time per 4,. Broperly
tructured module can help with unit teting, a in thi e8ample$
In all of thee e8ample we are going to aume thi module de1nition$
1. angular.module42greet.od2@ ?C5.
2.
3. 6actory42alert2@ 6unction4KLindoL5 )
4. return 6unction4te-t5 )
5. KLindoL.alert4te-t57
6. ,
7. ,5.
8.
9. !alue42salutation2@ 21ello25.
10.
11. 6actory42greet2@ 6unction4alert@ salutation5 )
12. return 6unction4name5 )
13. alert4salutation & 2 2 & name & 2!257
14. ,
15. ,57
-et" write ome tet$
1. descrie42myJpp2@ 6unction45 )
2. // load the rele!ant application modules then load a special
3. // test module Lhich o!errides the KLindoL Lith a moc< !ersion@
4. // so that calling LindoL.alert45 Lill not loc< the test
5. // runner Lith a real alert o-. (his is an e-ample o6 o!erriding
6. // con6iguration in6ormation in tests.
7. e6ore9ach4module42greet.od2@ 6unction4Kpro!ide5 )
8. Kpro!ide.!alue42KLindoL2@ )
9. alert: jasmine.createApy42alert25
10. ,57
11. ,557
12.
13. // (he inject45 Lill create the injector and inject the greet and
14. // KLindoL into the tests. (he test need not concern itsel6 Lith
15. // Liring o6 the application@ only Lith testing it.
16. it42should alert on KLindoL2@ inject46unction4greet@ KLindoL5 )
17. greet423orld257
18. e-pect4KLindoL.alert5.to1a!eNeen#alled3ith421ello 3orld!257
19. ,557
20.
21. // this is another Lay o6 o!erriding con6iguration in the
22. // tests using an inline module and inject methods.
23. it42should alert using the alert ser!ice2@ 6unction45 )
24. !ar alertApy = jasmine.createApy42alert257
48
4$
25. module46unction4Kpro!ide5 )
26. Kpro!ide.!alue42alert2@ alertApy57
27. ,57
28. inject46unction4greet5 )
29. greet423orld257
30. e-pect4alertApy5.to1a!eNeen#alled3ith421ello 3orld!257
31. ,57
32. ,57
33. ,57
12 What are Scopes?
scope i an o!7ect that refer to the application model. It i an e8ecution conte8t
for e8preion. %cope are arranged in hierarchical tructure which mimic the D0,
tructure of the application. %cope can watch e8preion and propagate event.
12.1 Scope characteristics
%cope provide &BI *$watch/ to o!erve model mutation.
%cope provide &BI *$apply/ to propagate any model change through the ytem
into the view from outide of the D&ngular realmD *controller, ervice, &ngular event
handler/.
%cope can !e neted to iolate application component while providing acce to
hared model propertie. & cope *prototypically/ inherit propertie from it parent
cope.
%cope provide conte8t againt which e8preion are evaluated. Cor
e8ample {{username}} e8preion i meaningle, unle it i evaluated againt a
peci1c cope which de1ne the username property.
12.2 Scope as "ata-,odel
%cope i the glue !etween application controller and the view. During the
template lin#ing phae the directives et up$watch e8preion on the cope.
'he $watch allow the directive to !e noti1ed of property change, which allow the
directive to render the updated value to the D0,.
5oth controller and directive have reference to the cope, !ut not to each other. 'hi
arrangement iolate the controller from the directive a well a from D0,. 'hi i an
important point ince it ma#e the controller view agnotic, which greatly improve the
teting tory of the application.
Source
9dit
inde8.html
cript.7
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. </head>
7. <ody>
8. <di! ng-controller=".y#ontroller">
9. Mour name:
10. <input type="te-t" ng-model="username">
11. <utton ng-clic<=2say1ello452>greet</utton>
4$
5%
12. <hr>
13. ))greeting,,
14. </di!>
15. </ody>
16. </html>
Demo
:our name$ ',-Direct greet
In the a!ove e8ample notice that the MyController aign World to
the username property of the cope. 'he cope then noti1e the input of the aignment,
which then render the input with uername pre(1lled. 'hi demontrate how a controller
can write data into the cope.
%imilarly the controller can aign !ehavior to cope a een !y the sayHello method,
which i invo#ed when the uer clic# on the "greet" !utton. 'he sayHello method can
read the username property and create a greeting property. 'hi demontrate that the
propertie on cope update automatically when they are !ound to +',- input widget.
-ogically the rendering of {{greeting}} involve$
retrieval of the cope aociated with D0, node where {{greeting}} i de1ned in
template. In thi e8ample thi i the ame cope a the cope which wa paed
into MyController. *We will dicu cope hierarchie later./
9valuate the greeting e8preion againt the cope retrieved a!ove, and aign
the reult to the te8t of the encloing D0, element.
:ou can thin# of the cope and it propertie a the data which i ued to render the view.
'he cope i the ingle ource(of(truth for all thing view related.
Crom a teta!ility point of view, the eparation of the controller and the view i deira!le,
!ecaue it allow u to tet the !ehavior without !eing ditracted !y the rendering detail.
1. it42should say hello2@ 6unction45 )
2. !ar scope.oc< = ),7
3. !ar cntl = neL .y#ontroller4scope.oc<57
4.
5. // Jssert that username is pre-6illed
6. e-pect4scope.oc<.username5.to9'ual423orld257
7.
8. // Jssert that Le read neL username and greet
9. scope.oc<.username = 2angular27
10. scope.oc<.say1ello457
11. e-pect4scope.oc<.greeting5.to9'ual421ello angular!257
12. ,57
12.3 Scope -ierarchies
9ach &ngular application ha e8actly one root scope, !ut may have everal child cope.
'he application can have multiple cope, !ecaue ome directive create new child
cope *refer to directive documentation to ee which directive create new cope/. When
new cope are created, they are added a children of their parent cope. 'hi create a
tree tructure which parallel the D0, where they"re attached
When &ngular evaluate {{username}}, it 1rt loo# at the cope aociated with the
given element for the usernameproperty. If no uch property i found, it earche the parent
cope and o on until the root cope i reached. In )ava%cript thi !ehavior i #nown a
prototypical inheritance, and child cope prototypically inherit from their parent.
'hi e8ample illutrate cope in application, and prototypical inheritance of propertie.
5%
51
Source
9dit
inde8.html
tyle.c
cript.7
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. </head>
7. <ody>
8. <di! ng-controller="9mployee#ontroller">
9. .anager: ))employee.name,, ? ))department,, C<r>
10. Ueports:
11. <ul>
12. <li ng-repeat="employee in employee.reports">
13. ))employee.name,, ? ))department,, C
14. </li>
15. </ul>
16. <hr>
17. ))greeting,,
18. </di!>
19. </ody>
20. </html>
Demo
,anager$ )oe the ,anager M 9ngineering N
=eport$
)ohn %mith M 9ngineering N
,ary =un M 9ngineering N
3otice that &ngular automatically place ng-scope cla on element where cope are
attached. 'he <style>de1nition in thi e8ample highlight in red the new cope location.
'he child cope are neceary !ecaue the repeater
evaluate {{employee.name}} e8preion, !ut depending on which cope the e8preion
i evaluated it produce different reult. %imilarly the evaluation
of {{department}} prototypically inherit from root cope, a it i the only place where
the department property i de1ned.
12.# Retrie0ing Scopes &ro! the ">,.
%cope are attached to the D0, a $scope data property, and can !e retrieved for
de!ugging purpoe. *It i unli#ely that one would need to retrieve cope in thi way inide
the application./ 'he location where the root cope i attached to the D0, i de1ned !y the
location of ng-app directive. 'ypically ng-app i placed on the <html> element, !ut it can
!e placed on other element a well, if, for e8ample, only a portion of the view need to !e
controlled !y &ngular.
'o e8amine the cope in the de!ugger$
1. right clic# on the element of interet in your !rower and elect "inpect element".
:ou hould ee the !rower de!ugger with the element you clic#ed on highlighted.
2. 'he de!ugger allow you to acce the currently elected element in the conole
a $0 varia!le.
51
52
3. 'o retrieve the aociated cope in conole
e8ecute$ angular.element($0).scope()
12.' Scope E0ents (ropagation
%cope can propagate event in imilar fahion to D0, event. 'he event can
!e broadcasted to the cope children oremitted to cope parent.
Source
9dit
inde8.html
cript.7
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. </head>
7. <ody>
8. <di! ng-controller="9!ent#ontroller">
9. Uoot scope <tt>.y9!ent</tt> count: ))count,,
10. <ul>
11. <li ng-repeat="i in ?1C" ng-controller="9!ent#ontroller">
12. <utton ng-clic<="Kemit42.y9!ent25">Kemit42.y9!ent25</utton>
13. <utton ng-clic<="Kroadcast42.y9!ent25">Kroadcast42.y9!ent25</utton>
14. <r>
15. .iddle scope <tt>.y9!ent</tt> count: ))count,,
16. <ul>
17. <li ng-repeat="item in ?1@ 0C" ng-controller="9!ent#ontroller">
18. ;ea6 scope <tt>.y9!ent</tt> count: ))count,,
19. </li>
20. </ul>
21. </li>
22. </ul>
23. </di!>
24. </ody>
25. </html>
Demo
=oot cope MyEvent count$ 0
Aemit*",y9vent"/ A!roadcat*",y9vent"/
,iddle cope MyEvent count$ 0
-eaf cope MyEvent count$ 0
-eaf cope MyEvent count$ 0
12.3 Scope .i&e /ycle
'he normal >ow of a !rower receiving an event i that it e8ecute a correponding
)ava%cript call!ac#. 0nce the call!ac# complete the !rower re(render the D0, and
return to waiting for more event.
When the !rower call into )ava%cript the code e8ecute outide the &ngular e8ecution
conte8t, which mean that &ngular i unaware of model modi1cation. 'o properly proce
model modi1cation the e8ecution ha to enter the &ngular e8ecution conte8t uing
the $apply method. 0nly model modi1cation which e8ecute inide the $applymethod will
!e properly accounted for !y &ngular. Cor e8ample if a directive liten on D0, event,
uch a ng-click it mut evaluate the e8preion inide the $apply method.
52
53
&fter evaluating the e8preion, the $apply method perform a $digest. In the Adiget
phae the cope e8amine all of the $watch e8preion and compare them with the
previou value. 'hi dirty chec#ing i done aynchronouly. 'hi mean that aignment
uch a $scope.username="angular" will not immediately caue a $watch to !e
noti1ed, intead the $watch noti1cation i delayed until the $digest phae. 'hi delay i
deira!le, ince it coalece multiple model update into one $watch noti1cation a well a
it guarantee that during the $watch noti1cation no other$watche are running. If
a $watch change the value of the model, it will force additional $digest cycle.
1. .reation
'he root scope i created during the application !oottrap !y the $injector. During
template lin#ing, ome directive create new child cope.
2. Watcher regitration
During template lin#ing directive regiter watches on the cope. 'hee watche will !e
ued to propagate model value to the D0,.
3. ,odel mutation
Cor mutation to !e properly o!erved, you hould ma#e them only within the scope.
$apply(). *&ngular &BI do thi implicitly, o no e8tra $apply call i needed when doing
ynchronou wor# in controller, or aynchronou wor# with $http or $timeout ervice.
4. ,utation o!ervation
&t the end $apply, &ngular perform a $digest cycle on the root cope, which then
propagate throughout all child cope. During the $digest cycle, all $watched
e8preion or function are chec#ed for model mutation and if a mutation i detected,
the $watch litener i called.
5. %cope detruction
When child cope are no longer needed, it i the reponi!ility of the child cope
creator to detroy them viascope.$destroy() &BI. 'hi will top propagation
of $digest call into the child cope and allow for memory ued !y the child cope
model to !e reclaimed !y the gar!age collector.
12.3.1 Scopes and "irecti0es
During the compilation phae, the compiler matche directives againt the D0, template.
'he directive uually fall into one of two categorie$
0!erving directives, uch a dou!le(curly e8preion {{expression}}, regiter
litener uing the$watch() method. 'hi type of directive need to !e noti1ed whenever
the e8preion change o that it can update the view.
-itener directive, uch a ng-click, regiter a litener with the D0,. When the D0,
litener 1re, the directive e8ecute the aociated e8preion and update the view
uing the $apply() method.
When an e8ternal event *uch a a uer action, timer or E+=/ i received, the
aociated e8preion mut !e applied to the cope through the $apply() method o that all
litener are updated correctly.
12.3.2 "irecti0es that /reate Scopes
In mot cae, directives and cope interact !ut do not create new intance of cope.
+owever, ome directive, uch a ng-controller and ng-repeat, create new child cope and
attach the child cope to the correponding D0, element. :ou can retrieve a cope for any
D0, element !y uing anangular.element(aDomElement).scope() method call.
53
54
12.3.3 /ontrollers and Scopes
%cope and controller interact with each other in the following ituation$
.ontroller ue cope to e8poe controller method to template *ee ng-controller/.
.ontroller de1ne method *!ehavior/ that can mutate the model *propertie on the
cope/.
.ontroller may regiter watches on the model. 'hee watche e8ecute immediately
after the controller !ehavior e8ecute.
%ee the ng-controller for more information.
12.3.# Scope $watch (er&or!ance /onsiderations
Dirty chec#ing the cope for property change i a common operation in &ngular and for
thi reaon the dirty chec#ing function mut !e ef1cient. .are hould !e ta#en that the dirty
chec#ing function doe not do any D0, acce, a D0, acce i order of magnitude
lower then property acce on )ava%cript o!7ect.
13 "ependency In7ection
Dependency In7ection *DI/ i a oftware deign pattern that deal with how code get hold of
it dependencie.
Cor in(depth dicuion a!out DI, ee Dependency In7ection at Wi#ipedia, Inverion of
.ontrol !y ,artin Cowler, or read a!out DI in your favorite oftware deign pattern !oo#.
13.1 "I in a nutshell
'here are only three way an o!7ect or a function can get a hold of it dependencie$
1. 'he dependency can !e created, typically uing the new operator.
2. 'he dependency can !e loo#ed up !y referring to a glo!al varia!le.
3. 'he dependency can !e paed in to where it i needed.
'he 1rt two option of creating or loo#ing up dependencie are not optimal !ecaue they
hard code the dependency. 'hi ma#e it dif1cult, if not impoi!le, to modify the
dependencie. 'hi i epecially pro!lematic in tet, where it i often deira!le to provide
moc# dependencie for tet iolation.
'he third option i the mot via!le, ince it remove the reponi!ility of locating the
dependency from the component. 'he dependency i imply handed to the component.
1. 6unction Aome#lass4greeter5 )
2. this.greeter = greeter7
3. ,
4.
5. Aome#lass.prototype.doAomething = 6unction4name5 )
6. this.greeter.greet4name57
7. ,
In the a!ove e8ample SomeClass i not concerned with locating the greeter dependency,
it i imply handed thegreeter at runtime.
'hi i deira!le, !ut it put the reponi!ility of getting hold of the dependency on the code
that contruct SomeClass.
'o manage the reponi!ility of dependency creation, each &ngular application ha
an injector. 'he in7ector i a ervice locator that i reponi!le for contruction and loo#up of
dependencie.
+ere i an e8ample of uing the in7ector ervice$
1. // Xro!ide the Liring in6ormation in a module
54
55
2. angular.module42my.odule2@ ?C5.
3.
4. // (each the injector hoL to uild a 2greeter2
5. // /otice that greeter itsel6 is dependent on 2KLindoL2
6. 6actory42greeter2@ 6unction4KLindoL5 )
7. // (his is a 6actory 6unction@ and is responsile 6or
8. // creating the 2greet2 ser!ice.
9. return )
10. greet: 6unction4te-t5 )
11. KLindoL.alert4te-t57
12. ,
13. ,7
14. ,57
15.
16. // /eL injector is created 6rom the module.
17. // 4(his is usually done automatically y angular ootstrap5
18. !ar injector = angular.injector4?2my.odule2@ 2ng2C57
19.
20. // Ue'uest any dependency 6rom the injector
21. !ar greeter = injector.get42greeter257
&#ing for dependencie olve the iue of hard coding, !ut it alo mean that the in7ector
need to !e paed throughout the application. Baing the in7ector !rea# the -aw of
Demeter. 'o remedy thi, we turn the dependency loo#up reponi!ility to the in7ector !y
declaring the dependencie a in thi e8ample$
1. <!-- :i!en this 1(.; -->
2. <di! ng-controller=".y#ontroller">
3. <utton ng-clic<="say1ello45">1ello</utton>
4. </di!>
1. // Jnd this controller de6inition
2. 6unction .y#ontroller4Kscope@ greeter5 )
3. Kscope.say1ello = 6unction45 )
4. greeter.greet421ello 3orld257
5. ,7
6. ,
7.
8. // (he 2ng-controller2 directi!e does this ehind the scenes
9. injector.instantiate4.y#ontroller57
3otice that !y having the ng-controller intantiate the cla, it can atify all of the
dependencie ofMyController without the controller ever #nowing a!out the in7ector. 'hi
i the !et outcome. 'he application code imply a# for the dependencie it need, without
having to deal with the in7ector. 'hi etup doe not !rea# the -aw of Demeter.
13.2 "ependency Annotation
+ow doe the in7ector #now what ervice need to !e in7ectedT
'he application developer need to provide annotation information that the in7ector ue in
order to reolve the dependencie. 'hroughout &ngular certain &BI function are invo#ed
uing the in7ector, a per the &BI documentation. 'he in7ector need to #now what ervice
to in7ect into the function. 5elow are three e6uivalent way of annotating your code with
ervice name information. 'hee can !e ued interchangea!ly a you ee 1t and are
e6uivalent.
55
56
13.3 In&erring "ependencies
'he implet way to get hold of the dependencie, i to aume that the function parameter
name are the name of the dependencie.
1. 6unction .y#ontroller4Kscope@ greeter5 )
2. ...
3. ,
Given a function the in7ector can infer the name of the ervice to in7ect !y e8amining the
function declaration and e8tracting the parameter name. In the a!ove e8ample $scope,
and greeter are two ervice which need to !e in7ected into the function.
While traightforward, thi method will not wor# with )ava%cript mini1er<o!fucator a
they rename the method parameter name. 'hi ma#e thi way of annotating only ueful
for pretotyping, and demo application.
13.# $inject Annotation
'o allow the minifer to rename the function parameter and till !e a!le to in7ect right
ervice the function need to !e annotate with the $inject property.
'he $inject property i an array of ervice name to in7ect.
1. !ar .y#ontroller = 6unction4renamedKscope@ renamed:reeter5 )
2. ...
3. ,
4. .y#ontroller.Kinject = ?2Kscope2@ 2greeter2C7
.are mut !e ta#en that the $inject annotation i #ept in ync with the actual argument
in the function declaration.
'hi method of annotation i ueful for controller declaration ince it aign the annotation
information with the function.
13.' Inline Annotation
%ometime uing the $inject annotation tyle i not convenient uch a when annotating
directive.
Cor e8ample$
1. some.odule.6actory42greeter2@ 6unction4KLindoL5 )
2. ...
3. ,57
=eult in code !loat due to needing a temporary varia!le$
1. !ar greeterBactory = 6unction4renamedKLindoL5 )
2. ...
3. ,7
4.
5. greeterBactory.Kinject = ?2KLindoL2C7
6.
7. some.odule.6actory42greeter2@ greeterBactory57
Cor thi reaon the third annotation tyle i provided a well.
1. some.odule.6actory42greeter2@ ?2KLindoL2@ 6unction4renamedKLindoL5 )
2. ...
3. ,C57
Ieep in mind that all of the annotation tyle are e6uivalent and can !e ued anywhere in
&ngular where in7ection i upported.
56
57
13.3 Where can I use "I?
DI i pervaive throughout &ngular. It i typically ued in controller and factory method.
13.3.1 "I in controllers
.ontroller are clae which are reponi!le for application !ehavior. 'he recommended
way of declaring controller i$
1. !ar .y#ontroller = 6unction4Kscope@ dep1@ dep05 )
2. ...
3. Kscope.a.ethod = 6unction45 )
4. ...
5. ,
6. ,
7. .y#ontroller.Kinject = ?2Kscope2@ 2dep12@ 2dep02C7
13.3.2 6actory !ethods
Cactory method are reponi!le for creating mot o!7ect in &ngular. 98ample are
directive, ervice, and 1lter. 'he factory method are regitered with the module, and the
recommended way of declaring factorie i$
1. angular.module42my.odule2@ ?C5.
2. con6ig4?2depXro!ider2@ 6unction4depXro!ider5)
3. ...
4. ,C5.
5. 6actory42ser!ice"d2@ ?2depAer!ice2@ 6unction4depAer!ice5 )
6. ...
7. ,C5.
8. directi!e42directi!e/ame2@ ?2depAer!ice2@ 6unction4depAer!ice5 )
9. ...
10. ,C5.
11. 6ilter426ilter/ame2@ ?2depAer!ice2@ 6unction4depAer!ice5 )
12. ...
13. ,C5.
14. run4?2depAer!ice2@ 6unction4depAer!ice5 )
15. ...
16. ,C57
1# A)out ,2/ in Angular
While ,odel(4iew(.ontroller *,4./ ha ac6uired different hade of meaning over the year
ince it 1rt appeared, &ngular incorporate the !aic principle !ehind the
original ,4. oftware deign pattern into it way of !uilding client(ide we! application.
'he ,4. pattern ummari;ed$
%eparate application into ditinct preentation, data, and logic component
9ncourage looe coupling !etween thee component
&long with ervice and dependency in7ection, ,4. ma#e angular application !etter
tructured, eaier to maintain and more teta!le.
'he following topic e8plain how angular incorporate the ,4. pattern into the angular way
of developing we! application$
2ndertanding the ,odel .omponent
2ndertanding the .ontroller .omponent
2ndertanding the 4iew .omponent
57
58
1' 1nderstanding the !odel co!ponent
Depending on the conte8t of the dicuion in the &ngular documentation, the
term model can refer to either a ingle o!7ect repreenting one entity *for e8ample, a model
called DphoneD with it value !eing an array of phone/ or the entire data model for the
application *all entitie/.
In &ngular, a model i any data that i reacha!le a a property of an angular %cope o!7ect.
'he name of the property i the model identi1er and the value i any )ava%cript o!7ect
*including array and primitive/.
'he only re6uirement for a )ava%cript o!7ect to !e a model in &ngular i that the o!7ect mut
!e referenced !y an &ngular cope a a property of that cope o!7ect. 'hi property
reference can !e created e8plicitly or implicitly.
:ou can create model !y e8plicitly creating cope propertie referencing )ava%cript
o!7ect in the following way$
,a#e a direct property aignment to the cope o!7ect in )ava%cript codeG thi mot
commonly occur in controller$
function MyCtrl($scope) { // create property 'foo' on the
MyCtrl's scope // and assign it an initial value 'bar'
$scope.foo = 'bar'; }
2e an angular e8preion with an aignment operator in template$
<button ng-click="{{foo='ball'}}">Click me</button>
2e ngInit directive in template *for toy<e8ample app only, not recommended for
real application/$
<body ng-init=" foo = 'bar' ">
&ngular create model implicitly *!y creating a cope property and aigning it a uita!le
value/ when proceing the following template contruct$
Corm input, elect, te8tarea and other form element$
<input ng-model="query" value="fluffy cloud">
'he code a!ove create a model called D6ueryD on the current cope with the value et
to D>uffy cloudD.
&n iterator declaration in ngRepeater$
<p ng-repeat="phone in phones"></p>
'he code a!ove create one child cope for each item in the DphoneD array and create
a DphoneD o!7ect *model/ on each of thee cope with it value et to the value of
DphoneD in the array.
In &ngular, a )ava%cript o!7ect top !eing a model when$
3o &ngular cope contain a property that reference the o!7ect.
&ll &ngular cope that contain a property referencing the o!7ect !ecome tale and
eligi!le for gar!age collection.
'he following illutration how a imple data model created implicitly from a imple
template$
58
5$
Related Topics
&!out ,4. in &ngular
2ndertanding the .ontroller .omponent
2ndertanding the 4iew .omponent
13 1nderstanding the /ontroller co!ponent
In &ngular, a controller i a )ava%cript function*type<cla/ that i ued to augment intance
of angular %cope, e8cluding the root cope.
2e controller to$
%et up the initial tate of a cope o!7ect.
&dd !ehavior to the cope o!7ect.
13.1 Setting up the initial state o& a scope o)7ect
'ypically, when you create an application you need to et up an initial tate for an &ngular
cope.
&ngular applie *in the ene of )ava%cript" Function#apply/ the controller contructor
function to a new &ngular cope o!7ect, which et up an initial cope tate. 'hi mean
that &ngular never create intance of the controller type *!y invo#ing the new operator on
the controller contructor/. .ontructor are alway applied to an e8iting cope o!7ect.
:ou et up the initial tate of a cope !y creating model propertie. Cor e8ample$
function Greeting.trl*Acope/ W Acope.greeting Q "+olaH"G X
'he GreetingCtrl controller create a greeting model which can !e referred to in a
template.
30'9$ ,any of the e8ample in the documentation how the creation of function in the
glo!al cope. 'hi i only for demontration purpoe ( in a real application you hould ue
the .controller method of your &ngular module for your application a follow$
var my&pp Q angular.module*"my&pp",MN/G
my&pp.controller*"Greeting.trl", M"Acope", function*Acope/ W Acope.greeting Q "+olaH"G XN/G
3ote alo that we ue the array notation to e8plicitly pecify the dependency of the
controller on the $scope ervice provided !y &ngular.
5$
6%
13.2 Adding *eha0ior to a Scope >)7ect
5ehavior on an &ngular cope o!7ect i in the form of cope method propertie availa!le to
the template<view. 'hi !ehavior interact with and modi1e the application model.
& dicued in the ,odel ection of thi guide, any o!7ect *or primitive/ aigned to the
cope !ecome model propertie. &ny function aigned to the cope are availa!le in the
template<view, and can !e invo#ed via angular e8preion and ng event handler directive
*e.g. ngClick/.
13.3 1sing /ontrollers /orrectly
In general, a controller houldn"t try to do too much. It hould contain only the !uine
logic needed for a ingle view.
'he mot common way to #eep controller lim i !y encapulating wor# that doen"t
!elong to controller into ervice and then uing thee ervice in controller via
dependency in7ection. 'hi i dicued in the Dependency Injection Services ection of thi
guide.
Do not ue controller for$
&ny #ind of D0, manipulation Y .ontroller hould contain only !uine logic.
D0, manipulationYthe preentation logic of an applicationYi well #nown for !eing
hard to tet. Butting any preentation logic into controller igni1cantly affect teta!ility
of the !uine logic. &ngular offer data!inding for automatic D0, manipulation. If you
have to perform your own manual D0, manipulation, encapulate the preentation logic
indirective.
Input formatting Y 2e angular form control intead.
0utput 1ltering Y 2e angular 1lter intead.
'o run tatele or tateful code hared acro controller Y 2e angular
ervice intead.
'o intantiate or manage the life(cycle of other component *for e8ample, to create
ervice intance/.
13.# Associating /ontrollers with Angular Scope >)7ects
:ou can aociate controller with cope o!7ect implicitly via the ngController
directive or $route service.
13.#.1 /ontroller /onstructor and ,ethods Ea!ple
'o illutrate how the controller component wor# in angular, let" create a little app with the
following component$
& template with two !utton and a imple meage
& model coniting of a tring named spice
& controller with two function that et the value of spice
'he meage in our template contain a !inding to the spice model, which !y default i et
to the tring DveryD. Depending on which !utton i clic#ed, the spice model i et
to chili or jalapeo, and the meage i automatically updated !y data(!inding.
13.#.2 A Spicy /ontroller Ea!ple
1. <ody ng-controller="Apicy#trl">
2. <utton ng-clic<="chiliApicy45">#hili</utton>
3. <utton ng-clic<="jalapenoApicy45">Zalape[o</utton>
4. <p>(he 6ood is ))spice,, spicy!</p>
6%
61
5. </ody>
6.
7. 6unction Apicy#trl4Kscope5 )
8. Kscope.spice = 2!ery27
9. Kscope.chiliApicy = 6unction45 )
10. Kscope.spice = 2chili27
11. ,
12. Kscope.jalapenoApicy = 6unction45 )
13. Kscope.spice = 2jalape[o27
14. ,
15. ,
'hing to notice in the e8ample a!ove$
'he ngController directive i ued to *implicitly/ create a cope for our template,
and the cope i augmented *managed/ !y the SpicyCtrl controller.
SpicyCtrl i 7ut a plain )ava%cript function. & an *optional/ naming convention
the name tart with capital letter and end with D.trlD or D.ontrollerD.
&igning a property to $scope create or update the model.
.ontroller method can !e created through direct aignment to cope
*the chiliSpicy method/
5oth controller method are availa!le in the template *for the body element and and
it children/.
35$ Breviou verion of &ngular *pre 1.0 =./ allowed you to
ue this interchangea!ly with the Acope method, !ut thi i no longer the cae. Inide
of method de1ned on the cope this and Acope are interchangea!le *angular
et this to Acope/, !ut not otherwie inide your controller contructor.
35$ Breviou verion of &ngular *pre 1.0 =./ added prototype method into the
cope automatically, !ut thi i no longer the caeG all method need to !e added
manually to the cope.
.ontroller method can alo ta#e argument, a demontrated in the following variation of
the previou e8ample.
13.#.3 /ontroller ,ethod Argu!ents Ea!ple
1. <ody ng-controller="Apicy#trl">
2. <input ng-model="customApice" !alue="Lasai">
3. <utton ng-clic<="spicy42chili25">#hili</utton>
4. <utton ng-clic<="spicy4customApice5">#ustom spice</utton>
5. <p>(he 6ood is ))spice,, spicy!</p>
6. </ody>
7.
8. 6unction Apicy#trl4Kscope5 )
9. Kscope.spice = 2!ery27
10. Kscope.spicy = 6unction4spice5 )
11. Kscope.spice = spice7
12. ,
13. ,
3otice that the SpicyCtrl controller now de1ne 7ut one method called spicy, which
ta#e one argument calledspice. 'he template then refer to thi controller method and
pae in a tring contant 'chili' in the !inding for the 1rt !utton and a model
property spice *!ound to an input !o8/ in the econd !utton.
61
62
13.#.# /ontroller Inheritance Ea!ple
.ontroller inheritance in &ngular i !aed on Scope inheritance. -et" have a loo# at an
e8ample$
1. <ody ng-controller=".ain#trl">
2. <p>:ood ))time=68ay,,@ ))name,,!</p>
3. <di! ng-controller="#hild#trl">
4. <p>:ood ))time=68ay,,@ ))name,,!</p>
5. <p ng-controller="Nay#trl">:ood ))time=68ay,,@ ))name,,!</p>
6. </di!>
7. </ody>
8.
9. 6unction .ain#trl4Kscope5 )
10. Kscope.time=68ay = 2morning27
11. Kscope.name = 2/i<<i27
12. ,
13.
14. 6unction #hild#trl4Kscope5 )
15. Kscope.name = 2.attie27
16. ,
17.
18. 6unction Nay#trl4Kscope5 )
19. Kscope.time=68ay = 2e!ening27
20. Kscope.name = 2:ingerrea< Nay27
21. ,
3otice how we neted three ngController directive in our template. 'hi template
contruct will reult in J cope !eing created for our view$
'he root cope
'he MainCtrl cope, which contain timeOfDay and name model
'he ChildCtrl cope, which hadow the name model from the previou cope
and inherit the timeOfDay model
'he BabyCtrl cope, which hadow !oth the timeOfDay model de1ned
in MainCtrl and name model de1ned in the .hild.trl
Inheritance wor# !etween controller in the ame way a it doe with model. %o in our
previou e8ample, all of the model could !e replaced with controller method that return
tring value.
3ote$ %tandard prototypical inheritance !etween two controller doen"t wor# a one might
e8pect, !ecaue a we mentioned earlier, controller are not intantiated directly !y &ngular,
!ut rather are applied to the cope o!7ect.
13.#.' $esting /ontrollers
&lthough there are many way to tet a controller, one of the !et convention, hown
!elow, involve in7ecting the$rootScope and $controller
.ontroller Cunction$
1. 6unction my#ontroller4Kscope5 )
2. Kscope.spices = ?)"name":"pasilla"@ "spiciness":"mild",@
3. )"name":"jalapeno"@ "spiceiness":"hot hot hot!",@
4. )"name":"haanero"@ "spiceness":";JVJ 1=(!!",C7
5.
6. Kscope.spice = "haanero"7
7. ,
.ontroller 'et$
1. descrie42my#ontroller 6unction2@ 6unction45 )
62
63
2.
3. descrie42my#ontroller2@ 6unction45 )
4. !ar scope7
5.
6. e6ore9ach4inject46unction4KrootAcope@ Kcontroller5 )
7. scope = KrootAcope.KneL457
8. !ar ctrl = Kcontroller4my#ontroller@ )Kscope: scope,57
9. ,557
10.
11. it42should create "spices" model Lith D spices2@ 6unction45 )
12. e-pect4scope.spices.length5.toNe4D57
13. ,57
14.
15. it42should set the de6ault !alue o6 spice2@ 6unction45 )
16. e-pect4scope.spice5.toNe42haanero257
17. ,57
18. ,57
19. ,57
If you need to tet a neted controller you need to create the ame cope hierarchy in your
tet that e8it in the D0,.
1. descrie42state2@ 6unction45 )
2. !ar mainAcope@ childAcope@ ayAcope7
3.
4. e6ore9ach4inject46unction4KrootAcope@ Kcontroller5 )
5. mainAcope = KrootAcope.KneL457
6. !ar main#trl = Kcontroller4.ain#trl@ )Kscope: mainAcope,57
7. childAcope = mainAcope.KneL457
8. !ar child#trl = Kcontroller4#hild#trl@ )Kscope: childAcope,57
9. ayAcope = child#trl.KneL457
10. !ar ay#trl = Kcontroller4Nay#trl@ )Kscope: ayAcope,57
11. ,557
12.
13. it42should ha!e o!er and selected2@ 6unction45 )
14. e-pect4mainAcope.time=68ay5.toNe42morning257
15. e-pect4mainAcope.name5.toNe42/i<<i257
16. e-pect4childAcope.time=68ay5.toNe42morning257
17. e-pect4childAcope.name5.toNe42.attie257
18. e-pect4ayAcope.time=68ay5.toNe42e!ening257
19. e-pect4ayAcope.name5.toNe42:ingerrea< Nay257
20. ,57
21. ,57
Related Topics
&!out ,4. in &ngular
2ndertanding the ,odel .omponent
2ndertanding the 4iew .omponent
14 1nderstanding the 2iew co!ponent
In &ngular, the view i the D0, loaded and rendered in the !rower, after &ngular ha
tranformed the D0, !aed on information in the template, controller and model.
63
64
In the &ngular implementation of ,4., the view ha #nowledge of !oth the model and the
controller. 'he view #now a!out the model where two(way data(!inding occur. 'he view
ha #nowledge of the controller through &ngular directive, uch a ngController and ngView,
and through !inding of thi form$ {{someControllerFunction()}}. In thee way, the
view can call function in an aociated controller function.
Related Topics
&!out ,4. in &ngular
2ndertanding the ,odel .omponent
2ndertanding the .ontroller .omponent
15 E2E testing
& application grow in i;e and comple8ity, it !ecome unrealitic to rely on manual teting
to verify the correctne of new feature, catch !ug and notice regreion.
'o olve thi pro!lem, we have !uilt an &ngular %cenario =unner which imulate uer
interaction that will help you verify the health of your &ngular application.
15.1 >0er0iew
:ou will write cenario tet in )ava%cript, which decri!e how your application hould
!ehave, given a certain interaction in a peci1c tate. & cenario i compried of one or
more it !loc# *you can thin# of thee a the re6uirement of your application/, which in
turn are made of command and e8pectation. .ommand tell the =unner to do omething
with the application *uch a navigate to a page or clic# on a !utton/, and e8pectation tell
the =unner to aert omething a!out the tate *uch a the value of a 1eld or the current
2=-/. If any e8pectation fail, the runner mar# the it a DfailedD and continue on to the
ne8t one. %cenario may alo have !efore9ach and after9ach !loc#, which will !e run
!efore *or after/ each it !loc#, regardle of whether they pa or fail.
64
65
In addition to the a!ove element, cenario may alo contain helper function to avoid
duplicating code in the it !loc#.
+ere i an e8ample of a imple cenario$
1. descrie42NuSS #lient2@ 6unction45 )
2. it42should 6ilter results2@ 6unction45 )
3. input42user25.enter42jac<sparroL257
4. element42:utton25.clic<457
5. e-pect4repeater42ul li25.count455.to9'ual41057
6. input426ilter(e-t25.enter42Nees257
7. e-pect4repeater42ul li25.count455.to9'ual4157
8. ,57
9. ,57
'hi cenario decri!e the re6uirement of a 5u;; .lient, peci1cally, that it hould !e a!le
to 1lter the tream of the uer. It tart !y entering a value in the "uer" input 1eld, clic#ing
the only !utton on the page, and then it veri1e that there are 10 item lited. It then enter
"5ee" in the "1lter'e8t" input 1eld and veri1e that the lit i reduced to a ingle item.
'he &BI ection !elow lit the availa!le command and e8pectation for the =unner.
15.2 A(I
%ource$ http$<<githu!.com<angular<angular.7<!lo!<mater<rc<ng%cenario<dl.7
pause()
Baue the e8ecution of the tet until you call resume() in the conole *or clic# the
reume lin# in the =unner 2I/.
1.3 sleep(seconds)
Baue the e8ecution of the tet for the peci1ed num!er of seconds.
65
66
1.# browser().navigateTo(url)
-oad the url into the tet frame.
1.' browser().navigateTo(url, fn)
-oad the 2=- returned !y fn into the teting frame. 'he given url i only ued for the tet
output. 2e thi when the detination 2=- i dynamic *that i, the detination i un#nown
when you write the tet/.
1.3 browser().reload()
=efrehe the currently loaded page in the tet frame.
1.4 browser().window().href()
=eturn the window.location.href of the currently loaded page in the tet frame.
1.5 browser().window().path()
=eturn the window.location.pathname of the currently loaded page in the tet frame.
1.8 browser().window().search()
=eturn the window.location.earch of the currently loaded page in the tet frame.
1.1A browser().window().hash()
=eturn the window.location.hah *without #/ of the currently loaded page in the tet frame.
1.11 browser().location().url()
=eturn the $location.url() of the currently loaded page in the tet frame.
1.12 browser().location().path()
=eturn the $location.path() of the currently loaded page in the tet frame.
1.13 )rowser<=.location<=.search<=
=eturn the $location.search() of the currently loaded page in the tet frame.
1.1# browser().location().hash()
=eturn the $location.hash() of the currently loaded page in the tet frame.
1.1' expect(future).!atcher"
&ert the value of the given future ati1e the matcher. &ll &BI tatement return
a future o!7ect, which get avalue aigned after they are e8ecuted. ,atcher are de1ned
uing angular.scenario.matcher, and they ue the value of future to run the
e8pectation. Cor
e8ample$expect(browser().location().href()).toEqual('http://www.googl
e.com'). &vaila!le matcher are preented further down thi document.
1.13 expect(future).not().!atcher"
&ert the value of the given future ati1e the negation of the matcher.
1.14 using(selector, label)
%cope the ne8t D%- element election.
66
67
1.15 binding(na!e)
=eturn the value of the 1rt !inding matching the given name.
1.18 input(na!e).enter(value)
9nter the given value in the te8t 1eld with the given name.
1.2A input(na!e).chec#()
.hec#<unchec# the chec#!o8 with the given name.
1.21 input(na!e).select(value)
%elect the given value in the radio !utton with the given name.
1.22 input(na!e).val()
=eturn the current value of an input 1eld with the given name.
1.23 repeater(selector, label).count()
=eturn the num!er of row in the repeater matching the given 7Zuery selector.
'he label i ued for tet output.
1.2# repeater(selector, label).row(index)
=eturn an array with the !inding in the row at the given index in the repeater matching
the given 7Zuery selector. 'he label i ued for tet output.
1.2' repeater(selector, label).colu!n(binding)
=eturn an array with the value in the column with the given binding in the repeater
matching the given 7Zueryselector. 'he label i ued for tet output.
1.23 select(na!e).option(value)
Bic# the option with the given value on the elect with the given name.
1.24 select(na!e).option(value$, value%...)
Bic# the option with the given values on the multi elect with the given name.
1.25 ele!ent(selector, label).count()
=eturn the num!er of element that match the given 7Zuery selector. 'he label i ued
for tet output.
1.28 ele!ent(selector, label).clic#()
.lic# on the element matching the given 7Zuery selector. 'he label i ued for tet
output.
1.3A ele!ent(selector, label).&uer'(fn)
98ecute the function fn(selectedElements, done), where elected9lement are the
element that match the given 7Zuery selector and done i a function that i called at the
end of the fn function. 'he label i ued for tet output.
67
68
1.31 ele!ent(selector, label).!ethod"()
=eturn the reult of calling method on the element matching the given 7Zuery selector,
where method can !e any of the following 7Zuery
method$ val, text, html, height, innerHeight, outerHeight, width, innerWidth,
outerWidth, position, scrollLeft, scrollTop, offset. 'he label i ued for tet
output.
1.32 ele!ent(selector, label).!ethod"(value)
98ecute the method paing in value on the element matching the given
7Zuery selector, where method can !e any of the following 7Zuery
method$ val, text, html, height, innerHeight, outerHeight, width, innerWidth,
outerWidth, position, scrollLeft, scrollTop, offset. 'he label i ued for tet
output.
1.33 ele!ent(selector, label).!ethod"(#e')
=eturn the reult of calling method paing in key on the element matching the given
7Zuery selector, wheremethod can !e any of the following 7Zuery
method$ attr, prop, css. 'he label i ued for tet output.
1.3# ele!ent(selector, label).!ethod"(#e', value)
98ecute the method paing in key and value on the element matching the given
7Zuery selector, where methodcan !e any of the following 7Zuery
method$ attr, prop, css. 'he label i ued for tet output.
)ava%cript i a dynamically typed language which come with great power of e8preion,
!ut it alo come with almot no(help from the compiler. Cor thi reaon we feel very trongly
that any code written in )ava%cript need to come with a trong et of tet. We have !uilt
many feature into angular which ma#e teting your angular application eay. %o there i
no e8cue for not teting.
15.3 ,atchers
,atcher are ued in com!ination with the expect(...) function a decri!ed a!ove and
can !e negated with not(). Cor
intance$ expect(element('h1').text()).not().toEqual('Error').
%ource$ http$<<githu!.com<angular<angular.7<!lo!<mater<rc<ng%cenario<matcher.7
1. // !alue and =ject comparison 6olloLing the rules o6 angular.e'uals45.
2. e-pect4!alue5.to9'ual4!alue5
3.
4. // a simpler !alue comparison using ===
5. e-pect4!alue5.toNe4!alue5
6.
7. // chec<s that the !alue is de6ined y chec<ing its type.
8. e-pect4!alue5.toNe8e6ined45
9.
10. // the 6olloLing tLo matchers are using Za!aAcript2s standard truthiness rules
11. e-pect4!alue5.toNe(ruthy45
12. e-pect4!alue5.toNeBalsy45
13.
14. // !eri6y that the !alue matches the gi!en regular e-pression. (he regular
15. // e-pression may e passed in 6orm o6 a string or a regular e-pression
16. // oject.
17. e-pect4!alue5.to.atch4e-pectedUeg9-p5
68
6$
18.
19. // a chec< 6or null using ===
20. e-pect4!alue5.toNe/ull45
21.
22. // Jrray.inde-=64...5 is used internally to chec< Lhether the element is
23. // contained Lithin the array.
24. e-pect4!alue5.to#ontain4e-pected5
25.
26. // numer comparison using < and >
27. e-pect4!alue5.toNe;ess(han4e-pected5
28. e-pect4!alue5.toNe:reater(han4e-pected5
15.# Ea!ple
%ee the angular(eed pro7ect for more e8ample.
15.#.1 /onditional actions with ele!ent<...=.Euery<&n=
929 teting with angular cenario i highly aynchronou and hide a lot of comple8ity !y
6ueueing action and e8pectation that can handle future. Crom time to time, you might
need conditional aertion or element election. 9ven though you hould generally try to
avoid thi *a it i can !e ign for unta!le tet/, you can add conditional !ehavior
withelement(...).query(fn). 'he following code liting how how thi function can
!e ued to delete added entrie *where an entry i ome domain o!7ect/ uing the
application" we! interface.
Imagine the application to !e tructure into two view$
1. Overview view which lit all the added entrie in a ta!le and
2. a detail view which how the entrie" detail and contain a delete !utton. When
clic#ing the delete !utton, the uer i redirected !ac# to the overview page.
1. e6ore9ach46unction 45 )
2. !ar delete9ntry = 6unction 45 )
3. roLser45.na!igate(o42/entries257
4.
5. // Le need to select the <tody> element as it might e the case that there
6. // are no entries 4and there6ore no roLs5. 3hen the selector does not
7. // result in a match@ the test Lould e mar<ed as a 6ailure.
8. element42tale tody25.'uery46unction 4tody@ done5 )
9. // ngAcenario gi!es us a j$uery lite Lrapped element. 3e call the
10. // \children45\ 6unction to retrie!e the tale ody2s roLs
11. !ar children = tody.children457
12.
13. i6 4children.length > 05 )
14. // i6 there is at least one entry in the tale@ clic< on the lin< to
15. // the entry2s detail !ieL
16. element42tale tody a25.clic<457
17. // and@ a6ter a route change@ clic< the delete utton
18. element42.tn-danger25.clic<457
19. ,
20.
21. // i6 there is more than one entry shoLn in the tale@ 'ueue another
22. // delete action.
23. i6 4children.length > 15 )
24. delete9ntry457
25. ,
26.
27. // rememer to call \done45\ so that ngAcenario can continue
6$
7%
28. // test e-ecution.
29. done457
30. ,57
31.
32. ,7
33.
34. // start deleting entries
35. delete9ntry457
36. ,57
In order to undertand what i happening, we hould emphai;e that ng%cenario call are
not immediately e8ecuted, !ut 6ueued *in ng%cenario term, we would !e tal#ing a!out
adding future action/. If we had only one entry in our ta!le, than the following future action
would !e 6ueued$
1. // delete entry 1
2. roLser45.na!igate(o42/entries257
3. element42tale tody25.'uery46unction 4tody@ done5 ) ... ,57
4. element42tale tody a257
5. element42.tn-danger25.clic<457
Cor two entrie, ng%cenario would have to wor# on the following 6ueue$
1. // delete entry 1
2. roLser45.na!igate(o42/entries257
3. element42tale tody25.'uery46unction 4tody@ done5 ) ... ,57
4. element42tale tody a257
5. element42.tn-danger25.clic<457
6.
7. // delete entry 0
8. // indented to represent "recursion depth"
9. roLser45.na!igate(o42/entries257
10. element42tale tody25.'uery46unction 4tody@ done5 ) ... ,57
11. element42tale tody a257
12. element42.tn-danger25.clic<457
18 1nderstanding Angular $e!plates
&n &ngular template i the declarative peci1cation that, along with information from the
model and controller, !ecome the rendered view that a uer ee in the !rower. It i the
tatic D0,, containing +',-, .%%, and angular(peci1c element and angular(peci1c
element attri!ute. 'he &ngular element and attri!ute direct angular to add !ehavior and
tranform the template D0, into the dynamic view D0,.
'hee are the type of &ngular element and element attri!ute you can ue in a template$
Directive Y &n attri!ute or element that augment an e8iting D0, element or
repreent a reua!le D0, component ( a widget.
!ar2up Y 'he dou!le curly !race notation {{ }} to !ind e8preion to element i
!uilt(in angular mar#up.
Cilter Y Cormat your data for diplay to the uer.
Corm control Y -et you validate uer input.
3ote$ In addition to declaring the element a!ove in template, you can alo acce thee
element in )ava%cript code.
'he following code nippet how a imple &ngular template made up of tandard +',-
tag along with &ngulardirective and curly(!race !inding with e8preion$
1. <html ng-app>
2. <!-- Nody tag augmented Lith ng#ontroller directi!e -->
3. <ody ng-controller=".y#ontroller">
7%
71
4. <input ng-model="6oo" !alue="ar">
5. <!-- Nutton tag Lith ng-clic< directi!e@ and
6. string e-pression 2utton(e-t2
7. Lrapped in ")) ,," mar<up -->
8. <utton ng-clic<="changeBoo45">))utton(e-t,,</utton>
9. <script src="angular.js">
10. </ody>
11. </html>
In a imple ingle(page app, the template conit of +',-, .%%, and angular directive
contained in 7ut one +',- 1le *uually index.html/. In a more comple8 app, you can
diplay multiple view within one main page uing DpartialD, which are egment of
template located in eparate +',- 1le. :ou DincludeD the partial in the main page uing
the$route ervice in con7unction with the ngView directive. &n e8ample of thi techni6ue i
hown in the angular tutorial, in tep even and eight.
Related Topics
&ngular Cilter
&ngular Corm
Related API
&BI =eference
2A Wor:ing with /SS in Angular
&ngular et thee .%% clae. It i up to your application to provide ueful tyling.
2A.1 /SS classes used )y angular
ng-invalid, ng-valid
2age$ angular applie thi cla to an input widget element if that element"
input doe not pa validation. *eeinput directive/.
ng-pristine, ng-dirty
2age$ angular input directive applie ng-pristine cla to a new input
widget element which did not have uer interaction. 0nce the uer interact with the
input widget the cla i changed to ng-dirty.
Related Topics
&ngular 'emplate
&ngular Corm
21 "ata *inding in Angular
Data(!inding in &ngular we! app i the automatic yncroni;ation of data !etween the
model and view component. 'he way that &ngular implement data(!inding let you treat
the model a the ingle(ource(of(truth in your application. 'he view i a pro7ection of the
model at all time. When the model change, the view re>ect the change, and vice vera.
21.1 "ata *inding in /lassical $e!plate Syste!s
,ot templating ytem !ind data in only one direction$ they merge template and model
component together into a view, a illutrated in the diagram. &fter the merge occur,
change to the model or related ection of the view are 30' automatically re>ected in the
view. Wore, any change that the uer ma#e to the view are not re>ected in the model.
71
72
'hi mean that the developer ha to write code that contantly
ync the view with the model and the model with the view.
21.2 "ata *inding in Angular $e!plates
'he way &ngular template wor# i different, a illutrated in the
diagram. 'hey are different !ecaue 1rt the template *which i
the uncompiled +',- along with any additional mar#up or
directive/ i compiled on the !rower, and econd, the
compilation tep produce a live view. We ay live !ecaue any
change to the view are immediately re>ected in the model, and
any change in the model are propagated to the view. 'hi
ma#e the model alway the ingle(ource(of(truth for the
application tate, greatly implifying the programming model for
the developer. :ou can thin# of the view a imply an intant
pro7ection of your model.
5ecaue the view i 7ut a pro7ection of the model, the controller
i completely eparated from the view and unaware of it. 'hi
ma#e teting a nap !ecaue it i eay to tet your controller in
iolation without the view and the related D0,<!rower dependency.
Related Topics
&ngular %cope
&ngular 'emplate
22 1nderstanding Angular 6ilters
&ngular 1lter format data for diplay to the uer.
Cor e8ample, you might have a data o!7ect that need to !e formatted according to the
locale !efore diplaying it to the uer. :ou can pa e8preion through a chain of 1lter
li#e thi$
name | uppercase
'he e8preion evaluator imply pae the value of name to uppercase filter.
Related Topics
2ing &ngular Cilter
.reating &ngular Cilter
23 /reating Angular 6ilters
Writing your own 1lter i very eay$ 7ut regiter a new 1lter *in7ecta!le/ factory function with
your module. 'hi factory function hould return a new 1lter function which ta#e the input
value a the 1rt argument. &ny 1lter argument are paed in a additional argument to
the 1lter function.
'he following ample 1lter revere a te8t tring. In addition, it conditionally ma#e the te8t
upper(cae and aign color.
Source
9dit
inde8.html
cript.7
9nd to end tet
1. <!doctype html>
72
73
2. <html ng-app=".yUe!erse.odule">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di! ng-controller="#trl">
9. <input ng-model="greeting" type="greeting"><r>
10. /o 6ilter: ))greeting,,<r>
11. Ue!erse: ))greeting+re!erse,,<r>
12. Ue!erse & uppercase: ))greeting+re!erse:true,,<r>
13. </di!>
14. </ody>
15. </html>
Demo
',-Direct
3o 1lter$ hello
=evere$ olleh
=evere O uppercae$ 0--9+
Related Topics
2ndertanding &ngular Cilter
&ngular +',- .ompiler
Related API
+ngular 3ilter +45
2# 1sing Angular 6ilters
Cilter can !e part of any api/ng.$rootScope.Scope evaluation !ut are typically ued to
format e8preion in !inding in your template$
{{ expression | filter }}
Cilter typically tranform the data to a new data type, formatting the data in the proce.
Cilter can alo !e chained, and can ta#e optional argument.
:ou can chain 1lter uing thi ynta8$
{{ expression | filter1 | filter2 }}
:ou can alo pa colon(delimited argument to 1lter, for e8ample, to diplay the num!er
123 with 2 decimal point$
123 | number:2
2e the ame ynta8 for multiple argument$
myArray | orderBy:'timestamp':true
+ere are ome e8ample that how value !efore and after applying different 1lter to an
e8preion in a !inding$
3o 1lter$ {{1234.5678}} QR 1234.5678
3um!er 1lter$ {{1234.5678|number}} QR 1,234.57. 3otice the D,D and rounding
to two igni1cant digit.
Cilter with argument$ {{1234.5678|number:5}} QR 1,234.56780. Cilter can
ta#e optional argument, eparated !y colon in a !inding. Cor e8ample, the Dnum!erD
1lter ta#e a num!er argument that peci1e how many digit to diplay to the right of
the decimal point.
73
74
2' Angular Ser0ices
%ervice are a feature that &ngular !ring to client(ide we! app from the erver ide,
where ervice have !een commonly ued for a long time. %ervice in &ngular app are
u!tituta!le o!7ect that are wired together uing dependency in7ection *DI/.
Related Topics
2ndertanding &ngular %ervice
.reating &ngular %ervice
,anaging %ervice Dependencie
In7ecting %ervice Into .ontroller
'eting &ngular %ervice
Related API
&ngular %ervice &BI
23 1nderstanding Angular Ser0ices
&ngular ervice are ingleton that carry out peci1c ta# common to we! app, uch a
the$http service that provide low level acce to the !rower" XMLHttpRequest o!7ect.
'o ue an &ngular ervice, you identify it a a dependency for the dependent *a controller, or
another ervice/ that depend on the ervice.
&ngular" dependency in7ection
u!ytem ta#e care of the ret. 'he
&ngular in7ector u!ytem i in charge of
ervice intantiation, reolution of
dependencie, and proviion of
dependencie to factory function a
re6ueted.
&ngular in7ect dependencie uing
DcontructorD in7ection *the ervice i
paed in via a factory function/.
5ecaue )ava%cript i a dynamically typed
language, &ngular" dependency in7ection
u!ytem cannot ue tatic type to
identify ervice dependencie. Cor thi reaon a dependent mut e8plicitly de1ne it
dependencie !y uing the $injectproperty. Cor e8ample$
myController.$inject = ['$location'];
'he &ngular we! framewor# provide a et of ervice for common operation. -i#e other
core &ngular varia!le and identi1er, the !uilt(in ervice alway tart with $ *uch
a $http mentioned a!ove/. :ou can alo create your own cutom ervice.
Related Topics
&!out &ngular Dependency In7ection
.reating &ngular %ervice
,anaging %ervice Dependencie
'eting &ngular %ervice
Related API
&ngular %ervice &BI
5njector +45
74
75
24 1sing @location
24.1 What does it do?
'he $location ervice pare the 2=- in the !rower addre !ar *!aed on
the window.location/ and ma#e the 2=- availa!le to your application. .hange to the 2=-
in the addre !ar are re>ected into Alocation ervice and change to Alocation are re>ected
into the !rower addre !ar.
'he Alocation ervice$
98poe the current 2=- in the !rower addre !ar, o you can
Watch and o!erve the 2=-.
.hange the 2=-.
%ynchroni;e the 2=- with the !rower when the uer
.hange the addre !ar.
.lic# the !ac# or forward !utton *or clic# a +itory lin#/.
.lic# on a lin#.
=epreent the 2=- o!7ect a a et of method *protocol, hot, port, path, earch,
hah/.
24.1.1 /o!paring @location to window.location
window.location (location service
purpoe allow read<write acce to the
current !rower location
ame
&BI e8poe DrawD o!7ect with
propertie that can !e directly
modi1ed
e8poe 7Zuery(tyle
getter and etter
integration with angular
application life(cycle
none #now a!out all internal
life(cycle phae,
integrate with Awatch, ...
eamle integration with
+',-5 &BI
no ye *with a fall!ac# for
legacy !rower/
aware of docroot<conte8t
from which the application
i loaded
no ( window.location.path
return D<docroot<actual<pathD
ye ( Alocation.path*/
return D<actual<pathD
24.1.2 When should I use @location?
&ny time your application need to react to a change in the current 2=- or if you want to
change the current 2=- in the !rower.
24.1.3 What does it not do?
It doe not caue a full page reload when the !rower 2=- i changed. 'o reload the page
after changing the 2=-, ue the lower(level &BI, $window.location.href.
75
76
24.2 Ceneral o0er0iew o& the A(I
'he $location ervice can !ehave differently, depending on the con1guration that wa
provided to it when it wa intantiated. 'he default con1guration i uita!le for many
application, for other cutomi;ing the con1guration can ena!le new feature.
0nce the $location ervice i intantiated, you can interact with it via 7Zuery(tyle getter
and etter method that allow you to get or change the current 2=- in the !rower.
24.2.1 @location ser0ice con&iguration
'o con1gure the $location ervice, retrieve the $locationProvider and et the parameter a
follow$
html5,ode*mode/$ W!ooleanX
true ( ee +',-5 mode
false ( ee +ah!ang mode
default$ false
hahBre18*pre18/$ WtringX
pre18 ued for +ah!ang 2=- *ued in +ah!ang mode or in legacy !rower in +tml5
mode/
default$ ""
1.3#.1 )xa!ple con*guration
1. KlocationXro!ider.htmlF.ode4true5.hashXre6i-42!257
24.2.2 Cetter and setter !ethods
$location ervice provide getter method for read(only part of the 2=- *a!2rl,
protocol, hot, port/ and getter < etter method for url, path, earch, hah$
1. // get the current path
2. Klocation.path457
3.
4. // change the path
5. Klocation.path42/neLValue25
&ll of the etter method return the ame $location o!7ect to allow chaining. Cor e8ample,
to change multiple egment in one go, chain etter li#e thi$
1. Klocation.path42/neLValue25.search4)<ey: !alue,57
'here i a pecial replace method which can !e ued to tell the Alocation ervice that the
ne8t time the Alocation ervice i ynced with the !rower, the lat hitory record hould !e
replaced intead of creating a new one. 'hi i ueful when you want to implement
redirection, which would otherwie !rea# the !ac# !utton *navigating !ac# would retrigger
the redirection/. 'o change the current 2=- without creating a new !rower hitory record
you can call$
1. Klocation.path42/some/eLXath257
2. Klocation.replace457
3. // or you can chain these as: Klocation.path42/some/eLXath25.replace457
3ote that the etter don"t update window.location immediately. Intead,
the $location ervice i aware of thescope life(cycle and coalece
multiple $location mutation into one DcommitD to the window.location o!7ect during
the cope $digest phae. %ince multiple change to the Alocation" tate will !e puhed to
the !rower a a ingle change, it" enough to call the replace() method 7ut once to
ma#e the entire DcommitD a replace operation rather than an addition to the !rower hitory.
0nce the !rower i updated, the Alocation ervice reet the >ag et
!yreplace() method and future mutation will create new hitory record,
unle replace() i called again.
76
77
1.34.1.1 Setters and character encoding
:ou can pa pecial character to $location ervice and it will encode them according to
rule peci1ed in =C. 3?LK. When you acce the method$
&ll value that are paed to $location etter
method, path(), search(), hash(), are encoded.
Getter *call to method without parameter/ return decoded value for the
following method path(), search(),hash().
When you call the absUrl() method, the returned value i a full url with it
egment encoded.
When you call the url() method, the returned value i path, earch and hah, in the
form /path?search=a&b=c#hash. 'he egment are encoded a well.
24.3 -ash)ang and -$,.' ,odes
$location ervice ha two con1guration mode which control the format of the 2=- in the
!rower addre !ar$+ah!ang mode *the default/ and the +',-5 mode which i !aed on
uing the +',-5 +itory &BI. &pplication ue the ame &BI in !oth mode and
the $location ervice will wor# with appropriate 2=- egment and !rower &BI to
facilitate the !rower 2=- change and hitory management.
+ashbang !ode +T,-. !ode
con1guration the default W html5,ode$ true X
2=- format hah!ang 2=- in all
!rower
regular 2=- in modern !rower,
hah!ang 2=- in old !rower
Pa hrefQDDR lin#
rewriting
no ye
re6uire erver(ide
con1guration
no ye
77
78
24.3.1 -ash)ang !ode <de&ault !ode=
In thi mode, $location ue +ah!ang 2=- in all !rower.
Example
1. it42should shoL e-ample2@ inject4
2. 6unction4KlocationXro!ider5 )
3. KlocationXro!ider.htmlF.ode46alse57
4. KlocationXro!ider.hashXre6i- = 2!27
5. ,@
6. 6unction4Klocation5 )
7. // open http://host.com/ase/inde-.htmlW!/a
8. Klocation.asQrl45 == 2http://host.com/ase/inde-.htmlW!/a2
9. Klocation.path45 == 2/a2
10.
11. Klocation.path42/6oo25
12. Klocation.asQrl45 == 2http://host.com/ase/inde-.htmlW!/6oo2
13.
14. Klocation.search45 == ),
15. Klocation.search4)a: 22@ c: true,57
16. Klocation.asQrl45 == 2http://host.com/ase/inde-.htmlW!/6oo]a=Oc2
17.
18. Klocation.path42/neL25.search42-=y257
19. Klocation.asQrl45 == 2http://host.com/ase/inde-.htmlW!/neL]-=y2
20. ,
21. 557
25 /rawling your app
'o allow inde8ing of your &)&E application, you have to add pecial meta tag in the head
ection of your document$
1. <meta name="6ragment" content="!" />
'hi will caue crawler !ot to re6uet lin# with _escaped_fragment_ param o that your
erver can recogni;e the crawler and erve a +',- naphot. Cor more information a!out
thi techni6ue, ee ,a#ing &)&E &pplication .rawla!le.
25.1.1 -$,.' !ode
In +',-5 mode, the $location ervice getter and etter interact with the !rower 2=-
addre through the +',-5 hitory &BI, which allow for ue of regular 2=- path and
earch egment, intead of their hah!ang e6uivalent. If the +',-5 +itory &BI i not
upported !y a !rower, the $location ervice will fall !ac# to uing the hah!ang 2=-
automatically. 'hi free you from having to worry a!out whether the !rower diplaying
your app upport the hitory &BI or notG the $location ervice tranparently ue the
!et availa!le option.
0pening a regular 2=- in a legacy !rower (R redirect to a hah!ang 2=-
0pening hah!ang 2=- in a modern !rower (R rewrite to a regular 2=-
Example
1. it42should shoL e-ample2@ inject4
2. 6unction4KlocationXro!ider5 )
3. KlocationXro!ider.htmlF.ode4true57
4. KlocationXro!ider.hashXre6i- = 2!27
5. ,@
6. 6unction4Klocation5 )
7. // in roLser Lith 1(.;F history support:
8. // open http://host.com/W!/a -> reLrite to http://host.com/a
78
7$
9. // 4replacing the http://host.com/W!/a history record5
10. Klocation.path45 == 2/a2
11.
12. Klocation.path42/6oo257
13. Klocation.asQrl45 == 2http://host.com/6oo2
14.
15. Klocation.search45 == ),
16. Klocation.search4)a: 22@ c: true,57
17. Klocation.asQrl45 == 2http://host.com/6oo]a=Oc2
18.
19. Klocation.path42/neL25.search42-=y257
20. Klocation.url45 == 2neL]-=y2
21. Klocation.asQrl45 == 2http://host.com/neL]-=y2
22.
23. // in roLser Lithout htmlF history support:
24. // open http://host.com/neL]-=y -> redirect to http://host.com/W!/neL]-=y
25. // 4again replacing the http://host.com/neL]-=y history item5
26. Klocation.path45 == 2/neL2
27. Klocation.search45 == )-: 2y2,
28.
29. Klocation.path42/6oo/ar257
30. Klocation.path45 == 2/6oo/ar2
31. Klocation.url45 == 2/6oo/ar]-=y2
32. Klocation.asQrl45 == 2http://host.com/W!/6oo/ar]-=y2
33. ,
34. 557
1.34.1.2 Fallback for legacy browsers
Cor !rower that upport the +',-5 hitory &BI, $location ue the +',-5 hitory &BI
to write path and earch. If the hitory &BI i not upported !y a
!rower, $location upplie a +a!ang 2=-. 'hi free you from having to worry a!out
whether the !rower viewing your app upport the hitory &BI or notG
the $location ervice ma#e thi tranparent to you.
1.34.1.3 Htl link rewriting
When you ue +',-5 hitory &BI mode, you will need different lin# in different !rower,
!ut all you have to do i pecify regular 2=- lin#, uch a$ <a href="/some?
foo=bar">link</a>
When a uer clic# on thi lin#,
In a legacy !rower, the 2=- change to /index.html#!/some?foo=bar
In a modern !rower, the 2=- change to /some?foo=bar
In cae li#e the following, lin# are not rewrittenG intead, the !rower will perform a full
page reload to the original lin#.
-in# that contain target element
98ample$ <a href="/ext/link?a=b" target="_self">link</a>
&!olute lin# that go to a different domain
98ample$ <a href="http://angularjs.org/">link</a>
-in# tarting with "<" that lead to a different !ae path when !ae i de1ned
98ample$ <a href="/not-my-base/link">link</a>
1.34.1.4 Ser!er side
2ing thi mode re6uire 2=- rewriting on erver ide, !aically you have to rewrite all your
lin# to entry point of your application *e.g. inde8.html/
7$
8%
1.34.1." #rawling your a$$
If you want your &)&E application to !e inde8ed !y we! crawler, you will need to add the
following meta tag to the +9&D ection of your document$
1. <meta name="6ragment" content="!" />
'hi tatement caue a crawler to re6uet lin# with an
empty _escaped_fragment_ parameter o that your erver can recogni;e the crawler and
erve it +',- naphot. Cor more information a!out thi techni6ue, ee ,a#ing &)&E
&pplication .rawla!le.
1.34.1.6 %elati!e links
5e ure to chec# all relative lin#, image, cript etc. :ou mut either pecify the url !ae in
the head of your main html 1le *<base href="/my-base">/ or you mut ue a!olute url
*tarting with // everywhere !ecaue relative url will !e reolved to a!olute url uing the
initial a!olute url of the document, which i often different from the root of the application.
=unning &ngular app with the +itory &BI ena!led from document root i trongly
encouraged a it ta#e care of all relative lin# iue.
1.34.1.& Sending links aong different browsers
5ecaue of rewriting capa!ility in +',-5 mode, your uer will !e a!le to open regular url
lin# in legacy !rower and hah!ang lin# in modern !rower$
,odern !rower will rewrite hah!ang 2=- to regular 2=-.
0lder !rower will redirect regular 2=- to hah!ang 2=-.
Example
+ere you can ee two $location intance, !oth in +tml5 mode, !ut on different
!rower, o that you can ee the difference. 'hee $location ervice are connected to
a fa#e !rower. 9ach input repreent addre !ar of the !rower.
3ote that when you type hah!ang url into 1rt !rower *or vice vera/ it doen"t rewrite <
redirect to regular < hah!ang url, a thi converion happen only during paring the initial
2=- Q on page reload.
In thi e8ample we ue <base href="/base/index.html" />
Source
9dit
inde8.html
cript.7
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. </head>
7. <ody>
8. <di! ng-non-indale class="htmlF-hashang-e-ample">
9. <di! id="htmlF-mode" ng-controller="1tmlF#ntl">
10. <hE>NroLser Lith 1istory JX"</hE>
11. <di! ng-address-ar roLser="htmlF"></di!><r><r>
12. Klocation.protocol45 = ))Klocation.protocol45,,<r>
13. Klocation.host45 = ))Klocation.host45,,<r>
14. Klocation.port45 = ))Klocation.port45,,<r>
15. Klocation.path45 = ))Klocation.path45,,<r>
16. Klocation.search45 = ))Klocation.search45,,<r>
17. Klocation.hash45 = ))Klocation.hash45,,<r>
8%
81
18. <a hre6="http://LLL.host.com/ase/6irst]a=">/ase/6irst]a=</a> +
19. <a hre6="http://LLL.host.com/ase/sec/ond]6lagWhash">sec/ond]6lagWhash</a> +
20. <a hre6="/other-ase/another]search">e-ternal</a>
21. </di!>
22.
23. <di! id="hashang-mode" ng-controller="1ashang#ntl">
24. <hE>NroLser Lithout 1istory JX"</hE>
25. <di! ng-address-ar roLser="hashang"></di!><r><r>
26. Klocation.protocol45 = ))Klocation.protocol45,,<r>
27. Klocation.host45 = ))Klocation.host45,,<r>
28. Klocation.port45 = ))Klocation.port45,,<r>
29. Klocation.path45 = ))Klocation.path45,,<r>
30. Klocation.search45 = ))Klocation.search45,,<r>
31. Klocation.hash45 = ))Klocation.hash45,,<r>
32. <a hre6="http://LLL.host.com/ase/6irst]a=">/ase/6irst]a=</a> +
33. <a hre6="http://LLL.host.com/ase/sec/ond]6lagWhash">sec/ond]6lagWhash</a> +
34. <a hre6="/other-ase/another]search">e-ternal</a>
35. </di!>
36. </di!>
37. </ody>
38. </html>
Demo
1.34.1.).1 Bro&s#r &"th H"stor2 A8I
Alocation.protocol*/ Q WWAlocation.protocol*/XX
Alocation.hot*/ Q WWAlocation.hot*/XX
Alocation.port*/ Q WWAlocation.port*/XX
Alocation.path*/ Q WWAlocation.path*/XX
Alocation.earch*/ Q WWAlocation.earch*/XX
Alocation.hah*/ Q WWAlocation.hah*/XX
<!ae<1rtTaQ! [ ec<ondT>ag\hah [ e8ternal
1.34.1.).2 Bro&s#r &"thout H"stor2 A8I
Alocation.protocol*/ Q WWAlocation.protocol*/XX
Alocation.hot*/ Q WWAlocation.hot*/XX
Alocation.port*/ Q WWAlocation.port*/XX
Alocation.path*/ Q WWAlocation.path*/XX
Alocation.earch*/ Q WWAlocation.earch*/XX
Alocation.hah*/ Q WWAlocation.hah*/XX
<!ae<1rtTaQ! [ ec<ondT>ag\hah [ e8ternal
25.2 /a0eats
25.2.1 (age reload na0igation
'he $location ervice allow you to change only the 2=-G it doe not allow you to reload
the page. When you need to change the 2=- and reload the page or navigate to a different
page, pleae ue a lower level &BI,$window.location.href.
81
82
25.2.2 1sing @location outside o& the scope li&e-cycle
$location #now a!out &ngular" scope life(cycle. When a 2=- change in the !rower it
update the $locationand call $apply o that all Awatcher < Ao!erver are noti1ed.
When you change the $location inide the $digestphae everything i
o#G $location will propagate thi change into !rower and will notify all the Awatcher <
Ao!erver. When you want to change the $location from outide &ngular *for e8ample,
through a D0, 9vent or during teting/ ( you mut call $apply to propagate the change.
25.2.3 @location.path<= and F or / pre&ies
& path hould alway !egin with forward lah *//G the $location.path() etter will add
the forward lah if it i miing.
3ote that the ! pre18 in the hah!ang mode i not part of $location.path()G it i
actually hahBre18.
25.3 $esting with the @location ser0ice
When uing $location ervice during teting, you are outide of the angular" scope life(
cycle. 'hi mean it" your reponi!ility to call scope.$apply().
1. descrie42ser!iceQnder(est2@ 6unction45 )
2. e6ore9ach4module46unction4Kpro!ide5 )
3. Kpro!ide.6actory42ser!iceQnder(est2@ 6unction4Klocation5)
4. // Lhate!er it does...
5. ,57
6. ,57
7.
8. it42should...2@ inject46unction4Klocation@ KrootAcope@ ser!iceQnder(est5 )
9. Klocation.path42/neL/path257
10. KrootAcope.Kapply457
11.
12. // test Lhate!er the ser!ice should do...
13.
14. ,557
15. ,57
25.# ,igrating &ro! earlier Angular?S releases
In earlier releae of &ngular, $location ued hashPath or hashSearch to proce path
and earch method. With thi releae, the $location ervice procee path and earch
method and then ue the information it o!tain to compoe hah!ang 2=- *uch
a http://server.com/#!/path?search=a/, when neceary.
25.#.1 /hanges to your code
/avigation inside the app 0hange to
Alocation.href Q value
Alocation.hah Q value
Alocation.update*value/
Alocation.update+ah*value/
Alocation.path*path/.earch*earch/
Alocation.hahBath Q path Alocation.path*path/
Alocation.hah%earch Q earch Alocation.earch*earch/
82
83
/avigation inside the app 0hange to
3avigation outide the app 2e lower level &BI
Alocation.href Q value
Alocation.update*value/
Awindow.location.href Q value
AlocationMprotocol [ hot [ port [ path [
earchN
Awindow.locationMprotocol [ hot [ port [ path [
earchN
=ead acce .hange to
Alocation.hahBath Alocation.path*/
Alocation.hah%earch Alocation.earch*/
Alocation.href
Alocation.protocol
Alocation.hot
Alocation.port
Alocation.hah
Alocation.a!2rl*/
Alocation.protocol*/
Alocation.hot*/
Alocation.port*/
Alocation.path*/ O Alocation.earch*/
Alocation.path
Alocation.earch
Awindow.location.path
Awindow.location.earch
25.#.2 $wo-way )inding to @location
'he &ngular" compiler currently doe not upport two(way !inding for method *ee iue/.
If you hould re6uire two(way !inding to the Alocation o!7ect *uing ngModel directive on an
input 1eld/, you will need to pecify an e8tra model property *e.g. locationPath/ with two
watcher which puh Alocation update in !oth direction. Cor e8ample$
1.34.1.' Source
9dit
inde8.html
cript.7
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. </head>
7. <ody>
8. <di! ng-controller=";ocation#ontroller">
9. <input type="te-t" ng-model="locationXath" />
10. </di!>
11. </ody>
12. </html>
1.34.1.( )eo
83
84
28 $,."irect /reating ser0ices
While &ngular offer everal ueful ervice, for any nontrivial application you"ll 1nd it ueful
to write your own cutom ervice. 'o do thi you !egin !y regitering a ervice factory
function with a module either via the Module#factory api or directly via the $provide api inide
of module con1g function.
&ll &ngular ervice participate in dependency in7ection *DI/ !y regitering themelve with
&ngular" DI ytem *in7ector/ under a name *id/ a well a !y declaring dependencie which
need to !e provided for the factory function of the regitered ervice. 'he a!ility to wap
dependencie for moc#<tu!<dummie in tet allow for ervice to !e highly teta!le.
28.1 Registering Ser0ices
'o regiter a ervice, you mut have a module that thi ervice will !e part of. &fterward,
you can regiter the ervice with the module either via the Module api or !y uing
the $provide ervice in the module con1guration function.'he following peudo(code how
!oth approache$
2ing the angular.,odule api$
1. !ar my.odule = angular.module42my.odule2@ ?C57
2. my.odule.6actory42ser!ice"d2@ 6unction45 )
3. !ar shiny/eLAer!ice"nstance7
4. //6actory 6unction ody that constructs shiny/eLAer!ice"nstance
5. return shiny/eLAer!ice"nstance7
6. ,57
2ing the Aprovide ervice$
1. angular.module42my.odule2@ ?C@ 6unction4Kpro!ide5 )
2. Kpro!ide.6actory42ser!ice"d2@ 6unction45 )
3. !ar shiny/eLAer!ice"nstance7
4. //6actory 6unction ody that constructs shiny/eLAer!ice"nstance
5. return shiny/eLAer!ice"nstance7
6. ,57
7. ,57
3ote that you are not regitering a ervice intance, !ut rather a factory function that will
create thi intance when called.
28.2 "ependencies
%ervice can not only !e depended upon, !ut can alo have their own dependencie. 'hee
can !e peci1ed a argument of the factory function. =ead more a!out dependency
in7ection *DI/ in &ngular and the ue of array notation and the Ain7ect property to ma#e DI
annotation mini1cation(proof.
Collowing i an e8ample of a very imple ervice. 'hi ervice depend on
the $window ervice *which i paed a a parameter to the factory function/ and i 7ut a
function. 'he ervice imply tore all noti1cationG after the third one, the ervice diplay
all of the noti1cation !y window alert.
1. angular.module42my.odule2@ ?C@ 6unction4Kpro!ide5 )
2. Kpro!ide.6actory42noti6y2@ ?2KLindoL2@ 6unction4Lin5 )
3. !ar msgs = ?C7
4. return 6unction4msg5 )
5. msgs.push4msg57
6. i6 4msgs.length == D5 )
7. Lin.alert4msgs.join4"%n"557
8. msgs = ?C7
9. ,
84
85
10. ,7
11. ,C57
12. ,57
28.3 Instantiating Angular Ser0ices
&ll ervice in &ngular are intantiated la;ily. 'hi mean that a ervice will !e created only
when it i needed for intantiation of a ervice or an application component that depend on
it. In other word, &ngular won"t intantiate ervice unle they are re6ueted directly or
indirectly !y the application.
28.# Ser0ices as singletons
-atly, it i important to reali;e that all &ngular ervice are application ingleton. 'hi
mean that there i only one intance of a given ervice per in7ector. %ince &ngular i lethally
allergic to glo!al tate, it i poi!le to create multiple in7ector, each with it own intance
of a given ervice, !ut that i rarely needed, e8cept in tet where thi property i crucially
important.
Related Topics
2ndertanding &ngular %ervice
,anaging %ervice Dependencie
In7ecting %ervice Into .ontroller
'eting &ngular %ervice
Related API
&ngular %ervice &BI
3A In7ecting Ser0ices into /ontroller
2ing ervice a dependencie for controller i very imilar to uing ervice a
dependencie for another ervice.
%ince )ava%cript i a dynamic language, DI can"t 1gure out which ervice to in7ect !y tatic
type *li#e in tatic typed language/. 'herefore, you can pecify the ervice name !y uing
the $inject property, which i an array containing tring with name of ervice to !e
in7ected. 'he name mut match the correponding ervice ID regitered with angular. 'he
order of the ervice ID matter$ the order of the ervice in the array will !e ued when
calling the factory function with in7ected parameter. 'he name of parameter in factory
function don"t matter, !ut !y convention they match the ervice ID, which ha added
!ene1t dicued !elow.
1. 6unction my#ontroller4Kloc@ Klog5 )
2. this.6irst.ethod = 6unction45 )
3. // use Klocation ser!ice
4. Kloc.set1ash457
5. ,7
6. this.second.ethod = 6unction45 )
7. // use Klog ser!ice
8. Klog.in6o42...257
9. ,7
10. ,
11. // Lhich ser!ices to inject ]
12. my#ontroller.Kinject = ?2Klocation2@ 2Klog2C7
Source
9dit
85
86
inde8.html
cript.7
9nd to end tet
1. <!doctype html>
2. <html ng-app=".yAer!ice.odule">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di! ng-controller="my#ontroller">
9. <p>;et2s try this simple noti6y ser!ice@ injected into the controller...</p>
10. <input ng-init="message=2test2" ng-model="message" >
11. <utton ng-clic<="call/oti6y4message57">/=("BM</utton>
12. </di!>
13. </ody>
14. </html>
Demo
-et" try thi imple notify ervice, in7ected into the controller...
',-Direct 30'IC:
3A.1 I!plicit "ependency In7ection
& new feature of &ngular DI allow it to determine the dependency from the name of the
parameter. -et" rewrite the a!ove e8ample to how the ue of thi implicit dependency
in7ection of $window, $scope, and our notify ervice$
Source
9dit
inde8.html
cript.7
1. <!doctype html>
2. <html ng-app=".yAer!ice.odule8"">
3. <head>
4. <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
5. <script src="script.js"></script>
6. </head>
7. <ody>
8. <di! ng-controller="my#ontroller">
9. <p>;et2s try the noti6y ser!ice@ that is implicitly injected into the
controller...</p>
10. <input ng-init="message=2test2" ng-model="message">
11. <utton ng-clic<="call/oti6y4message57">/=("BM</utton>
12. </di!>
13. </ody>
14. </html>
Demo
-et" try the notify ervice, that i implicitly in7ected into the controller...
',-Direct 30'IC:
+owever, if you plan to minify your code, your varia!le name will get renamed in which
cae you will till need to e8plicitly pecify dependencie with the $inject property.
Related Topics
86
87
2ndertanding &ngular %ervice .reating &ngular %ervice ,anaging %ervice
Dependencie 'eting &ngular %ervice
Related API
&ngular %ervice &BI
31 ,anaging Ser0ice "ependancies
&ngular allow ervice to declare other ervice a dependencie needed for contruction
of their intance.
'o declare dependencie, you pecify them in the factory function ignature and annotate
the function with the in7ect annotation either uing !y etting the $inject property, a an
array of tring identi1er or uing the array notation. 0ptionally the $inject property
declaration can !e dropped *ee DInferring $injectD !ut note that that i currently an
e8perimental feature/.
2ing the array notation$
1. 6unction my.odule#6gBn4Kpro!ide5 )
2. Kpro!ide.6actory42myAer!ice2@ ?2dep12@ 2dep02@ 6unction4dep1@ dep05 ),C57
3. ,
2ing the Ain7ect property$
1. 6unction my.odule#6gBn4Kpro!ide5 )
2. !ar myAer!iceBactory = 6unction4dep1@ dep05 ),7
3. myAer!iceBactory.Kinject = ?2dep12@ 2dep02C7
4. Kpro!ide.6actory42myAer!ice2@ myAer!iceBactory57
5. ,
2ing DI inference *incompati!le with mini1er/$
1. 6unction my.odule#6gBn4Kpro!ide5 )
2. Kpro!ide.6actory42myAer!ice2@ 6unction4dep1@ dep05 ),57
3. ,
+ere i an e8ample of two ervice, one of which depend on the other and !oth of which
depend on other ervice that are provided !y the &ngular framewor#$
1. /**
2. * atch;og ser!ice alloLs 6or messages to e 'ueued in memory and 6lushed
3. * to the console.log e!ery F0 seconds.
4. *
5. * Rparam )*, message .essage to e logged.
6. */
7. 6unction atch;og.odule4Kpro!ide5)
8. Kpro!ide.6actory42atch;og2@ ?2Ktimeout2@ 2Klog2@ 6unction4Ktimeout@ Klog5 )
9. !ar message$ueue = ?C7
10.
11. 6unction log45 )
12. i6 4message$ueue.length5 )
13. Klog42atch;og messages: 2@ message$ueue57
14. message$ueue = ?C7
15. ,
16. Ktimeout4log@ F000057
17. ,
18.
19. // start periodic chec<ing
20. log457
21.
22. return 6unction4message5 )
23. message$ueue.push4message57
24. ,
87
88
25. ,C57
26.
27. /**
28. * route(emplate.onitor monitors each Kroute change and logs the current
29. * template !ia the atch;og ser!ice.
30. */
31. Kpro!ide.6actory42route(emplate.onitor2@
32. ?2Kroute2@ 2atch;og2@ 2KrootAcope2@
33. 6unction4Kroute@ atch;og@ KrootAcope5 )
34. KrootAcope.Kon42Kroute#hangeAuccess2@ 6unction45 )
35. atch;og4Kroute.current ] Kroute.current.template : null57
36. ,57
37. ,C57
38. ,
39.
40. // get the main ser!ice to <ic< o6 the application
41. angular.injector4?atch;og.oduleC5.get42route(emplate.onitor257
'hing to notice in thi e8ample$
'he batchLog ervice depend on the !uilt(in 'ti(eout and 'log ervice, and allow
meage to !e logged into the console.log in !atche.
'he routeTemplateMonitor ervice depend on the !uilt(in 'route ervice a well
a our cutom batchLogervice.
5oth of our ervice ue the factory function ignature and array notation for in7ect
annotation to declare their dependencie. It i important that the order of the tring
identi1er in the array i the ame a the order of argument name in the ignature of the
factory function. 2nle the dependencie are inferred from the function ignature, it i
thi array with ID and their order that the in7ector ue to determine which ervice and
in which order to in7ect.
Related Topics
2ndertanding &ngular %ervice
.reating &ngular %ervice
In7ecting %ervice Into .ontroller
'eting &ngular %ervice
Related API
&ngular %ervice &BI
+ngular 5njector +45
32 $esting Angular Ser0ices
'he following i a unit tet for the "notify" ervice in the "Dependencie" e8ample in .reating
&ngular %ervice. 'he unit tet e8ample ue )amine py *moc#/ intead of a real !rower
alert.
1. !ar moc<@ noti6y7
2.
3. e6ore9ach46unction45 )
4. moc< = )alert: jasmine.createApy45,7
5.
6. module46unction4Kpro!ide5 )
7. Kpro!ide.!alue42KLindoL2@ moc<57
8. ,57
9.
10. inject46unction4Kinjector5 )
88
8$
11. noti6y = Kinjector.get42noti6y257
12. ,57
13. ,57
14.
15. it42should not alert 6irst tLo noti6ications2@ 6unction45 )
16. noti6y42one257
17. noti6y42tLo257
18.
19. e-pect4moc<.alert5.not.to1a!eNeen#alled457
20. ,57
21.
22. it42should alert all a6ter third noti6ication2@ 6unction45 )
23. noti6y42one257
24. noti6y42tLo257
25. noti6y42three257
26.
27. e-pect4moc<.alert5.to1a!eNeen#alled3ith4"one%ntLo%nthree"57
28. ,57
29.
30. it42should clear messages a6ter alert2@ 6unction45 )
31. noti6y42one257
32. noti6y42tLo257
33. noti6y42third257
34. noti6y42more257
35. noti6y42tLo257
36. noti6y42third257
37.
38. e-pect4moc<.alert.call#ount5.to9'ual4057
39. e-pect4moc<.alert.mostUecent#all.args5.to9'ual4?"more%ntLo%nthird"C57
40. ,57
Related Topics
2ndertanding &ngular %ervice
.reating &ngular %ervice
,anaging %ervice Dependencie
In7ecting %ervice Into .ontroller
Related API
&ngular %ervice &BI
33 1nit $esting
)ava%cript i a dynamically typed language which come with great power of e8preion,
!ut it alo come with almot no(help from the compiler. Cor thi reaon we feel very
trongly that any code written in )ava%cript need to come with a trong et of tet. We
have !uilt many feature into &ngular which ma#e teting your &ngular application eay.
%o there i no e8cue for not teting.
33.1 It is all a)out 9>$ !iing concerns
2nit teting a the name implie i a!out teting individual unit of code. 2nit tet try to
anwer 6uetion uch a DDid I thin# a!out the logic correctlyTD or DDoe the ort function
order the lit in the right orderTD
In order to anwer uch 6uetion it i very important that we can iolate the unit of code
under tet. 'hat i !ecaue when we are teting the ort function we don"t want to !e
8$
$%
forced into creating related piece uch a the D0, element, or ma#ing any E+= call in
getting the data to ort.
While thi may eem o!viou it uually i very dif1cult to !e a!le to call an individual
function on a typical pro7ect. 'he reaon i that the developer often mi8 concern, and they
end up with a piece of code which doe everything. It read the data from E+=, it ort it
and then it manipulate the D0,.
With &ngular we try to ma#e it eay for you to do the right thing, and o we provide
dependency in7ection for your E+= *which you can moc# out/ and we created a!traction
which allow you to ort your model without having to reort to manipulating the D0,. %o
that in the end, it i eay to write a ort function which ort ome data, o that your tet
can create a data et, apply the function, and aert that the reulting model i in the correct
order. 'he tet doe not have to wait for E+=, or create the right #ind of D0,, or aert that
your function ha mutated the D0, in the right way.
33.1.1 With great power co!es great responsi)ility
&ngular i written with teta!ility in mind, !ut it till re6uire that you do the right thing. We
tried to ma#e the right thing eay, !ut &ngular i not magic, which mean if you don"t follow
thee guideline you may very well end up with an unteta!le application.
33.1.2 "ependency In7ection
'here are everal way in which you can get a hold of a dependency$ 1. :ou could create it
uing the new operator. 2. :ou could loo# for it in a well #nown place, alo #nown a glo!al
ingleton. 3. :ou could a# a regitry *alo #nown a ervice regitry/ for it. *5ut how do you
get a hold of the regitryT ,ot li#ely !y loo#ing it up in a well #nown place. %ee \2/ J. :ou
could e8pect that it !e handed to you.
0ut of the four option in the lit a!ove, only the lat one i teta!le. -et" loo# at why$
33.1.2.1 *sing the new o$erator
While there i nothing wrong with the new operator fundamentally the iue i that calling a
new on a contructor permanently !ind the call ite to the type. Cor e8ample let ay that
we are trying to intantiate an XHR o that we can get ome data from the erver.
1. 6unction .y#lass45 )
2. this.do3or< = 6unction45 )
3. !ar -hr = neL T1U457
4. -hr.open4method@ url@ true57
5. -hr.onreadystatechange = 6unction45 )...,
6. -hr.send457
7. ,
8. ,
'he iue !ecome that in tet, we would very much li#e to intantiate a MockXHR which
would allow u to return fa#e data and imulate networ# failure. 5y calling new XHR() we
are permanently !ound to the actual E+=, and there i no good way to replace it. :e there
i mon#ey patching. 'hat i a !ad idea for many reaon which are outide the cope of thi
document.
'he cla a!ove i hard to tet ince we have to reort to mon#ey patching$
1. !ar oldT1U = T1U7
2. T1U = 6unction .oc<T1U45 ),7
3. !ar my#lass = neL .y#lass457
4. my#lass.do3or<457
5. // assert that .oc<T1U got called Lith the right arguments
6. T1U = oldT1U7 // i6 you 6orget this ad things Lill happen
$%
$1
33.1.2.2 +lobal look-u$,
&nother way to approach the pro!lem i to loo# for the ervice in a well #nown location.
1. 6unction .y#lass45 )
2. this.do3or< = 6unction45 )
3. gloal.-hr4)
4. method:2...2@
5. url:2...2@
6. complete:6unction4response5) ... ,
7. ,5
8. ,
9. ,
While no new intance of the dependency i !eing created, it i fundamentally the ame
a new, in that there i no good way to intercept the call to global.xhr for teting
purpoe, other then through mon#ey patching. 'he !aic iue for teting i that a glo!al
varia!le need to !e mutated in order to replace it with call to a moc# method. Cor further
e8planation why thi i !ad ee$ 5rittle Glo!al %tate ] %ingleton
'he cla a!ove i hard to tet ince we have to change glo!al tate$
1. !ar oldT1U = gloal.-hr7
2. gloal.-hr = 6unction moc<T1U45 ),7
3. !ar my#lass = neL .y#lass457
4. my#lass.do3or<457
5. // assert that moc<T1U got called Lith the right arguments
6. gloal.-hr = oldT1U7 // i6 you 6orget this ad things Lill happen
33.1.2.3 Ser!ice %egistry,
It may eem a that thi can !e olved !y having a regitry for all of the ervice, and then
having the tet replace the ervice a needed.
1. 6unction .y#lass45 )
2. !ar ser!iceUegistry = ]]]]7
3. this.do3or< = 6unction45 )
4. !ar -hr = ser!iceUegistry.get42-hr257
5. -hr4)
6. method:2...2@
7. url:2...2@
8. complete:6unction4response5) ... ,
9. ,5
10. ,
+owever, where doe the ervice=egitry come fromT if it i$ U new(ed up, the the tet ha
no chance to reet the ervice for teting U glo!al loo#(up, then the ervice returned i
glo!al a well *!ut reetting i eaier, ince there i only one glo!al varia!le to !e reet/.
'he cla a!ove i hard to tet ince we have to change glo!al tate$
1. !ar oldAer!ice;ocator = gloal.ser!ice;ocator7
2. gloal.ser!ice;ocator.set42-hr2@ 6unction moc<T1U45 ),57
3. !ar my#lass = neL .y#lass457
4. my#lass.do3or<457
5. // assert that moc<T1U got called Lith the right arguments
6. gloal.ser!ice;ocator = oldAer!ice;ocator7 // i6 you 6orget this ad things Lill
happen
33.1.2.4 Passing in )e$endencies,
-atly the dependency can !e paed in.
1. 6unction .y#lass4-hr5 )
2. this.do3or< = 6unction45 )
$1
$2
3. -hr4)
4. method:2...2@
5. url:2...2@
6. complete:6unction4response5) ... ,
7. ,5
8. ,
'hi i the preferred way ince the code ma#e no aumption a to where the xhr come
from, rather that whoever created the cla wa reponi!le for paing it in. %ince the
creator of the cla hould !e different code than the uer of the cla, it eparate the
reponi!ility of creation from the logic, and that i what dependency(in7ection i in a
nuthell.
'he cla a!ove i very teta!le, ince in the tet we can write$
1. 6unction -hr.oc<4args5 )...,
2. !ar my#lass = neL .y#lass4-hr.oc<57
3. my#lass.do3or<457
4. // assert that -hr.oc< got called Lith the right arguments
3otice that no glo!al varia!le were harmed in the writing of thi tet.
&ngular come with dependency in7ection !uilt in which ma#e the right thing eay to do,
!ut you till need to do it if you wih to ta#e advantage of the teta!ility tory.
33.1.3 /ontrollers
What ma#e each application uni6ue i it logic, which i what we would li#e to tet. If the
logic for your application i mi8ed in with D0, manipulation, it will !e hard to tet a in the
e8ample !elow$
1. 6unction XassLord#trl45 )
2. // get re6erences to 8=. elements
3. !ar msg = K42.e-1 span257
4. !ar input = K42.e-1 input257
5. !ar strength7
6.
7. this.grade = 6unction45 )
8. msg.remo!e#lass4strength57
9. !ar pLd = input.!al457
10. passLord.te-t4pLd57
11. i6 4pLd.length > H5 )
12. strength = 2strong27
13. , else i6 4pLd.length > D5 )
14. strength = 2medium27
15. , else )
16. strength = 2Lea<27
17. ,
18. msg
19. .add#lass4strength5
20. .te-t4strength57
21. ,
22. ,
'he code a!ove i pro!lematic from a teta!ility point of view, ince it re6uire your tet to
have the right #ind of D0, preent when the code e8ecute. 'he tet would loo# li#e thi$
1. !ar input = K42<input type="te-t"/>257
2. !ar span = K42<span>257
3. K42ody25.html42<di! class="e-1">25
4. .6ind42di!25
5. .append4input5
6. .append4span57
7. !ar pc = neL XassLord#trl457
$2
$3
8. input.!al42ac257
9. pc.grade457
10. e-pect4span.te-t455.to9'ual42Lea<257
11. K42ody25.html42257
In angular the controller are trictly eparated from the D0, manipulation logic which
reult in a much eaier teta!ility tory a can !e een in thi e8ample$
1. 6unction XassLord#trl4Kscope5 )
2. Kscope.passLord = 227
3. Kscope.grade = 6unction45 )
4. !ar siSe = Kscope.passLord.length7
5. i6 4siSe > H5 )
6. Kscope.strength = 2strong27
7. , else i6 4siSe > D5 )
8. Kscope.strength = 2medium27
9. , else )
10. Kscope.strength = 2Lea<27
11. ,
12. ,7
13. ,
and the tet i traight forward
1. !ar pc = neL XassLord#trl457
2. pc.passLord42ac257
3. pc.grade457
4. e-pect4pc.strength5.to9'ual42Lea<257
3otice that the tet i not only much horter !ut it i eaier to follow what i going on. We
ay that uch a tet tell a tory, rather then aerting random !it which don"t eem to !e
related.
33.1.# 6ilters
Filters are function which tranform the data into uer reada!le format. 'hey are important
!ecaue they remove the formatting reponi!ility from the application logic, further
implifying the application logic.
1. my.odule.6ilter42length2@ 6unction45 )
2. return 6unction4te-t5)
3. return 422&4te-t++2255.length7
4. ,
5. ,57
6.
7. !ar length = K6ilter42length257
8. e-pect4length4null55.to9'ual4057
9. e-pect4length42ac255.to9'ual4D57
33.1.' "irecti0es
Directive in angular are reponi!le for encapulating comple8 functionality within cutom
+',- tag, attri!ute, clae or comment. 2nit tet are very important for directive
!ecaue the component you create with directive may !e ued throughout your
application and in many different conte8t.
33.1.".1 Si$le H-./ 0leent )irecti!e
-et tart with an angular app with no dependencie.
1. !ar app = angular.module42myJpp2@ ?C57
3ow we can add a directive to our app.
1. app.directi!e42a:reat9ye2@ 6unction 45 )
2. return )
$3
$4
3. restrict: 292@
4. replace: true@
5. template: 2<h1>lidless@ Lreathed in 6lame</h1>2
6. ,7
7. ,57
'hi directive i ued a a tag <a-great-eye></a-great-eye>. It replace the entire tag
with the template<h1>lidless, wreathed in flame</h1>. 3ow we are going to write
a 7amine unit tet to verify thi functionality.
1. descrie42Qnit testing great 'uotes2@ 6unction45 )
2. !ar Kcompile7
3. !ar KrootAcope7
4.
5. // ;oad the myJpp module@ Lhich contains the directi!e
6. e6ore9ach4module42myJpp2557
7.
8. // Atore re6erences to KrootAcope and Kcompile
9. // so they are a!ailale to all tests in this descrie loc<
10. e6ore9ach4inject46unction4PKcompileP@ PKrootAcopeP5)
11. // (he injector unLraps the underscores 4P5 6rom around the parameter names Lhen
matching
12. Kcompile = PKcompileP7
13. KrootAcope = PKrootAcopeP7
14. ,557
15.
16. it42Ueplaces the element Lith the appropriate content2@ 6unction45 )
17. // #ompile a piece o6 1(.; containing the directi!e
18. !ar element = Kcompile4"<a-great-eye></a-great-eye>"54KrootAcope57
19. // #hec< that the compiled element contains the templated content
20. e-pect4element.html455.to#ontain4"lidless@ Lreathed in 6lame"57
21. ,57
22. ,57
We in7ect the Acompile ervice and Aroot%cope !efore each 7amine tet. 'he Acompile
ervice i ued to render the aGreat9ye directive. &fter rendering the directive we enure
that the directive ha replaced the content and Dlidle, wreathed in >ameD i preent.
33.1.3 ,oc:s
oue
33.1.4 Clo)al State Isolation
oue
33.2 (re&erred way o& $esting
uo
33.2.1 ?a0aScript$est"ri0er
ou
33.2.2 ?as!ine
ou
33.2.3 Sa!ple pro7ect
%ee the angular(eed pro7ect for an e8ample.
$4
$5
$5

Potrebbero piacerti anche