You are on page 1of 8

9/17/2015

LearnAngularJSWithThese5PracticalExamples|Tutorialzine

tutorialzine
articles

newsletter

thebook

LearnAngularJSWithThese5Practical
Examples
MartinAngelov

Download

August30th,2013

Tweet

836

Like

Share

713

BynowyouveprobablyheardofAngularJStheexcitingopensourceframework,developedby
Google,thatchangesthewayyouthinkaboutwebapps.Therehasbeenmuchwrittenaboutit,butI
haveyettofindsomethingthatiswrittenfordeveloperswhopreferquickandpracticalexamples.This
changestoday.BelowyouwillfindthebasicbuildingblocksofAngularappsModels,Views,
Controllers,ServicesandFiltersexplainedin5practicalexamplesthatyoucaneditdirectlyinyour
browser.Ifyouprefertoopenthemupinyourfavoritecodeeditor,grabthezipabove.

http://tutorialzine.com/2013/08/learnangularjs5examples/

1/8

9/17/2015

LearnAngularJSWithThese5PracticalExamples|Tutorialzine

WhatisAngularJS?
Onahighlevel,AngularJSisaframeworkthatbindsyourHTML(views)toJavaScriptobjects
(models).Whenyourmodelschange,thepageupdatesautomatically.Theoppositeisalsotruea
model,associatedwithatextfield,isupdatedwhenthecontentofthefieldischanged.Angular
handlesallthegluecode,soyoudonthavetoupdateHTMLmanuallyorlistenforevents,likeyoudo
withjQuery.Asamatteroffact,noneoftheexampleshereevenincludejQuery!
TouseAngularJS,youhavetoincludeitinyourpagebeforetheclosing<body>tag.GooglesCDNis
recommendedforafasterloadtime:

<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>

AngularJSgivesyoualargenumberofdirectivesthatletyouassociateHTMLelementstomodels.
Theyareattributesthatstartwithngandcanbeaddedtoanyelement.Themostimportantattribute
thatyouhavetoincludeinanypage,ifyouwishtouseAngular,is ngapp :

<bodyngapp>

Itshouldbeaddedtoanelementthatenclosestherestofthepage,likethebodyelementoran
outermostdiv.Angularlooksforitwhenthepageloadsandautomaticallyevaluatesalldirectivesit
seesonitschildelements.
Enoughwiththetheory!Nowletsseesomecode.

1.NavigationMenu
Asafirstexample,wewillbuildanavigationmenuthathighlightstheselectedentry.Theexampleuses
onlyAngularsdirectives,andisthesimplestapppossibleusingtheframework.ClicktheEditbutton
toseethesourcecode.Itisreadyforexperimentation!

HTML

1
2
3
4
5
6
7
8
9
10
11

CSS

<!AddingthengappdeclarationtoinitializeAngularJS>
<divid="main"ngapp>
HOME

PROJECTS

SERVICES

CONTACT
<!Thenavigationmenuwillgetthevalueofthe"active"variableasaclass.
The$event.preventDefault()stopsthepagefromjumpingwhenalinkisclicked.
<navclass="{{active}}"ngclick="$event.preventDefault()">

Pleaseclickamenuitem

<!Whenalinkinthemenuisclicked,wesettheactivevariable>
<ahref="#"class="home"ngclick="active='home'">Home</a>
<ahref="#"class="projects"ngclick="active='projects'">Projects</

http://tutorialzine.com/2013/08/learnangularjs5examples/

2/8

9/17/2015

LearnAngularJSWithThese5PracticalExamples|Tutorialzine

12
13
14
15
16
17
18
19
20
21
22

<ahref="#"class="services"ngclick="active='services'">Services</
<ahref="#"class="contact"ngclick="active='contact'">Contact</a>
</nav>
<!ngshowwillshowanelementifthevalueinthequotesistruthful,
whilenghidedoestheopposite.Becausetheactivevariableisnotset
initially,thiswillcausethefirstparagraphtobevisible.>
<pnghide="active">Pleaseclickamenuitem</p>
<pngshow="active">Youchose<b>{{active}}</b></p>
</div>

EDIT
RUN

Inthecodeabove,weareusingAngularsdirectivestosetandreadtheactivevariable.When
itchanges,itcausestheHTMLthatusesittobeupdatedautomatically.InAngularsterminology,this
variableiscalledamodel.Itisavailabletoalldirectivesinthecurrentscope,andcanbeaccessedin
yourcontrollers(moreonthatinthenextexample).
IfyouhaveusedJavaScripttemplatesbefore,youarefamiliarwiththe {{var}} syntax.Whenthe
frameworkseessuchastring,itreplacesitwiththecontentsofthevariable.Thisoperationisrepeated
everytimevarischanged.

2.InlineEditor
Forthesecondexample,wewillcreateasimpleinlineeditorclickingaparagraphwillshowatooltip
withatextfield.Wewilluseacontrollerthatwillinitializethemodelsanddeclaretwomethodsfor
togglingthevisibilityofthetooltip.ControllersareregularJavaScriptfunctionswhichareexecuted
automaticallybyAngular,andwhichareassociatedwithyourpageusingthe ngcontroller directive:

HTML

1
2
3
4
5
6
7
8
9
10
11
12

JS

CSS

<!Whenthiselementisclicked,hidethetooltip>
<divid="main"ngappngcontroller="InlineEditorController"ngclick="hideTooltip()"

<!Thisisthetooltip.Itisshownonlywhentheshowtooltipvariableistruthful
<divclass="tooltip"ngclick="$event.stopPropagation()"ngshow="showtooltip"

Editme.

<!ngmodelbindsthecontentsofthetextfieldwiththe"value"model.
Anychangestothetextfieldwillautomaticallyupdatethevalue,and
allotherbindingsonthepagethatdependonit.>
<inputtype="text"ngmodel="value"/>
</div>

http://tutorialzine.com/2013/08/learnangularjs5examples/

3/8

9/17/2015

LearnAngularJSWithThese5PracticalExamples|Tutorialzine

13
14
15
16
17

<!CallamethoddefinedintheInlineEditorControllerthattoggles
theshowtooltipvariable>
<pngclick="toggleTooltip($event)">{{value}}</p>
</div>

EDIT
RUN

Whenthecontrollerfunctionisexecuted,itgetsthespecial $scope objectasaparameter.Adding


propertiesorfunctionstoitmakesthemavailabletotheview.Usingthe ngmodel bindingonthetext
fieldtellsAngulartoupdatethatvariablewhenthevalueofthefieldchanges(thisinturnrerendersthe
paragraphwiththevalue).

3.OrderForm
Inthisexample,wewillcodeanorderformwithatotalpriceupdatedinrealtime,usinganotheroneof
Angularsusefulfeaturesfilters.Filtersletyoumodifymodelsandcanbechainedtogetherusingthe
pipecharacter | .Intheexamplebelow,Iamusingthecurrencyfilter,toturnanumberintoaproperly
formattedprice,completewithadollarsignandcents.Youcaneasilymakeyourownfilters,asyouwill
seeinexample#4.

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

JS

Services

CSS

<!DeclareanewAngularJSappandassociatethecontroller>
<formngappngcontroller="OrderFormController">
<h1>Services</h1>

WebDevelopment

$300.00

<ul>
<!Loopthroughtheservicesarray,assignaclickhandler,andsetor
removethe"active"cssclassifneeded>
<lingrepeat="serviceinservices"ngclick="toggleActive(service)"
Design
$400.00
<!Noticetheuseofthecurrencyfilter,itwillformattheprice>
{{service.name}}<span>{{service.price|currency}}</span>
</li>
</ul> Integration
$250.00

<divclass="total">
<!Calculatethetotalpriceofallchosenservices.Formatitascurrency.
Total:<span>{{total()|currency}}</span>
Training
$220.00

http://tutorialzine.com/2013/08/learnangularjs5examples/

4/8

LearnAngularJSWithThese5PracticalExamples|Tutorialzine
Training
$220.00

9/17/2015

18
19
20

</div>
</form>

Total:

$300.00

EDIT
RUN

The ngrepeat binding(docs)isanotherusefulfeatureoftheframework.Itletsyouloopthroughan


arrayofitemsandgeneratemarkupforthem.Itisintelligentlyupdatedwhenanitemischangedor
deleted.
Note:Foramorecompleteversion,seethistutorial,whichisbasedonthisone,writtenwith
Backbone.js.

4.InstantSearch
Thisexamplewillallowuserstofilteralistofitemsbytypingintoatextfield.Thisisanotherplace
whereAngularshines,andistheperfectusecaseforwritingacustomfilter.Todothisthough,wefirst
havetoturnourapplicationintoamodule.
ModulesareawayoforganizingJavaScriptapplicationsintoselfcontainedcomponentsthatcanbe
combinedinnewandinterestingways.Angularreliesonthistechniqueforcodeisolationandrequires
thatyourapplicationfollowsitbeforeyoucancreateafilter.Thereareonlytwothingsthatyouneedto
dototurnyourappintoamodule:
1. Usethe angular.module("name",[]) functioncallinyourJS.Thiswillinstantiateandreturnanew
module
2. Passthenameofthemoduleasthevalueofthe ngapp directive.
Creatingafilterthenisassimpleascallingthe filter() methodonthemoduleobjectreturned
by angular.module("name",[]) .

HTML

1
2
3
4

JS

CSS

MakingaSuperSimpleRegistrationSystem

<!InitializeanewAngularJSappandassociateitwithamodulenamed"instantSearch"
WithPHPandMySQL
<divngapp="instantSearch"ngcontroller="InstantSearchController">
<divclass="bar">

Createaslideoutfooterwiththisneatzindex

http://tutorialzine.com/2013/08/learnangularjs5examples/

5/8

9/17/2015

LearnAngularJSWithThese5PracticalExamples|Tutorialzine

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Createaslideoutfooterwiththisneatzindex
<!CreateabindingbetweenthesearchStringmodelandthetextfield>
trick
<inputtype="text"ngmodel="searchString"placeholder="Enteryoursearchterms"
</div>

HowtoMakeaDigitalClockwithjQueryand
<ul>
CSS3
<!Renderalielementforeveryentryintheitemsarray.Notice
thecustomsearchfilter"searchFor".Ittakesthevalueofthe
searchStringmodelasanargument.
>
SmoothDiagonalFadeGallerywithCSS3
<lingrepeat="iinitems|searchFor:searchString">
Transitions
<ahref="{{i.url}}"><imgngsrc="{{i.image}}"/></a>
<p>{{i.title}}</p>
</li>
MiniAJAXFileUploadForm
</ul>
</div>
YourFirstBackbone.jsAppServiceChooser

EDIT
RUN

FiltersfollowtheAngular.jsphilosophyeverypieceofcodethatyouwriteshouldbeselfcontained,
testableandreusable.Youcanusethisfilterinallyourviewsandevencombineitwithothersthrough
chaining.

5.SwitchableGrid
AnotherpopularUIinteractionisswitchingbetweendifferentlayoutmodes(gridorlist)withaclickofa
button.ThisisveryeasytodoinAngular.Inaddition,Iwillintroduceanotherimportantconcept
Services.Theyareobjectsthatcanbeusedbyyourapplicationtocommunicatewithaserver,anAPI,
oranotherdatasource.Inourcase,wewillwriteaservicethatcommunicateswithInstagramsAPI
andreturnsanarraywiththemostpopularphotosatthemoment.
Notethatforthiscodetowork,wewillhavetoincludeoneadditionalAngular.jsfileinthepage:

<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angularresource.min.js"></script>

ThisincludesthengResourcemoduleforeasilyworkingwithAJAXAPIs(themoduleisexposedasthe
$resourcevariableinthecode).Thisfileisautomaticallyincludedintheeditorbelow.

HTML

JS

CSS

http://tutorialzine.com/2013/08/learnangularjs5examples/

6/8

9/17/2015

LearnAngularJSWithThese5PracticalExamples|Tutorialzine

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

<divngapp="switchableGrid"ngcontroller="SwitchableGridController">
<divclass="bar">
<!Thesetwobuttonsswitchthelayoutvariable,
whichcausesthecorrectULtobeshown.>
<aclass="listicon"ngclass="{active:layout=='list'}"ngclick
<aclass="gridicon"ngclass="{active:layout=='grid'}"ngclick
</div>

<!Wehavetwolayouts.Wechoosewhichonetoshowdependingonthe"layout"bind

<ulngshow="layout=='grid'"class="grid">
<!Aviewwithbigphotosandnotext>
<lingrepeat="pinpics">
<ahref="{{p.link}}"target="_blank"><imgngsrc="{{p.images.low_resolution.u
</li>
</ul>

<ulngshow="layout=='list'"class="list">
<!Acompactviewsmallerphotosandtitles>
<lingrepeat="pinpics">
<ahref="{{p.link}}"target="_blank"><imgngsrc="{{p.images.thumbnail.url}}"
<p>{{p.caption.text}}</p>
</li>
</ul>
</div>

EDIT
RUN

Servicesareentirelyselfcontained,whichmakesitpossibletowritedifferentimplementationswithout
affectingtherestofyourcode.Forexample,whiletesting,youmightprefertoreturnahardcodedarray
ofphotoswhichwouldspeedupyourtests.

FurtherReading
Ifyouvereachedthispoint,youhavealreadygraspedthebasicsofdevelopingwithAngular.However,
thereismuchtolearnifyouwanttobeapro.Hereisalistofresourceswhichwillhelpyouinyour
quest:
TheAngularJSHomePage
TheAngularJSGuide
TheOfficialAngularJSTutorial
http://tutorialzine.com/2013/08/learnangularjs5examples/

7/8

9/17/2015

LearnAngularJSWithThese5PracticalExamples|Tutorialzine

Alistoflotsandlotsofmoreresources,videosandtutorials

ANGULARJS

ArticleLicense

JAVASCRIPT

PrivacyPolicy

QUICKLEARN

ContactForm

Advertise

Tutorialzine20092015

http://tutorialzine.com/2013/08/learnangularjs5examples/

8/8

You might also like