You are on page 1of 4

FirstbabystepswithAngular.

js
ThisarticleoutlinessomeofmynotesofawebinaraboutAngular.jsIrecentlyparticipatedat.Theseare
reallyjustbabystepsinthatitcoverstheverybasicsthatmighthelptogetstarted.Sincetheseare
reallymyfirststepswithAngular,Imighthavemisunderstoodsomeofthestuff.Sofeelfreetohelpme
improvethisarticle)
Info:thesourcecodeofsomeoftheexamplesdescribedherecanbefoundontheGitHubrepo.

TheApp
ngapprepresentstheangularapplication.ngapp="myApp"doesnormallyhaveacorresponding
1 angular.module( 'myApp' ,[]);
insomeJavaScriptfile.

DataBinding
{{}}areplaceholdersinHTMLthatarebeinginterpretedbyAngular.Similarasinotherpopular
templatingengineslikeMustache.Itonlyrepresentsaunidirectionalbindingthough.
nginit="text=HelloWorld"allowstointroducevariables.Aftersuchadeclarationyoucan
referencetextanditsvalue.
1 <divnginit= 'text=' HelloWorld '' > 2 <p>Value:{{text}}</p>
Ifwewanttoachievebidirectionalbindingsthenwehavetousengmodel.
1 <inputngmodel= 'text' />

Controllers
Asonewouldassume,controllersareresponsibleforacertainHTMLareatheyareboundto.
1 <bodyngcontroller= 'MyController' > 3 $scope .welcomeMessage= 'Hi,welcometo
theAngulartutorial' ; 4

Filters
Whatisquitehandyontheoutputisthattherearelotsoffiltersavailablethatallowyoutocustomizeit,

likereversingtheoutput:
1 {{welcomeMessage|reverse}}
Pipes(|)areusedtoapplythefiltertosomevalue.Youcanalsocombineseveralonce(justlikeunix
pipes).Therearepredefinedonesontheofficialdocsforpredefinedonesandcustomoneslikeour
reversefilterabove.Implementingitisquitesimple:
01 angular.module( 'myApp' ) 1 <bodyngcontroller= 'MyController' > 3 <buttonng
click= 'sayHello(name)' >Say
Hello</button> 4 </body> 1 angular.module( 'myApp' ) 3 $scope .welcomeMessage= 'Hi,
welcometotheAngulartutorial' ; 4 8 }]);
Inordertonotfillupthecontrollerwithlotsoflogic,youshouldextracttheminreusableservices.
1 angular.module( 'myApp' ) 8 });
Theaboveconstructrepresentsafactorymethodforcreatingtheservicewhichisuniquelyidentifiedby
MyGreetingService.Notethatservicesaresingletons.
Onthecontrolleryoutheninjecttheserviceasfollows:
1 angular.module( 'myApp' ) 3 ...
Variablesprefixedby$arethoseprovidedbyAngular.

Directives
AnotherpowerfulconceptofAngulararedirectives.Theyaimatbringingwebcomponentstoyou,
augmentingtheHTMLwithcustomelements.
1 <helloworld></helloworld>
The<helloworld>isimplementedasfollows:
01 angular.module( 'myApp' ) 03 //hastobeused. 07 //template:
'<p>Hello,world!</p>',//inlinespecification 08 templateUrl:
'helloWorldPartial.html'//loadfromHTMLfile 09 } 10 });
Therestrictpropertyspecifiesthekindofelement,whetheritisaHTMLelement,anattributeorCSS
class.Youcanalsomixmoreofthem.
Therenderedtemplatecanbeeitherspecifiedinlineusingthetemplatepropertyorinaseparatefile,
usingtemplateUrl.ThelatteroneisthesuggestedwayespeciallywhenyouhavemorecomplexHTML
code.
Note:HTMLisntcasesensitiveandassuchalsocustomHTMLtagsshouldnotbewrittenincamel
casebutratherbeseparatedbyadash.

IfyouwanttogetadeepdiveintohowdirectivesworkIabsolutelysuggestyouMiskoHeverysmeetup
video.

StructuringandModules
AnAngularmoduleisdefinedlike
1 angular.module( 'myApp' ,[]);
ThisexamplecodeshowsthedefinitionoftheapplicationinmyApp.js.Whilethereisnorestrictionon
howanAngularapplicationshouldbestructured,amodule/widgetstructureissuggested.Hence,rather
thanorganizingyourappincontrollers,modelsandviewsfolder
Badorganization.Source

..structureitaccordingtothefunctionalitiesormodules,likecalculator,contactsetc.,dependingon
thekindofapplicationyourecreating.
Suggestedorganization.Source:Source

IdidalreadywriteaboutsuchmodularityinJavaScriptMVCapplications.
InmyexamplecodeIhaveanappthatcontainsacalculatormodule.Thefolderstructurelookslike
1 <calculator> 3 ]);
WhatskindaoddisthatalthoughCalculatorControllerisdefinedwithinthecalculatormodule,
youdonthavetoprefixitintheHTMLcode:
1 <divngcontroller= 'CalculatorController' >...</div>
Wait,thismightgettrickyandleadtopotentialnameclasheswhenincludingmultiplemodules.Yep,and
itseemslikecurrentlythisisthesolution:
AsoftodayAngularJSdoesnthandlenamespacecollisionsforservicessoifyouvegot2different
moduleswiththeservicenamedthesamewayandyouincludebothmodulesinyourapp,onlyone
servicewillbeavailable.
ForthemomentthebestoptionistoprefixservicenameswithacustomprefixStackOverflow

WheresjQuery?
CanIuseit?AngularusesaliteversionofjQuery.ThesuggestedapproachistoavoidusingjQuery
directlyandgoasfarasyoucanbyusingdirectives,controllersandlivebinding.However,jQuerycan
obviouslybeincluded.Ifso,youneedtoincludeitbeforetheangular.jsscriptinclude.

1 <head> 3 <scripttype= 'text/javascript'src= 'angular.js' ></script> 4 ... 5 </head>


AngularwilldetectitandusetheincludedjQueryversionratherthanitsownliteversionofit.
GenerallyspeakingtheuseofjQueryshoulddramaticallydecreaseduetolivebindingand
Angulardirectives.

Theresalotmore
Thisarticlereallyjustcoverswhatwascoveredinthewebinar.Theresalotmorethathastobetakena
lookatinordertocreateafullyfeaturedsinglepageapplicationlikerouting,views,unittesting

Questiontothespeaker
HerearetwoquestionsIposedtothespeaker.
YoumentionedaboutusingAngulardirectivessparingly.Why?
Notusedirectivesforeverything,butjustwhereitmakessense,i.e.whenyoucreatealistwitha
simplefilteryoumightbebetterservedbysimplyusingacontroller.
Notduetoperformanceissues
directivesforhavingreusableHTMLelements(webcomponents)
WhatwouldbethemodelofMVCinAngular?
Thereisntamodellikeitmaybeknownfromotherframeworks.ThemodelofAngularissomehowthe
combinationof$scope,thedatabindingandtheservicesifwewish..
AngularusesmoreaMVVMvariationoftheclassicMVC.
JuniorWebDeveloperAmadeusITGroup
SaltLakeCity,UT
Feb,20

You might also like