Nenhuma Descrição

angular.js 1024KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604
  1. /**
  2. * @license AngularJS v1.4.4
  3. * (c) 2010-2015 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, document, undefined) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.4.4/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  57. encodeURIComponent(toDebugString(templateArgs[i]));
  58. }
  59. return new ErrorConstructor(message);
  60. };
  61. }
  62. /* We need to tell jshint what variables are being exported */
  63. /* global angular: true,
  64. msie: true,
  65. jqLite: true,
  66. jQuery: true,
  67. slice: true,
  68. splice: true,
  69. push: true,
  70. toString: true,
  71. ngMinErr: true,
  72. angularModule: true,
  73. uid: true,
  74. REGEX_STRING_REGEXP: true,
  75. VALIDITY_STATE_PROPERTY: true,
  76. lowercase: true,
  77. uppercase: true,
  78. manualLowercase: true,
  79. manualUppercase: true,
  80. nodeName_: true,
  81. isArrayLike: true,
  82. forEach: true,
  83. forEachSorted: true,
  84. reverseParams: true,
  85. nextUid: true,
  86. setHashKey: true,
  87. extend: true,
  88. toInt: true,
  89. inherit: true,
  90. merge: true,
  91. noop: true,
  92. identity: true,
  93. valueFn: true,
  94. isUndefined: true,
  95. isDefined: true,
  96. isObject: true,
  97. isBlankObject: true,
  98. isString: true,
  99. isNumber: true,
  100. isDate: true,
  101. isArray: true,
  102. isFunction: true,
  103. isRegExp: true,
  104. isWindow: true,
  105. isScope: true,
  106. isFile: true,
  107. isFormData: true,
  108. isBlob: true,
  109. isBoolean: true,
  110. isPromiseLike: true,
  111. trim: true,
  112. escapeForRegexp: true,
  113. isElement: true,
  114. makeMap: true,
  115. includes: true,
  116. arrayRemove: true,
  117. copy: true,
  118. shallowCopy: true,
  119. equals: true,
  120. csp: true,
  121. jq: true,
  122. concat: true,
  123. sliceArgs: true,
  124. bind: true,
  125. toJsonReplacer: true,
  126. toJson: true,
  127. fromJson: true,
  128. convertTimezoneToLocal: true,
  129. timezoneToOffset: true,
  130. startingTag: true,
  131. tryDecodeURIComponent: true,
  132. parseKeyValue: true,
  133. toKeyValue: true,
  134. encodeUriSegment: true,
  135. encodeUriQuery: true,
  136. angularInit: true,
  137. bootstrap: true,
  138. getTestability: true,
  139. snake_case: true,
  140. bindJQuery: true,
  141. assertArg: true,
  142. assertArgFn: true,
  143. assertNotHasOwnProperty: true,
  144. getter: true,
  145. getBlockNodes: true,
  146. hasOwnProperty: true,
  147. createMap: true,
  148. NODE_TYPE_ELEMENT: true,
  149. NODE_TYPE_ATTRIBUTE: true,
  150. NODE_TYPE_TEXT: true,
  151. NODE_TYPE_COMMENT: true,
  152. NODE_TYPE_DOCUMENT: true,
  153. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  154. */
  155. ////////////////////////////////////
  156. /**
  157. * @ngdoc module
  158. * @name ng
  159. * @module ng
  160. * @description
  161. *
  162. * # ng (core module)
  163. * The ng module is loaded by default when an AngularJS application is started. The module itself
  164. * contains the essential components for an AngularJS application to function. The table below
  165. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  166. * components available within this core module.
  167. *
  168. * <div doc-module-components="ng"></div>
  169. */
  170. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  171. // The name of a form control's ValidityState property.
  172. // This is used so that it's possible for internal tests to create mock ValidityStates.
  173. var VALIDITY_STATE_PROPERTY = 'validity';
  174. /**
  175. * @ngdoc function
  176. * @name angular.lowercase
  177. * @module ng
  178. * @kind function
  179. *
  180. * @description Converts the specified string to lowercase.
  181. * @param {string} string String to be converted to lowercase.
  182. * @returns {string} Lowercased string.
  183. */
  184. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  185. var hasOwnProperty = Object.prototype.hasOwnProperty;
  186. /**
  187. * @ngdoc function
  188. * @name angular.uppercase
  189. * @module ng
  190. * @kind function
  191. *
  192. * @description Converts the specified string to uppercase.
  193. * @param {string} string String to be converted to uppercase.
  194. * @returns {string} Uppercased string.
  195. */
  196. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  197. var manualLowercase = function(s) {
  198. /* jshint bitwise: false */
  199. return isString(s)
  200. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  201. : s;
  202. };
  203. var manualUppercase = function(s) {
  204. /* jshint bitwise: false */
  205. return isString(s)
  206. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  207. : s;
  208. };
  209. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  210. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  211. // with correct but slower alternatives.
  212. if ('i' !== 'I'.toLowerCase()) {
  213. lowercase = manualLowercase;
  214. uppercase = manualUppercase;
  215. }
  216. var
  217. msie, // holds major version number for IE, or NaN if UA is not IE.
  218. jqLite, // delay binding since jQuery could be loaded after us.
  219. jQuery, // delay binding
  220. slice = [].slice,
  221. splice = [].splice,
  222. push = [].push,
  223. toString = Object.prototype.toString,
  224. getPrototypeOf = Object.getPrototypeOf,
  225. ngMinErr = minErr('ng'),
  226. /** @name angular */
  227. angular = window.angular || (window.angular = {}),
  228. angularModule,
  229. uid = 0;
  230. /**
  231. * documentMode is an IE-only property
  232. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  233. */
  234. msie = document.documentMode;
  235. /**
  236. * @private
  237. * @param {*} obj
  238. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  239. * String ...)
  240. */
  241. function isArrayLike(obj) {
  242. if (obj == null || isWindow(obj)) {
  243. return false;
  244. }
  245. // Support: iOS 8.2 (not reproducible in simulator)
  246. // "length" in obj used to prevent JIT error (gh-11508)
  247. var length = "length" in Object(obj) && obj.length;
  248. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  249. return true;
  250. }
  251. return isString(obj) || isArray(obj) || length === 0 ||
  252. typeof length === 'number' && length > 0 && (length - 1) in obj;
  253. }
  254. /**
  255. * @ngdoc function
  256. * @name angular.forEach
  257. * @module ng
  258. * @kind function
  259. *
  260. * @description
  261. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  262. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  263. * is the value of an object property or an array element, `key` is the object property key or
  264. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  265. *
  266. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  267. * using the `hasOwnProperty` method.
  268. *
  269. * Unlike ES262's
  270. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  271. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  272. * return the value provided.
  273. *
  274. ```js
  275. var values = {name: 'misko', gender: 'male'};
  276. var log = [];
  277. angular.forEach(values, function(value, key) {
  278. this.push(key + ': ' + value);
  279. }, log);
  280. expect(log).toEqual(['name: misko', 'gender: male']);
  281. ```
  282. *
  283. * @param {Object|Array} obj Object to iterate over.
  284. * @param {Function} iterator Iterator function.
  285. * @param {Object=} context Object to become context (`this`) for the iterator function.
  286. * @returns {Object|Array} Reference to `obj`.
  287. */
  288. function forEach(obj, iterator, context) {
  289. var key, length;
  290. if (obj) {
  291. if (isFunction(obj)) {
  292. for (key in obj) {
  293. // Need to check if hasOwnProperty exists,
  294. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  295. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  296. iterator.call(context, obj[key], key, obj);
  297. }
  298. }
  299. } else if (isArray(obj) || isArrayLike(obj)) {
  300. var isPrimitive = typeof obj !== 'object';
  301. for (key = 0, length = obj.length; key < length; key++) {
  302. if (isPrimitive || key in obj) {
  303. iterator.call(context, obj[key], key, obj);
  304. }
  305. }
  306. } else if (obj.forEach && obj.forEach !== forEach) {
  307. obj.forEach(iterator, context, obj);
  308. } else if (isBlankObject(obj)) {
  309. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  310. for (key in obj) {
  311. iterator.call(context, obj[key], key, obj);
  312. }
  313. } else if (typeof obj.hasOwnProperty === 'function') {
  314. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  315. for (key in obj) {
  316. if (obj.hasOwnProperty(key)) {
  317. iterator.call(context, obj[key], key, obj);
  318. }
  319. }
  320. } else {
  321. // Slow path for objects which do not have a method `hasOwnProperty`
  322. for (key in obj) {
  323. if (hasOwnProperty.call(obj, key)) {
  324. iterator.call(context, obj[key], key, obj);
  325. }
  326. }
  327. }
  328. }
  329. return obj;
  330. }
  331. function forEachSorted(obj, iterator, context) {
  332. var keys = Object.keys(obj).sort();
  333. for (var i = 0; i < keys.length; i++) {
  334. iterator.call(context, obj[keys[i]], keys[i]);
  335. }
  336. return keys;
  337. }
  338. /**
  339. * when using forEach the params are value, key, but it is often useful to have key, value.
  340. * @param {function(string, *)} iteratorFn
  341. * @returns {function(*, string)}
  342. */
  343. function reverseParams(iteratorFn) {
  344. return function(value, key) { iteratorFn(key, value); };
  345. }
  346. /**
  347. * A consistent way of creating unique IDs in angular.
  348. *
  349. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  350. * we hit number precision issues in JavaScript.
  351. *
  352. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  353. *
  354. * @returns {number} an unique alpha-numeric string
  355. */
  356. function nextUid() {
  357. return ++uid;
  358. }
  359. /**
  360. * Set or clear the hashkey for an object.
  361. * @param obj object
  362. * @param h the hashkey (!truthy to delete the hashkey)
  363. */
  364. function setHashKey(obj, h) {
  365. if (h) {
  366. obj.$$hashKey = h;
  367. } else {
  368. delete obj.$$hashKey;
  369. }
  370. }
  371. function baseExtend(dst, objs, deep) {
  372. var h = dst.$$hashKey;
  373. for (var i = 0, ii = objs.length; i < ii; ++i) {
  374. var obj = objs[i];
  375. if (!isObject(obj) && !isFunction(obj)) continue;
  376. var keys = Object.keys(obj);
  377. for (var j = 0, jj = keys.length; j < jj; j++) {
  378. var key = keys[j];
  379. var src = obj[key];
  380. if (deep && isObject(src)) {
  381. if (isDate(src)) {
  382. dst[key] = new Date(src.valueOf());
  383. } else if (isRegExp(src)) {
  384. dst[key] = new RegExp(src);
  385. } else {
  386. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  387. baseExtend(dst[key], [src], true);
  388. }
  389. } else {
  390. dst[key] = src;
  391. }
  392. }
  393. }
  394. setHashKey(dst, h);
  395. return dst;
  396. }
  397. /**
  398. * @ngdoc function
  399. * @name angular.extend
  400. * @module ng
  401. * @kind function
  402. *
  403. * @description
  404. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  405. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  406. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  407. *
  408. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  409. * {@link angular.merge} for this.
  410. *
  411. * @param {Object} dst Destination object.
  412. * @param {...Object} src Source object(s).
  413. * @returns {Object} Reference to `dst`.
  414. */
  415. function extend(dst) {
  416. return baseExtend(dst, slice.call(arguments, 1), false);
  417. }
  418. /**
  419. * @ngdoc function
  420. * @name angular.merge
  421. * @module ng
  422. * @kind function
  423. *
  424. * @description
  425. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  426. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  427. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  428. *
  429. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  430. * objects, performing a deep copy.
  431. *
  432. * @param {Object} dst Destination object.
  433. * @param {...Object} src Source object(s).
  434. * @returns {Object} Reference to `dst`.
  435. */
  436. function merge(dst) {
  437. return baseExtend(dst, slice.call(arguments, 1), true);
  438. }
  439. function toInt(str) {
  440. return parseInt(str, 10);
  441. }
  442. function inherit(parent, extra) {
  443. return extend(Object.create(parent), extra);
  444. }
  445. /**
  446. * @ngdoc function
  447. * @name angular.noop
  448. * @module ng
  449. * @kind function
  450. *
  451. * @description
  452. * A function that performs no operations. This function can be useful when writing code in the
  453. * functional style.
  454. ```js
  455. function foo(callback) {
  456. var result = calculateResult();
  457. (callback || angular.noop)(result);
  458. }
  459. ```
  460. */
  461. function noop() {}
  462. noop.$inject = [];
  463. /**
  464. * @ngdoc function
  465. * @name angular.identity
  466. * @module ng
  467. * @kind function
  468. *
  469. * @description
  470. * A function that returns its first argument. This function is useful when writing code in the
  471. * functional style.
  472. *
  473. ```js
  474. function transformer(transformationFn, value) {
  475. return (transformationFn || angular.identity)(value);
  476. };
  477. ```
  478. * @param {*} value to be returned.
  479. * @returns {*} the value passed in.
  480. */
  481. function identity($) {return $;}
  482. identity.$inject = [];
  483. function valueFn(value) {return function() {return value;};}
  484. function hasCustomToString(obj) {
  485. return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
  486. }
  487. /**
  488. * @ngdoc function
  489. * @name angular.isUndefined
  490. * @module ng
  491. * @kind function
  492. *
  493. * @description
  494. * Determines if a reference is undefined.
  495. *
  496. * @param {*} value Reference to check.
  497. * @returns {boolean} True if `value` is undefined.
  498. */
  499. function isUndefined(value) {return typeof value === 'undefined';}
  500. /**
  501. * @ngdoc function
  502. * @name angular.isDefined
  503. * @module ng
  504. * @kind function
  505. *
  506. * @description
  507. * Determines if a reference is defined.
  508. *
  509. * @param {*} value Reference to check.
  510. * @returns {boolean} True if `value` is defined.
  511. */
  512. function isDefined(value) {return typeof value !== 'undefined';}
  513. /**
  514. * @ngdoc function
  515. * @name angular.isObject
  516. * @module ng
  517. * @kind function
  518. *
  519. * @description
  520. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  521. * considered to be objects. Note that JavaScript arrays are objects.
  522. *
  523. * @param {*} value Reference to check.
  524. * @returns {boolean} True if `value` is an `Object` but not `null`.
  525. */
  526. function isObject(value) {
  527. // http://jsperf.com/isobject4
  528. return value !== null && typeof value === 'object';
  529. }
  530. /**
  531. * Determine if a value is an object with a null prototype
  532. *
  533. * @returns {boolean} True if `value` is an `Object` with a null prototype
  534. */
  535. function isBlankObject(value) {
  536. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  537. }
  538. /**
  539. * @ngdoc function
  540. * @name angular.isString
  541. * @module ng
  542. * @kind function
  543. *
  544. * @description
  545. * Determines if a reference is a `String`.
  546. *
  547. * @param {*} value Reference to check.
  548. * @returns {boolean} True if `value` is a `String`.
  549. */
  550. function isString(value) {return typeof value === 'string';}
  551. /**
  552. * @ngdoc function
  553. * @name angular.isNumber
  554. * @module ng
  555. * @kind function
  556. *
  557. * @description
  558. * Determines if a reference is a `Number`.
  559. *
  560. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  561. *
  562. * If you wish to exclude these then you can use the native
  563. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  564. * method.
  565. *
  566. * @param {*} value Reference to check.
  567. * @returns {boolean} True if `value` is a `Number`.
  568. */
  569. function isNumber(value) {return typeof value === 'number';}
  570. /**
  571. * @ngdoc function
  572. * @name angular.isDate
  573. * @module ng
  574. * @kind function
  575. *
  576. * @description
  577. * Determines if a value is a date.
  578. *
  579. * @param {*} value Reference to check.
  580. * @returns {boolean} True if `value` is a `Date`.
  581. */
  582. function isDate(value) {
  583. return toString.call(value) === '[object Date]';
  584. }
  585. /**
  586. * @ngdoc function
  587. * @name angular.isArray
  588. * @module ng
  589. * @kind function
  590. *
  591. * @description
  592. * Determines if a reference is an `Array`.
  593. *
  594. * @param {*} value Reference to check.
  595. * @returns {boolean} True if `value` is an `Array`.
  596. */
  597. var isArray = Array.isArray;
  598. /**
  599. * @ngdoc function
  600. * @name angular.isFunction
  601. * @module ng
  602. * @kind function
  603. *
  604. * @description
  605. * Determines if a reference is a `Function`.
  606. *
  607. * @param {*} value Reference to check.
  608. * @returns {boolean} True if `value` is a `Function`.
  609. */
  610. function isFunction(value) {return typeof value === 'function';}
  611. /**
  612. * Determines if a value is a regular expression object.
  613. *
  614. * @private
  615. * @param {*} value Reference to check.
  616. * @returns {boolean} True if `value` is a `RegExp`.
  617. */
  618. function isRegExp(value) {
  619. return toString.call(value) === '[object RegExp]';
  620. }
  621. /**
  622. * Checks if `obj` is a window object.
  623. *
  624. * @private
  625. * @param {*} obj Object to check
  626. * @returns {boolean} True if `obj` is a window obj.
  627. */
  628. function isWindow(obj) {
  629. return obj && obj.window === obj;
  630. }
  631. function isScope(obj) {
  632. return obj && obj.$evalAsync && obj.$watch;
  633. }
  634. function isFile(obj) {
  635. return toString.call(obj) === '[object File]';
  636. }
  637. function isFormData(obj) {
  638. return toString.call(obj) === '[object FormData]';
  639. }
  640. function isBlob(obj) {
  641. return toString.call(obj) === '[object Blob]';
  642. }
  643. function isBoolean(value) {
  644. return typeof value === 'boolean';
  645. }
  646. function isPromiseLike(obj) {
  647. return obj && isFunction(obj.then);
  648. }
  649. var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
  650. function isTypedArray(value) {
  651. return TYPED_ARRAY_REGEXP.test(toString.call(value));
  652. }
  653. var trim = function(value) {
  654. return isString(value) ? value.trim() : value;
  655. };
  656. // Copied from:
  657. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  658. // Prereq: s is a string.
  659. var escapeForRegexp = function(s) {
  660. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  661. replace(/\x08/g, '\\x08');
  662. };
  663. /**
  664. * @ngdoc function
  665. * @name angular.isElement
  666. * @module ng
  667. * @kind function
  668. *
  669. * @description
  670. * Determines if a reference is a DOM element (or wrapped jQuery element).
  671. *
  672. * @param {*} value Reference to check.
  673. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  674. */
  675. function isElement(node) {
  676. return !!(node &&
  677. (node.nodeName // we are a direct element
  678. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  679. }
  680. /**
  681. * @param str 'key1,key2,...'
  682. * @returns {object} in the form of {key1:true, key2:true, ...}
  683. */
  684. function makeMap(str) {
  685. var obj = {}, items = str.split(","), i;
  686. for (i = 0; i < items.length; i++) {
  687. obj[items[i]] = true;
  688. }
  689. return obj;
  690. }
  691. function nodeName_(element) {
  692. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  693. }
  694. function includes(array, obj) {
  695. return Array.prototype.indexOf.call(array, obj) != -1;
  696. }
  697. function arrayRemove(array, value) {
  698. var index = array.indexOf(value);
  699. if (index >= 0) {
  700. array.splice(index, 1);
  701. }
  702. return index;
  703. }
  704. /**
  705. * @ngdoc function
  706. * @name angular.copy
  707. * @module ng
  708. * @kind function
  709. *
  710. * @description
  711. * Creates a deep copy of `source`, which should be an object or an array.
  712. *
  713. * * If no destination is supplied, a copy of the object or array is created.
  714. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  715. * are deleted and then all elements/properties from the source are copied to it.
  716. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  717. * * If `source` is identical to 'destination' an exception will be thrown.
  718. *
  719. * @param {*} source The source that will be used to make a copy.
  720. * Can be any type, including primitives, `null`, and `undefined`.
  721. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  722. * provided, must be of the same type as `source`.
  723. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  724. *
  725. * @example
  726. <example module="copyExample">
  727. <file name="index.html">
  728. <div ng-controller="ExampleController">
  729. <form novalidate class="simple-form">
  730. Name: <input type="text" ng-model="user.name" /><br />
  731. E-mail: <input type="email" ng-model="user.email" /><br />
  732. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  733. <input type="radio" ng-model="user.gender" value="female" />female<br />
  734. <button ng-click="reset()">RESET</button>
  735. <button ng-click="update(user)">SAVE</button>
  736. </form>
  737. <pre>form = {{user | json}}</pre>
  738. <pre>master = {{master | json}}</pre>
  739. </div>
  740. <script>
  741. angular.module('copyExample', [])
  742. .controller('ExampleController', ['$scope', function($scope) {
  743. $scope.master= {};
  744. $scope.update = function(user) {
  745. // Example with 1 argument
  746. $scope.master= angular.copy(user);
  747. };
  748. $scope.reset = function() {
  749. // Example with 2 arguments
  750. angular.copy($scope.master, $scope.user);
  751. };
  752. $scope.reset();
  753. }]);
  754. </script>
  755. </file>
  756. </example>
  757. */
  758. function copy(source, destination, stackSource, stackDest) {
  759. if (isWindow(source) || isScope(source)) {
  760. throw ngMinErr('cpws',
  761. "Can't copy! Making copies of Window or Scope instances is not supported.");
  762. }
  763. if (isTypedArray(destination)) {
  764. throw ngMinErr('cpta',
  765. "Can't copy! TypedArray destination cannot be mutated.");
  766. }
  767. if (!destination) {
  768. destination = source;
  769. if (isObject(source)) {
  770. var index;
  771. if (stackSource && (index = stackSource.indexOf(source)) !== -1) {
  772. return stackDest[index];
  773. }
  774. // TypedArray, Date and RegExp have specific copy functionality and must be
  775. // pushed onto the stack before returning.
  776. // Array and other objects create the base object and recurse to copy child
  777. // objects. The array/object will be pushed onto the stack when recursed.
  778. if (isArray(source)) {
  779. return copy(source, [], stackSource, stackDest);
  780. } else if (isTypedArray(source)) {
  781. destination = new source.constructor(source);
  782. } else if (isDate(source)) {
  783. destination = new Date(source.getTime());
  784. } else if (isRegExp(source)) {
  785. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  786. destination.lastIndex = source.lastIndex;
  787. } else {
  788. var emptyObject = Object.create(getPrototypeOf(source));
  789. return copy(source, emptyObject, stackSource, stackDest);
  790. }
  791. if (stackDest) {
  792. stackSource.push(source);
  793. stackDest.push(destination);
  794. }
  795. }
  796. } else {
  797. if (source === destination) throw ngMinErr('cpi',
  798. "Can't copy! Source and destination are identical.");
  799. stackSource = stackSource || [];
  800. stackDest = stackDest || [];
  801. if (isObject(source)) {
  802. stackSource.push(source);
  803. stackDest.push(destination);
  804. }
  805. var result, key;
  806. if (isArray(source)) {
  807. destination.length = 0;
  808. for (var i = 0; i < source.length; i++) {
  809. destination.push(copy(source[i], null, stackSource, stackDest));
  810. }
  811. } else {
  812. var h = destination.$$hashKey;
  813. if (isArray(destination)) {
  814. destination.length = 0;
  815. } else {
  816. forEach(destination, function(value, key) {
  817. delete destination[key];
  818. });
  819. }
  820. if (isBlankObject(source)) {
  821. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  822. for (key in source) {
  823. destination[key] = copy(source[key], null, stackSource, stackDest);
  824. }
  825. } else if (source && typeof source.hasOwnProperty === 'function') {
  826. // Slow path, which must rely on hasOwnProperty
  827. for (key in source) {
  828. if (source.hasOwnProperty(key)) {
  829. destination[key] = copy(source[key], null, stackSource, stackDest);
  830. }
  831. }
  832. } else {
  833. // Slowest path --- hasOwnProperty can't be called as a method
  834. for (key in source) {
  835. if (hasOwnProperty.call(source, key)) {
  836. destination[key] = copy(source[key], null, stackSource, stackDest);
  837. }
  838. }
  839. }
  840. setHashKey(destination,h);
  841. }
  842. }
  843. return destination;
  844. }
  845. /**
  846. * Creates a shallow copy of an object, an array or a primitive.
  847. *
  848. * Assumes that there are no proto properties for objects.
  849. */
  850. function shallowCopy(src, dst) {
  851. if (isArray(src)) {
  852. dst = dst || [];
  853. for (var i = 0, ii = src.length; i < ii; i++) {
  854. dst[i] = src[i];
  855. }
  856. } else if (isObject(src)) {
  857. dst = dst || {};
  858. for (var key in src) {
  859. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  860. dst[key] = src[key];
  861. }
  862. }
  863. }
  864. return dst || src;
  865. }
  866. /**
  867. * @ngdoc function
  868. * @name angular.equals
  869. * @module ng
  870. * @kind function
  871. *
  872. * @description
  873. * Determines if two objects or two values are equivalent. Supports value types, regular
  874. * expressions, arrays and objects.
  875. *
  876. * Two objects or values are considered equivalent if at least one of the following is true:
  877. *
  878. * * Both objects or values pass `===` comparison.
  879. * * Both objects or values are of the same type and all of their properties are equal by
  880. * comparing them with `angular.equals`.
  881. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  882. * * Both values represent the same regular expression (In JavaScript,
  883. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  884. * representation matches).
  885. *
  886. * During a property comparison, properties of `function` type and properties with names
  887. * that begin with `$` are ignored.
  888. *
  889. * Scope and DOMWindow objects are being compared only by identify (`===`).
  890. *
  891. * @param {*} o1 Object or value to compare.
  892. * @param {*} o2 Object or value to compare.
  893. * @returns {boolean} True if arguments are equal.
  894. */
  895. function equals(o1, o2) {
  896. if (o1 === o2) return true;
  897. if (o1 === null || o2 === null) return false;
  898. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  899. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  900. if (t1 == t2) {
  901. if (t1 == 'object') {
  902. if (isArray(o1)) {
  903. if (!isArray(o2)) return false;
  904. if ((length = o1.length) == o2.length) {
  905. for (key = 0; key < length; key++) {
  906. if (!equals(o1[key], o2[key])) return false;
  907. }
  908. return true;
  909. }
  910. } else if (isDate(o1)) {
  911. if (!isDate(o2)) return false;
  912. return equals(o1.getTime(), o2.getTime());
  913. } else if (isRegExp(o1)) {
  914. return isRegExp(o2) ? o1.toString() == o2.toString() : false;
  915. } else {
  916. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  917. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  918. keySet = createMap();
  919. for (key in o1) {
  920. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  921. if (!equals(o1[key], o2[key])) return false;
  922. keySet[key] = true;
  923. }
  924. for (key in o2) {
  925. if (!(key in keySet) &&
  926. key.charAt(0) !== '$' &&
  927. o2[key] !== undefined &&
  928. !isFunction(o2[key])) return false;
  929. }
  930. return true;
  931. }
  932. }
  933. }
  934. return false;
  935. }
  936. var csp = function() {
  937. if (!isDefined(csp.rules)) {
  938. var ngCspElement = (document.querySelector('[ng-csp]') ||
  939. document.querySelector('[data-ng-csp]'));
  940. if (ngCspElement) {
  941. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  942. ngCspElement.getAttribute('data-ng-csp');
  943. csp.rules = {
  944. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  945. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  946. };
  947. } else {
  948. csp.rules = {
  949. noUnsafeEval: noUnsafeEval(),
  950. noInlineStyle: false
  951. };
  952. }
  953. }
  954. return csp.rules;
  955. function noUnsafeEval() {
  956. try {
  957. /* jshint -W031, -W054 */
  958. new Function('');
  959. /* jshint +W031, +W054 */
  960. return false;
  961. } catch (e) {
  962. return true;
  963. }
  964. }
  965. };
  966. /**
  967. * @ngdoc directive
  968. * @module ng
  969. * @name ngJq
  970. *
  971. * @element ANY
  972. * @param {string=} ngJq the name of the library available under `window`
  973. * to be used for angular.element
  974. * @description
  975. * Use this directive to force the angular.element library. This should be
  976. * used to force either jqLite by leaving ng-jq blank or setting the name of
  977. * the jquery variable under window (eg. jQuery).
  978. *
  979. * Since angular looks for this directive when it is loaded (doesn't wait for the
  980. * DOMContentLoaded event), it must be placed on an element that comes before the script
  981. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  982. * others ignored.
  983. *
  984. * @example
  985. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  986. ```html
  987. <!doctype html>
  988. <html ng-app ng-jq>
  989. ...
  990. ...
  991. </html>
  992. ```
  993. * @example
  994. * This example shows how to use a jQuery based library of a different name.
  995. * The library name must be available at the top most 'window'.
  996. ```html
  997. <!doctype html>
  998. <html ng-app ng-jq="jQueryLib">
  999. ...
  1000. ...
  1001. </html>
  1002. ```
  1003. */
  1004. var jq = function() {
  1005. if (isDefined(jq.name_)) return jq.name_;
  1006. var el;
  1007. var i, ii = ngAttrPrefixes.length, prefix, name;
  1008. for (i = 0; i < ii; ++i) {
  1009. prefix = ngAttrPrefixes[i];
  1010. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  1011. name = el.getAttribute(prefix + 'jq');
  1012. break;
  1013. }
  1014. }
  1015. return (jq.name_ = name);
  1016. };
  1017. function concat(array1, array2, index) {
  1018. return array1.concat(slice.call(array2, index));
  1019. }
  1020. function sliceArgs(args, startIndex) {
  1021. return slice.call(args, startIndex || 0);
  1022. }
  1023. /* jshint -W101 */
  1024. /**
  1025. * @ngdoc function
  1026. * @name angular.bind
  1027. * @module ng
  1028. * @kind function
  1029. *
  1030. * @description
  1031. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1032. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1033. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1034. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1035. *
  1036. * @param {Object} self Context which `fn` should be evaluated in.
  1037. * @param {function()} fn Function to be bound.
  1038. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1039. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1040. */
  1041. /* jshint +W101 */
  1042. function bind(self, fn) {
  1043. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1044. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1045. return curryArgs.length
  1046. ? function() {
  1047. return arguments.length
  1048. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1049. : fn.apply(self, curryArgs);
  1050. }
  1051. : function() {
  1052. return arguments.length
  1053. ? fn.apply(self, arguments)
  1054. : fn.call(self);
  1055. };
  1056. } else {
  1057. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  1058. return fn;
  1059. }
  1060. }
  1061. function toJsonReplacer(key, value) {
  1062. var val = value;
  1063. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1064. val = undefined;
  1065. } else if (isWindow(value)) {
  1066. val = '$WINDOW';
  1067. } else if (value && document === value) {
  1068. val = '$DOCUMENT';
  1069. } else if (isScope(value)) {
  1070. val = '$SCOPE';
  1071. }
  1072. return val;
  1073. }
  1074. /**
  1075. * @ngdoc function
  1076. * @name angular.toJson
  1077. * @module ng
  1078. * @kind function
  1079. *
  1080. * @description
  1081. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1082. * stripped since angular uses this notation internally.
  1083. *
  1084. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1085. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1086. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1087. * @returns {string|undefined} JSON-ified string representing `obj`.
  1088. */
  1089. function toJson(obj, pretty) {
  1090. if (typeof obj === 'undefined') return undefined;
  1091. if (!isNumber(pretty)) {
  1092. pretty = pretty ? 2 : null;
  1093. }
  1094. return JSON.stringify(obj, toJsonReplacer, pretty);
  1095. }
  1096. /**
  1097. * @ngdoc function
  1098. * @name angular.fromJson
  1099. * @module ng
  1100. * @kind function
  1101. *
  1102. * @description
  1103. * Deserializes a JSON string.
  1104. *
  1105. * @param {string} json JSON string to deserialize.
  1106. * @returns {Object|Array|string|number} Deserialized JSON string.
  1107. */
  1108. function fromJson(json) {
  1109. return isString(json)
  1110. ? JSON.parse(json)
  1111. : json;
  1112. }
  1113. function timezoneToOffset(timezone, fallback) {
  1114. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1115. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1116. }
  1117. function addDateMinutes(date, minutes) {
  1118. date = new Date(date.getTime());
  1119. date.setMinutes(date.getMinutes() + minutes);
  1120. return date;
  1121. }
  1122. function convertTimezoneToLocal(date, timezone, reverse) {
  1123. reverse = reverse ? -1 : 1;
  1124. var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  1125. return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
  1126. }
  1127. /**
  1128. * @returns {string} Returns the string representation of the element.
  1129. */
  1130. function startingTag(element) {
  1131. element = jqLite(element).clone();
  1132. try {
  1133. // turns out IE does not let you set .html() on elements which
  1134. // are not allowed to have children. So we just ignore it.
  1135. element.empty();
  1136. } catch (e) {}
  1137. var elemHtml = jqLite('<div>').append(element).html();
  1138. try {
  1139. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1140. elemHtml.
  1141. match(/^(<[^>]+>)/)[1].
  1142. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1143. } catch (e) {
  1144. return lowercase(elemHtml);
  1145. }
  1146. }
  1147. /////////////////////////////////////////////////
  1148. /**
  1149. * Tries to decode the URI component without throwing an exception.
  1150. *
  1151. * @private
  1152. * @param str value potential URI component to check.
  1153. * @returns {boolean} True if `value` can be decoded
  1154. * with the decodeURIComponent function.
  1155. */
  1156. function tryDecodeURIComponent(value) {
  1157. try {
  1158. return decodeURIComponent(value);
  1159. } catch (e) {
  1160. // Ignore any invalid uri component
  1161. }
  1162. }
  1163. /**
  1164. * Parses an escaped url query string into key-value pairs.
  1165. * @returns {Object.<string,boolean|Array>}
  1166. */
  1167. function parseKeyValue(/**string*/keyValue) {
  1168. var obj = {};
  1169. forEach((keyValue || "").split('&'), function(keyValue) {
  1170. var splitPoint, key, val;
  1171. if (keyValue) {
  1172. key = keyValue = keyValue.replace(/\+/g,'%20');
  1173. splitPoint = keyValue.indexOf('=');
  1174. if (splitPoint !== -1) {
  1175. key = keyValue.substring(0, splitPoint);
  1176. val = keyValue.substring(splitPoint + 1);
  1177. }
  1178. key = tryDecodeURIComponent(key);
  1179. if (isDefined(key)) {
  1180. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1181. if (!hasOwnProperty.call(obj, key)) {
  1182. obj[key] = val;
  1183. } else if (isArray(obj[key])) {
  1184. obj[key].push(val);
  1185. } else {
  1186. obj[key] = [obj[key],val];
  1187. }
  1188. }
  1189. }
  1190. });
  1191. return obj;
  1192. }
  1193. function toKeyValue(obj) {
  1194. var parts = [];
  1195. forEach(obj, function(value, key) {
  1196. if (isArray(value)) {
  1197. forEach(value, function(arrayValue) {
  1198. parts.push(encodeUriQuery(key, true) +
  1199. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1200. });
  1201. } else {
  1202. parts.push(encodeUriQuery(key, true) +
  1203. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1204. }
  1205. });
  1206. return parts.length ? parts.join('&') : '';
  1207. }
  1208. /**
  1209. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1210. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1211. * segments:
  1212. * segment = *pchar
  1213. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1214. * pct-encoded = "%" HEXDIG HEXDIG
  1215. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1216. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1217. * / "*" / "+" / "," / ";" / "="
  1218. */
  1219. function encodeUriSegment(val) {
  1220. return encodeUriQuery(val, true).
  1221. replace(/%26/gi, '&').
  1222. replace(/%3D/gi, '=').
  1223. replace(/%2B/gi, '+');
  1224. }
  1225. /**
  1226. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1227. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1228. * encoded per http://tools.ietf.org/html/rfc3986:
  1229. * query = *( pchar / "/" / "?" )
  1230. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1231. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1232. * pct-encoded = "%" HEXDIG HEXDIG
  1233. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1234. * / "*" / "+" / "," / ";" / "="
  1235. */
  1236. function encodeUriQuery(val, pctEncodeSpaces) {
  1237. return encodeURIComponent(val).
  1238. replace(/%40/gi, '@').
  1239. replace(/%3A/gi, ':').
  1240. replace(/%24/g, '$').
  1241. replace(/%2C/gi, ',').
  1242. replace(/%3B/gi, ';').
  1243. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1244. }
  1245. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1246. function getNgAttribute(element, ngAttr) {
  1247. var attr, i, ii = ngAttrPrefixes.length;
  1248. for (i = 0; i < ii; ++i) {
  1249. attr = ngAttrPrefixes[i] + ngAttr;
  1250. if (isString(attr = element.getAttribute(attr))) {
  1251. return attr;
  1252. }
  1253. }
  1254. return null;
  1255. }
  1256. /**
  1257. * @ngdoc directive
  1258. * @name ngApp
  1259. * @module ng
  1260. *
  1261. * @element ANY
  1262. * @param {angular.Module} ngApp an optional application
  1263. * {@link angular.module module} name to load.
  1264. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1265. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1266. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1267. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1268. * tracking down the root of these bugs.
  1269. *
  1270. * @description
  1271. *
  1272. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1273. * designates the **root element** of the application and is typically placed near the root element
  1274. * of the page - e.g. on the `<body>` or `<html>` tags.
  1275. *
  1276. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1277. * found in the document will be used to define the root element to auto-bootstrap as an
  1278. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1279. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1280. *
  1281. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1282. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1283. * should contain the application code needed or have dependencies on other modules that will
  1284. * contain the code. See {@link angular.module} for more information.
  1285. *
  1286. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1287. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1288. * would not be resolved to `3`.
  1289. *
  1290. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1291. *
  1292. <example module="ngAppDemo">
  1293. <file name="index.html">
  1294. <div ng-controller="ngAppDemoController">
  1295. I can add: {{a}} + {{b}} = {{ a+b }}
  1296. </div>
  1297. </file>
  1298. <file name="script.js">
  1299. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1300. $scope.a = 1;
  1301. $scope.b = 2;
  1302. });
  1303. </file>
  1304. </example>
  1305. *
  1306. * Using `ngStrictDi`, you would see something like this:
  1307. *
  1308. <example ng-app-included="true">
  1309. <file name="index.html">
  1310. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1311. <div ng-controller="GoodController1">
  1312. I can add: {{a}} + {{b}} = {{ a+b }}
  1313. <p>This renders because the controller does not fail to
  1314. instantiate, by using explicit annotation style (see
  1315. script.js for details)
  1316. </p>
  1317. </div>
  1318. <div ng-controller="GoodController2">
  1319. Name: <input ng-model="name"><br />
  1320. Hello, {{name}}!
  1321. <p>This renders because the controller does not fail to
  1322. instantiate, by using explicit annotation style
  1323. (see script.js for details)
  1324. </p>
  1325. </div>
  1326. <div ng-controller="BadController">
  1327. I can add: {{a}} + {{b}} = {{ a+b }}
  1328. <p>The controller could not be instantiated, due to relying
  1329. on automatic function annotations (which are disabled in
  1330. strict mode). As such, the content of this section is not
  1331. interpolated, and there should be an error in your web console.
  1332. </p>
  1333. </div>
  1334. </div>
  1335. </file>
  1336. <file name="script.js">
  1337. angular.module('ngAppStrictDemo', [])
  1338. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1339. // rather than an explicit annotation
  1340. .controller('BadController', function($scope) {
  1341. $scope.a = 1;
  1342. $scope.b = 2;
  1343. })
  1344. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1345. // due to using explicit annotations using the array style and $inject property, respectively.
  1346. .controller('GoodController1', ['$scope', function($scope) {
  1347. $scope.a = 1;
  1348. $scope.b = 2;
  1349. }])
  1350. .controller('GoodController2', GoodController2);
  1351. function GoodController2($scope) {
  1352. $scope.name = "World";
  1353. }
  1354. GoodController2.$inject = ['$scope'];
  1355. </file>
  1356. <file name="style.css">
  1357. div[ng-controller] {
  1358. margin-bottom: 1em;
  1359. -webkit-border-radius: 4px;
  1360. border-radius: 4px;
  1361. border: 1px solid;
  1362. padding: .5em;
  1363. }
  1364. div[ng-controller^=Good] {
  1365. border-color: #d6e9c6;
  1366. background-color: #dff0d8;
  1367. color: #3c763d;
  1368. }
  1369. div[ng-controller^=Bad] {
  1370. border-color: #ebccd1;
  1371. background-color: #f2dede;
  1372. color: #a94442;
  1373. margin-bottom: 0;
  1374. }
  1375. </file>
  1376. </example>
  1377. */
  1378. function angularInit(element, bootstrap) {
  1379. var appElement,
  1380. module,
  1381. config = {};
  1382. // The element `element` has priority over any other element
  1383. forEach(ngAttrPrefixes, function(prefix) {
  1384. var name = prefix + 'app';
  1385. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1386. appElement = element;
  1387. module = element.getAttribute(name);
  1388. }
  1389. });
  1390. forEach(ngAttrPrefixes, function(prefix) {
  1391. var name = prefix + 'app';
  1392. var candidate;
  1393. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1394. appElement = candidate;
  1395. module = candidate.getAttribute(name);
  1396. }
  1397. });
  1398. if (appElement) {
  1399. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1400. bootstrap(appElement, module ? [module] : [], config);
  1401. }
  1402. }
  1403. /**
  1404. * @ngdoc function
  1405. * @name angular.bootstrap
  1406. * @module ng
  1407. * @description
  1408. * Use this function to manually start up angular application.
  1409. *
  1410. * See: {@link guide/bootstrap Bootstrap}
  1411. *
  1412. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1413. * They must use {@link ng.directive:ngApp ngApp}.
  1414. *
  1415. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1416. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1417. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1418. * multiple instances of Angular try to work on the DOM.
  1419. *
  1420. * ```html
  1421. * <!doctype html>
  1422. * <html>
  1423. * <body>
  1424. * <div ng-controller="WelcomeController">
  1425. * {{greeting}}
  1426. * </div>
  1427. *
  1428. * <script src="angular.js"></script>
  1429. * <script>
  1430. * var app = angular.module('demo', [])
  1431. * .controller('WelcomeController', function($scope) {
  1432. * $scope.greeting = 'Welcome!';
  1433. * });
  1434. * angular.bootstrap(document, ['demo']);
  1435. * </script>
  1436. * </body>
  1437. * </html>
  1438. * ```
  1439. *
  1440. * @param {DOMElement} element DOM element which is the root of angular application.
  1441. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1442. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1443. * function that will be invoked by the injector as a `config` block.
  1444. * See: {@link angular.module modules}
  1445. * @param {Object=} config an object for defining configuration options for the application. The
  1446. * following keys are supported:
  1447. *
  1448. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1449. * assist in finding bugs which break minified code. Defaults to `false`.
  1450. *
  1451. * @returns {auto.$injector} Returns the newly created injector for this app.
  1452. */
  1453. function bootstrap(element, modules, config) {
  1454. if (!isObject(config)) config = {};
  1455. var defaultConfig = {
  1456. strictDi: false
  1457. };
  1458. config = extend(defaultConfig, config);
  1459. var doBootstrap = function() {
  1460. element = jqLite(element);
  1461. if (element.injector()) {
  1462. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1463. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1464. throw ngMinErr(
  1465. 'btstrpd',
  1466. "App Already Bootstrapped with this Element '{0}'",
  1467. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1468. }
  1469. modules = modules || [];
  1470. modules.unshift(['$provide', function($provide) {
  1471. $provide.value('$rootElement', element);
  1472. }]);
  1473. if (config.debugInfoEnabled) {
  1474. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1475. modules.push(['$compileProvider', function($compileProvider) {
  1476. $compileProvider.debugInfoEnabled(true);
  1477. }]);
  1478. }
  1479. modules.unshift('ng');
  1480. var injector = createInjector(modules, config.strictDi);
  1481. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1482. function bootstrapApply(scope, element, compile, injector) {
  1483. scope.$apply(function() {
  1484. element.data('$injector', injector);
  1485. compile(element)(scope);
  1486. });
  1487. }]
  1488. );
  1489. return injector;
  1490. };
  1491. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1492. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1493. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1494. config.debugInfoEnabled = true;
  1495. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1496. }
  1497. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1498. return doBootstrap();
  1499. }
  1500. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1501. angular.resumeBootstrap = function(extraModules) {
  1502. forEach(extraModules, function(module) {
  1503. modules.push(module);
  1504. });
  1505. return doBootstrap();
  1506. };
  1507. if (isFunction(angular.resumeDeferredBootstrap)) {
  1508. angular.resumeDeferredBootstrap();
  1509. }
  1510. }
  1511. /**
  1512. * @ngdoc function
  1513. * @name angular.reloadWithDebugInfo
  1514. * @module ng
  1515. * @description
  1516. * Use this function to reload the current application with debug information turned on.
  1517. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1518. *
  1519. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1520. */
  1521. function reloadWithDebugInfo() {
  1522. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1523. window.location.reload();
  1524. }
  1525. /**
  1526. * @name angular.getTestability
  1527. * @module ng
  1528. * @description
  1529. * Get the testability service for the instance of Angular on the given
  1530. * element.
  1531. * @param {DOMElement} element DOM element which is the root of angular application.
  1532. */
  1533. function getTestability(rootElement) {
  1534. var injector = angular.element(rootElement).injector();
  1535. if (!injector) {
  1536. throw ngMinErr('test',
  1537. 'no injector found for element argument to getTestability');
  1538. }
  1539. return injector.get('$$testability');
  1540. }
  1541. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1542. function snake_case(name, separator) {
  1543. separator = separator || '_';
  1544. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1545. return (pos ? separator : '') + letter.toLowerCase();
  1546. });
  1547. }
  1548. var bindJQueryFired = false;
  1549. var skipDestroyOnNextJQueryCleanData;
  1550. function bindJQuery() {
  1551. var originalCleanData;
  1552. if (bindJQueryFired) {
  1553. return;
  1554. }
  1555. // bind to jQuery if present;
  1556. var jqName = jq();
  1557. jQuery = window.jQuery; // use default jQuery.
  1558. if (isDefined(jqName)) { // `ngJq` present
  1559. jQuery = jqName === null ? undefined : window[jqName]; // if empty; use jqLite. if not empty, use jQuery specified by `ngJq`.
  1560. }
  1561. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1562. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1563. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1564. // versions. It will not work for sure with jQuery <1.7, though.
  1565. if (jQuery && jQuery.fn.on) {
  1566. jqLite = jQuery;
  1567. extend(jQuery.fn, {
  1568. scope: JQLitePrototype.scope,
  1569. isolateScope: JQLitePrototype.isolateScope,
  1570. controller: JQLitePrototype.controller,
  1571. injector: JQLitePrototype.injector,
  1572. inheritedData: JQLitePrototype.inheritedData
  1573. });
  1574. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1575. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1576. // the $destroy event on all removed nodes.
  1577. originalCleanData = jQuery.cleanData;
  1578. jQuery.cleanData = function(elems) {
  1579. var events;
  1580. if (!skipDestroyOnNextJQueryCleanData) {
  1581. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1582. events = jQuery._data(elem, "events");
  1583. if (events && events.$destroy) {
  1584. jQuery(elem).triggerHandler('$destroy');
  1585. }
  1586. }
  1587. } else {
  1588. skipDestroyOnNextJQueryCleanData = false;
  1589. }
  1590. originalCleanData(elems);
  1591. };
  1592. } else {
  1593. jqLite = JQLite;
  1594. }
  1595. angular.element = jqLite;
  1596. // Prevent double-proxying.
  1597. bindJQueryFired = true;
  1598. }
  1599. /**
  1600. * throw error if the argument is falsy.
  1601. */
  1602. function assertArg(arg, name, reason) {
  1603. if (!arg) {
  1604. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1605. }
  1606. return arg;
  1607. }
  1608. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1609. if (acceptArrayAnnotation && isArray(arg)) {
  1610. arg = arg[arg.length - 1];
  1611. }
  1612. assertArg(isFunction(arg), name, 'not a function, got ' +
  1613. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1614. return arg;
  1615. }
  1616. /**
  1617. * throw error if the name given is hasOwnProperty
  1618. * @param {String} name the name to test
  1619. * @param {String} context the context in which the name is used, such as module or directive
  1620. */
  1621. function assertNotHasOwnProperty(name, context) {
  1622. if (name === 'hasOwnProperty') {
  1623. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1624. }
  1625. }
  1626. /**
  1627. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1628. * @param {Object} obj starting object
  1629. * @param {String} path path to traverse
  1630. * @param {boolean} [bindFnToScope=true]
  1631. * @returns {Object} value as accessible by path
  1632. */
  1633. //TODO(misko): this function needs to be removed
  1634. function getter(obj, path, bindFnToScope) {
  1635. if (!path) return obj;
  1636. var keys = path.split('.');
  1637. var key;
  1638. var lastInstance = obj;
  1639. var len = keys.length;
  1640. for (var i = 0; i < len; i++) {
  1641. key = keys[i];
  1642. if (obj) {
  1643. obj = (lastInstance = obj)[key];
  1644. }
  1645. }
  1646. if (!bindFnToScope && isFunction(obj)) {
  1647. return bind(lastInstance, obj);
  1648. }
  1649. return obj;
  1650. }
  1651. /**
  1652. * Return the DOM siblings between the first and last node in the given array.
  1653. * @param {Array} array like object
  1654. * @returns {jqLite} jqLite collection containing the nodes
  1655. */
  1656. function getBlockNodes(nodes) {
  1657. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1658. // collection, otherwise update the original collection.
  1659. var node = nodes[0];
  1660. var endNode = nodes[nodes.length - 1];
  1661. var blockNodes = [node];
  1662. do {
  1663. node = node.nextSibling;
  1664. if (!node) break;
  1665. blockNodes.push(node);
  1666. } while (node !== endNode);
  1667. return jqLite(blockNodes);
  1668. }
  1669. /**
  1670. * Creates a new object without a prototype. This object is useful for lookup without having to
  1671. * guard against prototypically inherited properties via hasOwnProperty.
  1672. *
  1673. * Related micro-benchmarks:
  1674. * - http://jsperf.com/object-create2
  1675. * - http://jsperf.com/proto-map-lookup/2
  1676. * - http://jsperf.com/for-in-vs-object-keys2
  1677. *
  1678. * @returns {Object}
  1679. */
  1680. function createMap() {
  1681. return Object.create(null);
  1682. }
  1683. var NODE_TYPE_ELEMENT = 1;
  1684. var NODE_TYPE_ATTRIBUTE = 2;
  1685. var NODE_TYPE_TEXT = 3;
  1686. var NODE_TYPE_COMMENT = 8;
  1687. var NODE_TYPE_DOCUMENT = 9;
  1688. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1689. /**
  1690. * @ngdoc type
  1691. * @name angular.Module
  1692. * @module ng
  1693. * @description
  1694. *
  1695. * Interface for configuring angular {@link angular.module modules}.
  1696. */
  1697. function setupModuleLoader(window) {
  1698. var $injectorMinErr = minErr('$injector');
  1699. var ngMinErr = minErr('ng');
  1700. function ensure(obj, name, factory) {
  1701. return obj[name] || (obj[name] = factory());
  1702. }
  1703. var angular = ensure(window, 'angular', Object);
  1704. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1705. angular.$$minErr = angular.$$minErr || minErr;
  1706. return ensure(angular, 'module', function() {
  1707. /** @type {Object.<string, angular.Module>} */
  1708. var modules = {};
  1709. /**
  1710. * @ngdoc function
  1711. * @name angular.module
  1712. * @module ng
  1713. * @description
  1714. *
  1715. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1716. * modules.
  1717. * All modules (angular core or 3rd party) that should be available to an application must be
  1718. * registered using this mechanism.
  1719. *
  1720. * Passing one argument retrieves an existing {@link angular.Module},
  1721. * whereas passing more than one argument creates a new {@link angular.Module}
  1722. *
  1723. *
  1724. * # Module
  1725. *
  1726. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1727. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1728. *
  1729. * ```js
  1730. * // Create a new module
  1731. * var myModule = angular.module('myModule', []);
  1732. *
  1733. * // register a new service
  1734. * myModule.value('appName', 'MyCoolApp');
  1735. *
  1736. * // configure existing services inside initialization blocks.
  1737. * myModule.config(['$locationProvider', function($locationProvider) {
  1738. * // Configure existing providers
  1739. * $locationProvider.hashPrefix('!');
  1740. * }]);
  1741. * ```
  1742. *
  1743. * Then you can create an injector and load your modules like this:
  1744. *
  1745. * ```js
  1746. * var injector = angular.injector(['ng', 'myModule'])
  1747. * ```
  1748. *
  1749. * However it's more likely that you'll just use
  1750. * {@link ng.directive:ngApp ngApp} or
  1751. * {@link angular.bootstrap} to simplify this process for you.
  1752. *
  1753. * @param {!string} name The name of the module to create or retrieve.
  1754. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1755. * unspecified then the module is being retrieved for further configuration.
  1756. * @param {Function=} configFn Optional configuration function for the module. Same as
  1757. * {@link angular.Module#config Module#config()}.
  1758. * @returns {module} new module with the {@link angular.Module} api.
  1759. */
  1760. return function module(name, requires, configFn) {
  1761. var assertNotHasOwnProperty = function(name, context) {
  1762. if (name === 'hasOwnProperty') {
  1763. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1764. }
  1765. };
  1766. assertNotHasOwnProperty(name, 'module');
  1767. if (requires && modules.hasOwnProperty(name)) {
  1768. modules[name] = null;
  1769. }
  1770. return ensure(modules, name, function() {
  1771. if (!requires) {
  1772. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1773. "the module name or forgot to load it. If registering a module ensure that you " +
  1774. "specify the dependencies as the second argument.", name);
  1775. }
  1776. /** @type {!Array.<Array.<*>>} */
  1777. var invokeQueue = [];
  1778. /** @type {!Array.<Function>} */
  1779. var configBlocks = [];
  1780. /** @type {!Array.<Function>} */
  1781. var runBlocks = [];
  1782. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1783. /** @type {angular.Module} */
  1784. var moduleInstance = {
  1785. // Private state
  1786. _invokeQueue: invokeQueue,
  1787. _configBlocks: configBlocks,
  1788. _runBlocks: runBlocks,
  1789. /**
  1790. * @ngdoc property
  1791. * @name angular.Module#requires
  1792. * @module ng
  1793. *
  1794. * @description
  1795. * Holds the list of modules which the injector will load before the current module is
  1796. * loaded.
  1797. */
  1798. requires: requires,
  1799. /**
  1800. * @ngdoc property
  1801. * @name angular.Module#name
  1802. * @module ng
  1803. *
  1804. * @description
  1805. * Name of the module.
  1806. */
  1807. name: name,
  1808. /**
  1809. * @ngdoc method
  1810. * @name angular.Module#provider
  1811. * @module ng
  1812. * @param {string} name service name
  1813. * @param {Function} providerType Construction function for creating new instance of the
  1814. * service.
  1815. * @description
  1816. * See {@link auto.$provide#provider $provide.provider()}.
  1817. */
  1818. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1819. /**
  1820. * @ngdoc method
  1821. * @name angular.Module#factory
  1822. * @module ng
  1823. * @param {string} name service name
  1824. * @param {Function} providerFunction Function for creating new instance of the service.
  1825. * @description
  1826. * See {@link auto.$provide#factory $provide.factory()}.
  1827. */
  1828. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1829. /**
  1830. * @ngdoc method
  1831. * @name angular.Module#service
  1832. * @module ng
  1833. * @param {string} name service name
  1834. * @param {Function} constructor A constructor function that will be instantiated.
  1835. * @description
  1836. * See {@link auto.$provide#service $provide.service()}.
  1837. */
  1838. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1839. /**
  1840. * @ngdoc method
  1841. * @name angular.Module#value
  1842. * @module ng
  1843. * @param {string} name service name
  1844. * @param {*} object Service instance object.
  1845. * @description
  1846. * See {@link auto.$provide#value $provide.value()}.
  1847. */
  1848. value: invokeLater('$provide', 'value'),
  1849. /**
  1850. * @ngdoc method
  1851. * @name angular.Module#constant
  1852. * @module ng
  1853. * @param {string} name constant name
  1854. * @param {*} object Constant value.
  1855. * @description
  1856. * Because the constant are fixed, they get applied before other provide methods.
  1857. * See {@link auto.$provide#constant $provide.constant()}.
  1858. */
  1859. constant: invokeLater('$provide', 'constant', 'unshift'),
  1860. /**
  1861. * @ngdoc method
  1862. * @name angular.Module#decorator
  1863. * @module ng
  1864. * @param {string} The name of the service to decorate.
  1865. * @param {Function} This function will be invoked when the service needs to be
  1866. * instantiated and should return the decorated service instance.
  1867. * @description
  1868. * See {@link auto.$provide#decorator $provide.decorator()}.
  1869. */
  1870. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1871. /**
  1872. * @ngdoc method
  1873. * @name angular.Module#animation
  1874. * @module ng
  1875. * @param {string} name animation name
  1876. * @param {Function} animationFactory Factory function for creating new instance of an
  1877. * animation.
  1878. * @description
  1879. *
  1880. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1881. *
  1882. *
  1883. * Defines an animation hook that can be later used with
  1884. * {@link $animate $animate} service and directives that use this service.
  1885. *
  1886. * ```js
  1887. * module.animation('.animation-name', function($inject1, $inject2) {
  1888. * return {
  1889. * eventName : function(element, done) {
  1890. * //code to run the animation
  1891. * //once complete, then run done()
  1892. * return function cancellationFunction(element) {
  1893. * //code to cancel the animation
  1894. * }
  1895. * }
  1896. * }
  1897. * })
  1898. * ```
  1899. *
  1900. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1901. * {@link ngAnimate ngAnimate module} for more information.
  1902. */
  1903. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1904. /**
  1905. * @ngdoc method
  1906. * @name angular.Module#filter
  1907. * @module ng
  1908. * @param {string} name Filter name - this must be a valid angular expression identifier
  1909. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1910. * @description
  1911. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1912. *
  1913. * <div class="alert alert-warning">
  1914. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1915. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1916. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1917. * (`myapp_subsection_filterx`).
  1918. * </div>
  1919. */
  1920. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  1921. /**
  1922. * @ngdoc method
  1923. * @name angular.Module#controller
  1924. * @module ng
  1925. * @param {string|Object} name Controller name, or an object map of controllers where the
  1926. * keys are the names and the values are the constructors.
  1927. * @param {Function} constructor Controller constructor function.
  1928. * @description
  1929. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1930. */
  1931. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  1932. /**
  1933. * @ngdoc method
  1934. * @name angular.Module#directive
  1935. * @module ng
  1936. * @param {string|Object} name Directive name, or an object map of directives where the
  1937. * keys are the names and the values are the factories.
  1938. * @param {Function} directiveFactory Factory function for creating new instance of
  1939. * directives.
  1940. * @description
  1941. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1942. */
  1943. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  1944. /**
  1945. * @ngdoc method
  1946. * @name angular.Module#config
  1947. * @module ng
  1948. * @param {Function} configFn Execute this function on module load. Useful for service
  1949. * configuration.
  1950. * @description
  1951. * Use this method to register work which needs to be performed on module loading.
  1952. * For more about how to configure services, see
  1953. * {@link providers#provider-recipe Provider Recipe}.
  1954. */
  1955. config: config,
  1956. /**
  1957. * @ngdoc method
  1958. * @name angular.Module#run
  1959. * @module ng
  1960. * @param {Function} initializationFn Execute this function after injector creation.
  1961. * Useful for application initialization.
  1962. * @description
  1963. * Use this method to register work which should be performed when the injector is done
  1964. * loading all modules.
  1965. */
  1966. run: function(block) {
  1967. runBlocks.push(block);
  1968. return this;
  1969. }
  1970. };
  1971. if (configFn) {
  1972. config(configFn);
  1973. }
  1974. return moduleInstance;
  1975. /**
  1976. * @param {string} provider
  1977. * @param {string} method
  1978. * @param {String=} insertMethod
  1979. * @returns {angular.Module}
  1980. */
  1981. function invokeLater(provider, method, insertMethod, queue) {
  1982. if (!queue) queue = invokeQueue;
  1983. return function() {
  1984. queue[insertMethod || 'push']([provider, method, arguments]);
  1985. return moduleInstance;
  1986. };
  1987. }
  1988. /**
  1989. * @param {string} provider
  1990. * @param {string} method
  1991. * @returns {angular.Module}
  1992. */
  1993. function invokeLaterAndSetModuleName(provider, method) {
  1994. return function(recipeName, factoryFunction) {
  1995. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  1996. invokeQueue.push([provider, method, arguments]);
  1997. return moduleInstance;
  1998. };
  1999. }
  2000. });
  2001. };
  2002. });
  2003. }
  2004. /* global: toDebugString: true */
  2005. function serializeObject(obj) {
  2006. var seen = [];
  2007. return JSON.stringify(obj, function(key, val) {
  2008. val = toJsonReplacer(key, val);
  2009. if (isObject(val)) {
  2010. if (seen.indexOf(val) >= 0) return '<<already seen>>';
  2011. seen.push(val);
  2012. }
  2013. return val;
  2014. });
  2015. }
  2016. function toDebugString(obj) {
  2017. if (typeof obj === 'function') {
  2018. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2019. } else if (typeof obj === 'undefined') {
  2020. return 'undefined';
  2021. } else if (typeof obj !== 'string') {
  2022. return serializeObject(obj);
  2023. }
  2024. return obj;
  2025. }
  2026. /* global angularModule: true,
  2027. version: true,
  2028. $CompileProvider,
  2029. htmlAnchorDirective,
  2030. inputDirective,
  2031. inputDirective,
  2032. formDirective,
  2033. scriptDirective,
  2034. selectDirective,
  2035. styleDirective,
  2036. optionDirective,
  2037. ngBindDirective,
  2038. ngBindHtmlDirective,
  2039. ngBindTemplateDirective,
  2040. ngClassDirective,
  2041. ngClassEvenDirective,
  2042. ngClassOddDirective,
  2043. ngCloakDirective,
  2044. ngControllerDirective,
  2045. ngFormDirective,
  2046. ngHideDirective,
  2047. ngIfDirective,
  2048. ngIncludeDirective,
  2049. ngIncludeFillContentDirective,
  2050. ngInitDirective,
  2051. ngNonBindableDirective,
  2052. ngPluralizeDirective,
  2053. ngRepeatDirective,
  2054. ngShowDirective,
  2055. ngStyleDirective,
  2056. ngSwitchDirective,
  2057. ngSwitchWhenDirective,
  2058. ngSwitchDefaultDirective,
  2059. ngOptionsDirective,
  2060. ngTranscludeDirective,
  2061. ngModelDirective,
  2062. ngListDirective,
  2063. ngChangeDirective,
  2064. patternDirective,
  2065. patternDirective,
  2066. requiredDirective,
  2067. requiredDirective,
  2068. minlengthDirective,
  2069. minlengthDirective,
  2070. maxlengthDirective,
  2071. maxlengthDirective,
  2072. ngValueDirective,
  2073. ngModelOptionsDirective,
  2074. ngAttributeAliasDirectives,
  2075. ngEventDirectives,
  2076. $AnchorScrollProvider,
  2077. $AnimateProvider,
  2078. $CoreAnimateCssProvider,
  2079. $$CoreAnimateQueueProvider,
  2080. $$CoreAnimateRunnerProvider,
  2081. $BrowserProvider,
  2082. $CacheFactoryProvider,
  2083. $ControllerProvider,
  2084. $DocumentProvider,
  2085. $ExceptionHandlerProvider,
  2086. $FilterProvider,
  2087. $$ForceReflowProvider,
  2088. $InterpolateProvider,
  2089. $IntervalProvider,
  2090. $$HashMapProvider,
  2091. $HttpProvider,
  2092. $HttpParamSerializerProvider,
  2093. $HttpParamSerializerJQLikeProvider,
  2094. $HttpBackendProvider,
  2095. $LocationProvider,
  2096. $LogProvider,
  2097. $ParseProvider,
  2098. $RootScopeProvider,
  2099. $QProvider,
  2100. $$QProvider,
  2101. $$SanitizeUriProvider,
  2102. $SceProvider,
  2103. $SceDelegateProvider,
  2104. $SnifferProvider,
  2105. $TemplateCacheProvider,
  2106. $TemplateRequestProvider,
  2107. $$TestabilityProvider,
  2108. $TimeoutProvider,
  2109. $$RAFProvider,
  2110. $WindowProvider,
  2111. $$jqLiteProvider,
  2112. $$CookieReaderProvider
  2113. */
  2114. /**
  2115. * @ngdoc object
  2116. * @name angular.version
  2117. * @module ng
  2118. * @description
  2119. * An object that contains information about the current AngularJS version. This object has the
  2120. * following properties:
  2121. *
  2122. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2123. * - `major` – `{number}` – Major version number, such as "0".
  2124. * - `minor` – `{number}` – Minor version number, such as "9".
  2125. * - `dot` – `{number}` – Dot version number, such as "18".
  2126. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2127. */
  2128. var version = {
  2129. full: '1.4.4', // all of these placeholder strings will be replaced by grunt's
  2130. major: 1, // package task
  2131. minor: 4,
  2132. dot: 4,
  2133. codeName: 'pylon-requirement'
  2134. };
  2135. function publishExternalAPI(angular) {
  2136. extend(angular, {
  2137. 'bootstrap': bootstrap,
  2138. 'copy': copy,
  2139. 'extend': extend,
  2140. 'merge': merge,
  2141. 'equals': equals,
  2142. 'element': jqLite,
  2143. 'forEach': forEach,
  2144. 'injector': createInjector,
  2145. 'noop': noop,
  2146. 'bind': bind,
  2147. 'toJson': toJson,
  2148. 'fromJson': fromJson,
  2149. 'identity': identity,
  2150. 'isUndefined': isUndefined,
  2151. 'isDefined': isDefined,
  2152. 'isString': isString,
  2153. 'isFunction': isFunction,
  2154. 'isObject': isObject,
  2155. 'isNumber': isNumber,
  2156. 'isElement': isElement,
  2157. 'isArray': isArray,
  2158. 'version': version,
  2159. 'isDate': isDate,
  2160. 'lowercase': lowercase,
  2161. 'uppercase': uppercase,
  2162. 'callbacks': {counter: 0},
  2163. 'getTestability': getTestability,
  2164. '$$minErr': minErr,
  2165. '$$csp': csp,
  2166. 'reloadWithDebugInfo': reloadWithDebugInfo
  2167. });
  2168. angularModule = setupModuleLoader(window);
  2169. angularModule('ng', ['ngLocale'], ['$provide',
  2170. function ngModule($provide) {
  2171. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2172. $provide.provider({
  2173. $$sanitizeUri: $$SanitizeUriProvider
  2174. });
  2175. $provide.provider('$compile', $CompileProvider).
  2176. directive({
  2177. a: htmlAnchorDirective,
  2178. input: inputDirective,
  2179. textarea: inputDirective,
  2180. form: formDirective,
  2181. script: scriptDirective,
  2182. select: selectDirective,
  2183. style: styleDirective,
  2184. option: optionDirective,
  2185. ngBind: ngBindDirective,
  2186. ngBindHtml: ngBindHtmlDirective,
  2187. ngBindTemplate: ngBindTemplateDirective,
  2188. ngClass: ngClassDirective,
  2189. ngClassEven: ngClassEvenDirective,
  2190. ngClassOdd: ngClassOddDirective,
  2191. ngCloak: ngCloakDirective,
  2192. ngController: ngControllerDirective,
  2193. ngForm: ngFormDirective,
  2194. ngHide: ngHideDirective,
  2195. ngIf: ngIfDirective,
  2196. ngInclude: ngIncludeDirective,
  2197. ngInit: ngInitDirective,
  2198. ngNonBindable: ngNonBindableDirective,
  2199. ngPluralize: ngPluralizeDirective,
  2200. ngRepeat: ngRepeatDirective,
  2201. ngShow: ngShowDirective,
  2202. ngStyle: ngStyleDirective,
  2203. ngSwitch: ngSwitchDirective,
  2204. ngSwitchWhen: ngSwitchWhenDirective,
  2205. ngSwitchDefault: ngSwitchDefaultDirective,
  2206. ngOptions: ngOptionsDirective,
  2207. ngTransclude: ngTranscludeDirective,
  2208. ngModel: ngModelDirective,
  2209. ngList: ngListDirective,
  2210. ngChange: ngChangeDirective,
  2211. pattern: patternDirective,
  2212. ngPattern: patternDirective,
  2213. required: requiredDirective,
  2214. ngRequired: requiredDirective,
  2215. minlength: minlengthDirective,
  2216. ngMinlength: minlengthDirective,
  2217. maxlength: maxlengthDirective,
  2218. ngMaxlength: maxlengthDirective,
  2219. ngValue: ngValueDirective,
  2220. ngModelOptions: ngModelOptionsDirective
  2221. }).
  2222. directive({
  2223. ngInclude: ngIncludeFillContentDirective
  2224. }).
  2225. directive(ngAttributeAliasDirectives).
  2226. directive(ngEventDirectives);
  2227. $provide.provider({
  2228. $anchorScroll: $AnchorScrollProvider,
  2229. $animate: $AnimateProvider,
  2230. $animateCss: $CoreAnimateCssProvider,
  2231. $$animateQueue: $$CoreAnimateQueueProvider,
  2232. $$AnimateRunner: $$CoreAnimateRunnerProvider,
  2233. $browser: $BrowserProvider,
  2234. $cacheFactory: $CacheFactoryProvider,
  2235. $controller: $ControllerProvider,
  2236. $document: $DocumentProvider,
  2237. $exceptionHandler: $ExceptionHandlerProvider,
  2238. $filter: $FilterProvider,
  2239. $$forceReflow: $$ForceReflowProvider,
  2240. $interpolate: $InterpolateProvider,
  2241. $interval: $IntervalProvider,
  2242. $http: $HttpProvider,
  2243. $httpParamSerializer: $HttpParamSerializerProvider,
  2244. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2245. $httpBackend: $HttpBackendProvider,
  2246. $location: $LocationProvider,
  2247. $log: $LogProvider,
  2248. $parse: $ParseProvider,
  2249. $rootScope: $RootScopeProvider,
  2250. $q: $QProvider,
  2251. $$q: $$QProvider,
  2252. $sce: $SceProvider,
  2253. $sceDelegate: $SceDelegateProvider,
  2254. $sniffer: $SnifferProvider,
  2255. $templateCache: $TemplateCacheProvider,
  2256. $templateRequest: $TemplateRequestProvider,
  2257. $$testability: $$TestabilityProvider,
  2258. $timeout: $TimeoutProvider,
  2259. $window: $WindowProvider,
  2260. $$rAF: $$RAFProvider,
  2261. $$jqLite: $$jqLiteProvider,
  2262. $$HashMap: $$HashMapProvider,
  2263. $$cookieReader: $$CookieReaderProvider
  2264. });
  2265. }
  2266. ]);
  2267. }
  2268. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2269. * Any commits to this file should be reviewed with security in mind. *
  2270. * Changes to this file can potentially create security vulnerabilities. *
  2271. * An approval from 2 Core members with history of modifying *
  2272. * this file is required. *
  2273. * *
  2274. * Does the change somehow allow for arbitrary javascript to be executed? *
  2275. * Or allows for someone to change the prototype of built-in objects? *
  2276. * Or gives undesired access to variables likes document or window? *
  2277. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2278. /* global JQLitePrototype: true,
  2279. addEventListenerFn: true,
  2280. removeEventListenerFn: true,
  2281. BOOLEAN_ATTR: true,
  2282. ALIASED_ATTR: true,
  2283. */
  2284. //////////////////////////////////
  2285. //JQLite
  2286. //////////////////////////////////
  2287. /**
  2288. * @ngdoc function
  2289. * @name angular.element
  2290. * @module ng
  2291. * @kind function
  2292. *
  2293. * @description
  2294. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2295. *
  2296. * If jQuery is available, `angular.element` is an alias for the
  2297. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2298. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2299. *
  2300. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2301. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2302. * commonly needed functionality with the goal of having a very small footprint.</div>
  2303. *
  2304. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
  2305. *
  2306. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2307. * jqLite; they are never raw DOM references.</div>
  2308. *
  2309. * ## Angular's jqLite
  2310. * jqLite provides only the following jQuery methods:
  2311. *
  2312. * - [`addClass()`](http://api.jquery.com/addClass/)
  2313. * - [`after()`](http://api.jquery.com/after/)
  2314. * - [`append()`](http://api.jquery.com/append/)
  2315. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2316. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2317. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2318. * - [`clone()`](http://api.jquery.com/clone/)
  2319. * - [`contents()`](http://api.jquery.com/contents/)
  2320. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
  2321. * - [`data()`](http://api.jquery.com/data/)
  2322. * - [`detach()`](http://api.jquery.com/detach/)
  2323. * - [`empty()`](http://api.jquery.com/empty/)
  2324. * - [`eq()`](http://api.jquery.com/eq/)
  2325. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2326. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2327. * - [`html()`](http://api.jquery.com/html/)
  2328. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2329. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2330. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2331. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2332. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2333. * - [`prepend()`](http://api.jquery.com/prepend/)
  2334. * - [`prop()`](http://api.jquery.com/prop/)
  2335. * - [`ready()`](http://api.jquery.com/ready/)
  2336. * - [`remove()`](http://api.jquery.com/remove/)
  2337. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2338. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2339. * - [`removeData()`](http://api.jquery.com/removeData/)
  2340. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2341. * - [`text()`](http://api.jquery.com/text/)
  2342. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2343. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2344. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2345. * - [`val()`](http://api.jquery.com/val/)
  2346. * - [`wrap()`](http://api.jquery.com/wrap/)
  2347. *
  2348. * ## jQuery/jqLite Extras
  2349. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2350. *
  2351. * ### Events
  2352. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2353. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2354. * element before it is removed.
  2355. *
  2356. * ### Methods
  2357. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2358. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2359. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2360. * `'ngModel'`).
  2361. * - `injector()` - retrieves the injector of the current element or its parent.
  2362. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2363. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2364. * be enabled.
  2365. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2366. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2367. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2368. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2369. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2370. * parent element is reached.
  2371. *
  2372. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2373. * @returns {Object} jQuery object.
  2374. */
  2375. JQLite.expando = 'ng339';
  2376. var jqCache = JQLite.cache = {},
  2377. jqId = 1,
  2378. addEventListenerFn = function(element, type, fn) {
  2379. element.addEventListener(type, fn, false);
  2380. },
  2381. removeEventListenerFn = function(element, type, fn) {
  2382. element.removeEventListener(type, fn, false);
  2383. };
  2384. /*
  2385. * !!! This is an undocumented "private" function !!!
  2386. */
  2387. JQLite._data = function(node) {
  2388. //jQuery always returns an object on cache miss
  2389. return this.cache[node[this.expando]] || {};
  2390. };
  2391. function jqNextId() { return ++jqId; }
  2392. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2393. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2394. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2395. var jqLiteMinErr = minErr('jqLite');
  2396. /**
  2397. * Converts snake_case to camelCase.
  2398. * Also there is special case for Moz prefix starting with upper case letter.
  2399. * @param name Name to normalize
  2400. */
  2401. function camelCase(name) {
  2402. return name.
  2403. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2404. return offset ? letter.toUpperCase() : letter;
  2405. }).
  2406. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2407. }
  2408. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2409. var HTML_REGEXP = /<|&#?\w+;/;
  2410. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2411. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2412. var wrapMap = {
  2413. 'option': [1, '<select multiple="multiple">', '</select>'],
  2414. 'thead': [1, '<table>', '</table>'],
  2415. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2416. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2417. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2418. '_default': [0, "", ""]
  2419. };
  2420. wrapMap.optgroup = wrapMap.option;
  2421. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2422. wrapMap.th = wrapMap.td;
  2423. function jqLiteIsTextNode(html) {
  2424. return !HTML_REGEXP.test(html);
  2425. }
  2426. function jqLiteAcceptsData(node) {
  2427. // The window object can accept data but has no nodeType
  2428. // Otherwise we are only interested in elements (1) and documents (9)
  2429. var nodeType = node.nodeType;
  2430. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2431. }
  2432. function jqLiteHasData(node) {
  2433. for (var key in jqCache[node.ng339]) {
  2434. return true;
  2435. }
  2436. return false;
  2437. }
  2438. function jqLiteBuildFragment(html, context) {
  2439. var tmp, tag, wrap,
  2440. fragment = context.createDocumentFragment(),
  2441. nodes = [], i;
  2442. if (jqLiteIsTextNode(html)) {
  2443. // Convert non-html into a text node
  2444. nodes.push(context.createTextNode(html));
  2445. } else {
  2446. // Convert html into DOM nodes
  2447. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2448. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2449. wrap = wrapMap[tag] || wrapMap._default;
  2450. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2451. // Descend through wrappers to the right content
  2452. i = wrap[0];
  2453. while (i--) {
  2454. tmp = tmp.lastChild;
  2455. }
  2456. nodes = concat(nodes, tmp.childNodes);
  2457. tmp = fragment.firstChild;
  2458. tmp.textContent = "";
  2459. }
  2460. // Remove wrapper from fragment
  2461. fragment.textContent = "";
  2462. fragment.innerHTML = ""; // Clear inner HTML
  2463. forEach(nodes, function(node) {
  2464. fragment.appendChild(node);
  2465. });
  2466. return fragment;
  2467. }
  2468. function jqLiteParseHTML(html, context) {
  2469. context = context || document;
  2470. var parsed;
  2471. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2472. return [context.createElement(parsed[1])];
  2473. }
  2474. if ((parsed = jqLiteBuildFragment(html, context))) {
  2475. return parsed.childNodes;
  2476. }
  2477. return [];
  2478. }
  2479. /////////////////////////////////////////////
  2480. function JQLite(element) {
  2481. if (element instanceof JQLite) {
  2482. return element;
  2483. }
  2484. var argIsString;
  2485. if (isString(element)) {
  2486. element = trim(element);
  2487. argIsString = true;
  2488. }
  2489. if (!(this instanceof JQLite)) {
  2490. if (argIsString && element.charAt(0) != '<') {
  2491. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2492. }
  2493. return new JQLite(element);
  2494. }
  2495. if (argIsString) {
  2496. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2497. } else {
  2498. jqLiteAddNodes(this, element);
  2499. }
  2500. }
  2501. function jqLiteClone(element) {
  2502. return element.cloneNode(true);
  2503. }
  2504. function jqLiteDealoc(element, onlyDescendants) {
  2505. if (!onlyDescendants) jqLiteRemoveData(element);
  2506. if (element.querySelectorAll) {
  2507. var descendants = element.querySelectorAll('*');
  2508. for (var i = 0, l = descendants.length; i < l; i++) {
  2509. jqLiteRemoveData(descendants[i]);
  2510. }
  2511. }
  2512. }
  2513. function jqLiteOff(element, type, fn, unsupported) {
  2514. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2515. var expandoStore = jqLiteExpandoStore(element);
  2516. var events = expandoStore && expandoStore.events;
  2517. var handle = expandoStore && expandoStore.handle;
  2518. if (!handle) return; //no listeners registered
  2519. if (!type) {
  2520. for (type in events) {
  2521. if (type !== '$destroy') {
  2522. removeEventListenerFn(element, type, handle);
  2523. }
  2524. delete events[type];
  2525. }
  2526. } else {
  2527. forEach(type.split(' '), function(type) {
  2528. if (isDefined(fn)) {
  2529. var listenerFns = events[type];
  2530. arrayRemove(listenerFns || [], fn);
  2531. if (listenerFns && listenerFns.length > 0) {
  2532. return;
  2533. }
  2534. }
  2535. removeEventListenerFn(element, type, handle);
  2536. delete events[type];
  2537. });
  2538. }
  2539. }
  2540. function jqLiteRemoveData(element, name) {
  2541. var expandoId = element.ng339;
  2542. var expandoStore = expandoId && jqCache[expandoId];
  2543. if (expandoStore) {
  2544. if (name) {
  2545. delete expandoStore.data[name];
  2546. return;
  2547. }
  2548. if (expandoStore.handle) {
  2549. if (expandoStore.events.$destroy) {
  2550. expandoStore.handle({}, '$destroy');
  2551. }
  2552. jqLiteOff(element);
  2553. }
  2554. delete jqCache[expandoId];
  2555. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2556. }
  2557. }
  2558. function jqLiteExpandoStore(element, createIfNecessary) {
  2559. var expandoId = element.ng339,
  2560. expandoStore = expandoId && jqCache[expandoId];
  2561. if (createIfNecessary && !expandoStore) {
  2562. element.ng339 = expandoId = jqNextId();
  2563. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2564. }
  2565. return expandoStore;
  2566. }
  2567. function jqLiteData(element, key, value) {
  2568. if (jqLiteAcceptsData(element)) {
  2569. var isSimpleSetter = isDefined(value);
  2570. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2571. var massGetter = !key;
  2572. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2573. var data = expandoStore && expandoStore.data;
  2574. if (isSimpleSetter) { // data('key', value)
  2575. data[key] = value;
  2576. } else {
  2577. if (massGetter) { // data()
  2578. return data;
  2579. } else {
  2580. if (isSimpleGetter) { // data('key')
  2581. // don't force creation of expandoStore if it doesn't exist yet
  2582. return data && data[key];
  2583. } else { // mass-setter: data({key1: val1, key2: val2})
  2584. extend(data, key);
  2585. }
  2586. }
  2587. }
  2588. }
  2589. }
  2590. function jqLiteHasClass(element, selector) {
  2591. if (!element.getAttribute) return false;
  2592. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2593. indexOf(" " + selector + " ") > -1);
  2594. }
  2595. function jqLiteRemoveClass(element, cssClasses) {
  2596. if (cssClasses && element.setAttribute) {
  2597. forEach(cssClasses.split(' '), function(cssClass) {
  2598. element.setAttribute('class', trim(
  2599. (" " + (element.getAttribute('class') || '') + " ")
  2600. .replace(/[\n\t]/g, " ")
  2601. .replace(" " + trim(cssClass) + " ", " "))
  2602. );
  2603. });
  2604. }
  2605. }
  2606. function jqLiteAddClass(element, cssClasses) {
  2607. if (cssClasses && element.setAttribute) {
  2608. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2609. .replace(/[\n\t]/g, " ");
  2610. forEach(cssClasses.split(' '), function(cssClass) {
  2611. cssClass = trim(cssClass);
  2612. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2613. existingClasses += cssClass + ' ';
  2614. }
  2615. });
  2616. element.setAttribute('class', trim(existingClasses));
  2617. }
  2618. }
  2619. function jqLiteAddNodes(root, elements) {
  2620. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2621. if (elements) {
  2622. // if a Node (the most common case)
  2623. if (elements.nodeType) {
  2624. root[root.length++] = elements;
  2625. } else {
  2626. var length = elements.length;
  2627. // if an Array or NodeList and not a Window
  2628. if (typeof length === 'number' && elements.window !== elements) {
  2629. if (length) {
  2630. for (var i = 0; i < length; i++) {
  2631. root[root.length++] = elements[i];
  2632. }
  2633. }
  2634. } else {
  2635. root[root.length++] = elements;
  2636. }
  2637. }
  2638. }
  2639. }
  2640. function jqLiteController(element, name) {
  2641. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2642. }
  2643. function jqLiteInheritedData(element, name, value) {
  2644. // if element is the document object work with the html element instead
  2645. // this makes $(document).scope() possible
  2646. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2647. element = element.documentElement;
  2648. }
  2649. var names = isArray(name) ? name : [name];
  2650. while (element) {
  2651. for (var i = 0, ii = names.length; i < ii; i++) {
  2652. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2653. }
  2654. // If dealing with a document fragment node with a host element, and no parent, use the host
  2655. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2656. // to lookup parent controllers.
  2657. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2658. }
  2659. }
  2660. function jqLiteEmpty(element) {
  2661. jqLiteDealoc(element, true);
  2662. while (element.firstChild) {
  2663. element.removeChild(element.firstChild);
  2664. }
  2665. }
  2666. function jqLiteRemove(element, keepData) {
  2667. if (!keepData) jqLiteDealoc(element);
  2668. var parent = element.parentNode;
  2669. if (parent) parent.removeChild(element);
  2670. }
  2671. function jqLiteDocumentLoaded(action, win) {
  2672. win = win || window;
  2673. if (win.document.readyState === 'complete') {
  2674. // Force the action to be run async for consistent behaviour
  2675. // from the action's point of view
  2676. // i.e. it will definitely not be in a $apply
  2677. win.setTimeout(action);
  2678. } else {
  2679. // No need to unbind this handler as load is only ever called once
  2680. jqLite(win).on('load', action);
  2681. }
  2682. }
  2683. //////////////////////////////////////////
  2684. // Functions which are declared directly.
  2685. //////////////////////////////////////////
  2686. var JQLitePrototype = JQLite.prototype = {
  2687. ready: function(fn) {
  2688. var fired = false;
  2689. function trigger() {
  2690. if (fired) return;
  2691. fired = true;
  2692. fn();
  2693. }
  2694. // check if document is already loaded
  2695. if (document.readyState === 'complete') {
  2696. setTimeout(trigger);
  2697. } else {
  2698. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2699. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2700. // jshint -W064
  2701. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2702. // jshint +W064
  2703. }
  2704. },
  2705. toString: function() {
  2706. var value = [];
  2707. forEach(this, function(e) { value.push('' + e);});
  2708. return '[' + value.join(', ') + ']';
  2709. },
  2710. eq: function(index) {
  2711. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2712. },
  2713. length: 0,
  2714. push: push,
  2715. sort: [].sort,
  2716. splice: [].splice
  2717. };
  2718. //////////////////////////////////////////
  2719. // Functions iterating getter/setters.
  2720. // these functions return self on setter and
  2721. // value on get.
  2722. //////////////////////////////////////////
  2723. var BOOLEAN_ATTR = {};
  2724. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2725. BOOLEAN_ATTR[lowercase(value)] = value;
  2726. });
  2727. var BOOLEAN_ELEMENTS = {};
  2728. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2729. BOOLEAN_ELEMENTS[value] = true;
  2730. });
  2731. var ALIASED_ATTR = {
  2732. 'ngMinlength': 'minlength',
  2733. 'ngMaxlength': 'maxlength',
  2734. 'ngMin': 'min',
  2735. 'ngMax': 'max',
  2736. 'ngPattern': 'pattern'
  2737. };
  2738. function getBooleanAttrName(element, name) {
  2739. // check dom last since we will most likely fail on name
  2740. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2741. // booleanAttr is here twice to minimize DOM access
  2742. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2743. }
  2744. function getAliasedAttrName(element, name) {
  2745. var nodeName = element.nodeName;
  2746. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2747. }
  2748. forEach({
  2749. data: jqLiteData,
  2750. removeData: jqLiteRemoveData,
  2751. hasData: jqLiteHasData
  2752. }, function(fn, name) {
  2753. JQLite[name] = fn;
  2754. });
  2755. forEach({
  2756. data: jqLiteData,
  2757. inheritedData: jqLiteInheritedData,
  2758. scope: function(element) {
  2759. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2760. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2761. },
  2762. isolateScope: function(element) {
  2763. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2764. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2765. },
  2766. controller: jqLiteController,
  2767. injector: function(element) {
  2768. return jqLiteInheritedData(element, '$injector');
  2769. },
  2770. removeAttr: function(element, name) {
  2771. element.removeAttribute(name);
  2772. },
  2773. hasClass: jqLiteHasClass,
  2774. css: function(element, name, value) {
  2775. name = camelCase(name);
  2776. if (isDefined(value)) {
  2777. element.style[name] = value;
  2778. } else {
  2779. return element.style[name];
  2780. }
  2781. },
  2782. attr: function(element, name, value) {
  2783. var nodeType = element.nodeType;
  2784. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2785. return;
  2786. }
  2787. var lowercasedName = lowercase(name);
  2788. if (BOOLEAN_ATTR[lowercasedName]) {
  2789. if (isDefined(value)) {
  2790. if (!!value) {
  2791. element[name] = true;
  2792. element.setAttribute(name, lowercasedName);
  2793. } else {
  2794. element[name] = false;
  2795. element.removeAttribute(lowercasedName);
  2796. }
  2797. } else {
  2798. return (element[name] ||
  2799. (element.attributes.getNamedItem(name) || noop).specified)
  2800. ? lowercasedName
  2801. : undefined;
  2802. }
  2803. } else if (isDefined(value)) {
  2804. element.setAttribute(name, value);
  2805. } else if (element.getAttribute) {
  2806. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2807. // some elements (e.g. Document) don't have get attribute, so return undefined
  2808. var ret = element.getAttribute(name, 2);
  2809. // normalize non-existing attributes to undefined (as jQuery)
  2810. return ret === null ? undefined : ret;
  2811. }
  2812. },
  2813. prop: function(element, name, value) {
  2814. if (isDefined(value)) {
  2815. element[name] = value;
  2816. } else {
  2817. return element[name];
  2818. }
  2819. },
  2820. text: (function() {
  2821. getText.$dv = '';
  2822. return getText;
  2823. function getText(element, value) {
  2824. if (isUndefined(value)) {
  2825. var nodeType = element.nodeType;
  2826. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2827. }
  2828. element.textContent = value;
  2829. }
  2830. })(),
  2831. val: function(element, value) {
  2832. if (isUndefined(value)) {
  2833. if (element.multiple && nodeName_(element) === 'select') {
  2834. var result = [];
  2835. forEach(element.options, function(option) {
  2836. if (option.selected) {
  2837. result.push(option.value || option.text);
  2838. }
  2839. });
  2840. return result.length === 0 ? null : result;
  2841. }
  2842. return element.value;
  2843. }
  2844. element.value = value;
  2845. },
  2846. html: function(element, value) {
  2847. if (isUndefined(value)) {
  2848. return element.innerHTML;
  2849. }
  2850. jqLiteDealoc(element, true);
  2851. element.innerHTML = value;
  2852. },
  2853. empty: jqLiteEmpty
  2854. }, function(fn, name) {
  2855. /**
  2856. * Properties: writes return selection, reads return first value
  2857. */
  2858. JQLite.prototype[name] = function(arg1, arg2) {
  2859. var i, key;
  2860. var nodeCount = this.length;
  2861. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2862. // in a way that survives minification.
  2863. // jqLiteEmpty takes no arguments but is a setter.
  2864. if (fn !== jqLiteEmpty &&
  2865. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2866. if (isObject(arg1)) {
  2867. // we are a write, but the object properties are the key/values
  2868. for (i = 0; i < nodeCount; i++) {
  2869. if (fn === jqLiteData) {
  2870. // data() takes the whole object in jQuery
  2871. fn(this[i], arg1);
  2872. } else {
  2873. for (key in arg1) {
  2874. fn(this[i], key, arg1[key]);
  2875. }
  2876. }
  2877. }
  2878. // return self for chaining
  2879. return this;
  2880. } else {
  2881. // we are a read, so read the first child.
  2882. // TODO: do we still need this?
  2883. var value = fn.$dv;
  2884. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2885. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2886. for (var j = 0; j < jj; j++) {
  2887. var nodeValue = fn(this[j], arg1, arg2);
  2888. value = value ? value + nodeValue : nodeValue;
  2889. }
  2890. return value;
  2891. }
  2892. } else {
  2893. // we are a write, so apply to all children
  2894. for (i = 0; i < nodeCount; i++) {
  2895. fn(this[i], arg1, arg2);
  2896. }
  2897. // return self for chaining
  2898. return this;
  2899. }
  2900. };
  2901. });
  2902. function createEventHandler(element, events) {
  2903. var eventHandler = function(event, type) {
  2904. // jQuery specific api
  2905. event.isDefaultPrevented = function() {
  2906. return event.defaultPrevented;
  2907. };
  2908. var eventFns = events[type || event.type];
  2909. var eventFnsLength = eventFns ? eventFns.length : 0;
  2910. if (!eventFnsLength) return;
  2911. if (isUndefined(event.immediatePropagationStopped)) {
  2912. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2913. event.stopImmediatePropagation = function() {
  2914. event.immediatePropagationStopped = true;
  2915. if (event.stopPropagation) {
  2916. event.stopPropagation();
  2917. }
  2918. if (originalStopImmediatePropagation) {
  2919. originalStopImmediatePropagation.call(event);
  2920. }
  2921. };
  2922. }
  2923. event.isImmediatePropagationStopped = function() {
  2924. return event.immediatePropagationStopped === true;
  2925. };
  2926. // Copy event handlers in case event handlers array is modified during execution.
  2927. if ((eventFnsLength > 1)) {
  2928. eventFns = shallowCopy(eventFns);
  2929. }
  2930. for (var i = 0; i < eventFnsLength; i++) {
  2931. if (!event.isImmediatePropagationStopped()) {
  2932. eventFns[i].call(element, event);
  2933. }
  2934. }
  2935. };
  2936. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2937. // events on `element`
  2938. eventHandler.elem = element;
  2939. return eventHandler;
  2940. }
  2941. //////////////////////////////////////////
  2942. // Functions iterating traversal.
  2943. // These functions chain results into a single
  2944. // selector.
  2945. //////////////////////////////////////////
  2946. forEach({
  2947. removeData: jqLiteRemoveData,
  2948. on: function jqLiteOn(element, type, fn, unsupported) {
  2949. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2950. // Do not add event handlers to non-elements because they will not be cleaned up.
  2951. if (!jqLiteAcceptsData(element)) {
  2952. return;
  2953. }
  2954. var expandoStore = jqLiteExpandoStore(element, true);
  2955. var events = expandoStore.events;
  2956. var handle = expandoStore.handle;
  2957. if (!handle) {
  2958. handle = expandoStore.handle = createEventHandler(element, events);
  2959. }
  2960. // http://jsperf.com/string-indexof-vs-split
  2961. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2962. var i = types.length;
  2963. while (i--) {
  2964. type = types[i];
  2965. var eventFns = events[type];
  2966. if (!eventFns) {
  2967. events[type] = [];
  2968. if (type === 'mouseenter' || type === 'mouseleave') {
  2969. // Refer to jQuery's implementation of mouseenter & mouseleave
  2970. // Read about mouseenter and mouseleave:
  2971. // http://www.quirksmode.org/js/events_mouse.html#link8
  2972. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2973. var target = this, related = event.relatedTarget;
  2974. // For mousenter/leave call the handler if related is outside the target.
  2975. // NB: No relatedTarget if the mouse left/entered the browser window
  2976. if (!related || (related !== target && !target.contains(related))) {
  2977. handle(event, type);
  2978. }
  2979. });
  2980. } else {
  2981. if (type !== '$destroy') {
  2982. addEventListenerFn(element, type, handle);
  2983. }
  2984. }
  2985. eventFns = events[type];
  2986. }
  2987. eventFns.push(fn);
  2988. }
  2989. },
  2990. off: jqLiteOff,
  2991. one: function(element, type, fn) {
  2992. element = jqLite(element);
  2993. //add the listener twice so that when it is called
  2994. //you can remove the original function and still be
  2995. //able to call element.off(ev, fn) normally
  2996. element.on(type, function onFn() {
  2997. element.off(type, fn);
  2998. element.off(type, onFn);
  2999. });
  3000. element.on(type, fn);
  3001. },
  3002. replaceWith: function(element, replaceNode) {
  3003. var index, parent = element.parentNode;
  3004. jqLiteDealoc(element);
  3005. forEach(new JQLite(replaceNode), function(node) {
  3006. if (index) {
  3007. parent.insertBefore(node, index.nextSibling);
  3008. } else {
  3009. parent.replaceChild(node, element);
  3010. }
  3011. index = node;
  3012. });
  3013. },
  3014. children: function(element) {
  3015. var children = [];
  3016. forEach(element.childNodes, function(element) {
  3017. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3018. children.push(element);
  3019. }
  3020. });
  3021. return children;
  3022. },
  3023. contents: function(element) {
  3024. return element.contentDocument || element.childNodes || [];
  3025. },
  3026. append: function(element, node) {
  3027. var nodeType = element.nodeType;
  3028. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3029. node = new JQLite(node);
  3030. for (var i = 0, ii = node.length; i < ii; i++) {
  3031. var child = node[i];
  3032. element.appendChild(child);
  3033. }
  3034. },
  3035. prepend: function(element, node) {
  3036. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3037. var index = element.firstChild;
  3038. forEach(new JQLite(node), function(child) {
  3039. element.insertBefore(child, index);
  3040. });
  3041. }
  3042. },
  3043. wrap: function(element, wrapNode) {
  3044. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  3045. var parent = element.parentNode;
  3046. if (parent) {
  3047. parent.replaceChild(wrapNode, element);
  3048. }
  3049. wrapNode.appendChild(element);
  3050. },
  3051. remove: jqLiteRemove,
  3052. detach: function(element) {
  3053. jqLiteRemove(element, true);
  3054. },
  3055. after: function(element, newElement) {
  3056. var index = element, parent = element.parentNode;
  3057. newElement = new JQLite(newElement);
  3058. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3059. var node = newElement[i];
  3060. parent.insertBefore(node, index.nextSibling);
  3061. index = node;
  3062. }
  3063. },
  3064. addClass: jqLiteAddClass,
  3065. removeClass: jqLiteRemoveClass,
  3066. toggleClass: function(element, selector, condition) {
  3067. if (selector) {
  3068. forEach(selector.split(' '), function(className) {
  3069. var classCondition = condition;
  3070. if (isUndefined(classCondition)) {
  3071. classCondition = !jqLiteHasClass(element, className);
  3072. }
  3073. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3074. });
  3075. }
  3076. },
  3077. parent: function(element) {
  3078. var parent = element.parentNode;
  3079. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3080. },
  3081. next: function(element) {
  3082. return element.nextElementSibling;
  3083. },
  3084. find: function(element, selector) {
  3085. if (element.getElementsByTagName) {
  3086. return element.getElementsByTagName(selector);
  3087. } else {
  3088. return [];
  3089. }
  3090. },
  3091. clone: jqLiteClone,
  3092. triggerHandler: function(element, event, extraParameters) {
  3093. var dummyEvent, eventFnsCopy, handlerArgs;
  3094. var eventName = event.type || event;
  3095. var expandoStore = jqLiteExpandoStore(element);
  3096. var events = expandoStore && expandoStore.events;
  3097. var eventFns = events && events[eventName];
  3098. if (eventFns) {
  3099. // Create a dummy event to pass to the handlers
  3100. dummyEvent = {
  3101. preventDefault: function() { this.defaultPrevented = true; },
  3102. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3103. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3104. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3105. stopPropagation: noop,
  3106. type: eventName,
  3107. target: element
  3108. };
  3109. // If a custom event was provided then extend our dummy event with it
  3110. if (event.type) {
  3111. dummyEvent = extend(dummyEvent, event);
  3112. }
  3113. // Copy event handlers in case event handlers array is modified during execution.
  3114. eventFnsCopy = shallowCopy(eventFns);
  3115. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3116. forEach(eventFnsCopy, function(fn) {
  3117. if (!dummyEvent.isImmediatePropagationStopped()) {
  3118. fn.apply(element, handlerArgs);
  3119. }
  3120. });
  3121. }
  3122. }
  3123. }, function(fn, name) {
  3124. /**
  3125. * chaining functions
  3126. */
  3127. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3128. var value;
  3129. for (var i = 0, ii = this.length; i < ii; i++) {
  3130. if (isUndefined(value)) {
  3131. value = fn(this[i], arg1, arg2, arg3);
  3132. if (isDefined(value)) {
  3133. // any function which returns a value needs to be wrapped
  3134. value = jqLite(value);
  3135. }
  3136. } else {
  3137. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3138. }
  3139. }
  3140. return isDefined(value) ? value : this;
  3141. };
  3142. // bind legacy bind/unbind to on/off
  3143. JQLite.prototype.bind = JQLite.prototype.on;
  3144. JQLite.prototype.unbind = JQLite.prototype.off;
  3145. });
  3146. // Provider for private $$jqLite service
  3147. function $$jqLiteProvider() {
  3148. this.$get = function $$jqLite() {
  3149. return extend(JQLite, {
  3150. hasClass: function(node, classes) {
  3151. if (node.attr) node = node[0];
  3152. return jqLiteHasClass(node, classes);
  3153. },
  3154. addClass: function(node, classes) {
  3155. if (node.attr) node = node[0];
  3156. return jqLiteAddClass(node, classes);
  3157. },
  3158. removeClass: function(node, classes) {
  3159. if (node.attr) node = node[0];
  3160. return jqLiteRemoveClass(node, classes);
  3161. }
  3162. });
  3163. };
  3164. }
  3165. /**
  3166. * Computes a hash of an 'obj'.
  3167. * Hash of a:
  3168. * string is string
  3169. * number is number as string
  3170. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3171. * that is also assigned to the $$hashKey property of the object.
  3172. *
  3173. * @param obj
  3174. * @returns {string} hash string such that the same input will have the same hash string.
  3175. * The resulting string key is in 'type:hashKey' format.
  3176. */
  3177. function hashKey(obj, nextUidFn) {
  3178. var key = obj && obj.$$hashKey;
  3179. if (key) {
  3180. if (typeof key === 'function') {
  3181. key = obj.$$hashKey();
  3182. }
  3183. return key;
  3184. }
  3185. var objType = typeof obj;
  3186. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3187. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3188. } else {
  3189. key = objType + ':' + obj;
  3190. }
  3191. return key;
  3192. }
  3193. /**
  3194. * HashMap which can use objects as keys
  3195. */
  3196. function HashMap(array, isolatedUid) {
  3197. if (isolatedUid) {
  3198. var uid = 0;
  3199. this.nextUid = function() {
  3200. return ++uid;
  3201. };
  3202. }
  3203. forEach(array, this.put, this);
  3204. }
  3205. HashMap.prototype = {
  3206. /**
  3207. * Store key value pair
  3208. * @param key key to store can be any type
  3209. * @param value value to store can be any type
  3210. */
  3211. put: function(key, value) {
  3212. this[hashKey(key, this.nextUid)] = value;
  3213. },
  3214. /**
  3215. * @param key
  3216. * @returns {Object} the value for the key
  3217. */
  3218. get: function(key) {
  3219. return this[hashKey(key, this.nextUid)];
  3220. },
  3221. /**
  3222. * Remove the key/value pair
  3223. * @param key
  3224. */
  3225. remove: function(key) {
  3226. var value = this[key = hashKey(key, this.nextUid)];
  3227. delete this[key];
  3228. return value;
  3229. }
  3230. };
  3231. var $$HashMapProvider = [function() {
  3232. this.$get = [function() {
  3233. return HashMap;
  3234. }];
  3235. }];
  3236. /**
  3237. * @ngdoc function
  3238. * @module ng
  3239. * @name angular.injector
  3240. * @kind function
  3241. *
  3242. * @description
  3243. * Creates an injector object that can be used for retrieving services as well as for
  3244. * dependency injection (see {@link guide/di dependency injection}).
  3245. *
  3246. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3247. * {@link angular.module}. The `ng` module must be explicitly added.
  3248. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3249. * disallows argument name annotation inference.
  3250. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3251. *
  3252. * @example
  3253. * Typical usage
  3254. * ```js
  3255. * // create an injector
  3256. * var $injector = angular.injector(['ng']);
  3257. *
  3258. * // use the injector to kick off your application
  3259. * // use the type inference to auto inject arguments, or use implicit injection
  3260. * $injector.invoke(function($rootScope, $compile, $document) {
  3261. * $compile($document)($rootScope);
  3262. * $rootScope.$digest();
  3263. * });
  3264. * ```
  3265. *
  3266. * Sometimes you want to get access to the injector of a currently running Angular app
  3267. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3268. * application has been bootstrapped. You can do this using the extra `injector()` added
  3269. * to JQuery/jqLite elements. See {@link angular.element}.
  3270. *
  3271. * *This is fairly rare but could be the case if a third party library is injecting the
  3272. * markup.*
  3273. *
  3274. * In the following example a new block of HTML containing a `ng-controller`
  3275. * directive is added to the end of the document body by JQuery. We then compile and link
  3276. * it into the current AngularJS scope.
  3277. *
  3278. * ```js
  3279. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3280. * $(document.body).append($div);
  3281. *
  3282. * angular.element(document).injector().invoke(function($compile) {
  3283. * var scope = angular.element($div).scope();
  3284. * $compile($div)(scope);
  3285. * });
  3286. * ```
  3287. */
  3288. /**
  3289. * @ngdoc module
  3290. * @name auto
  3291. * @description
  3292. *
  3293. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3294. */
  3295. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  3296. var FN_ARG_SPLIT = /,/;
  3297. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3298. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3299. var $injectorMinErr = minErr('$injector');
  3300. function anonFn(fn) {
  3301. // For anonymous functions, showing at the very least the function signature can help in
  3302. // debugging.
  3303. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3304. args = fnText.match(FN_ARGS);
  3305. if (args) {
  3306. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3307. }
  3308. return 'fn';
  3309. }
  3310. function annotate(fn, strictDi, name) {
  3311. var $inject,
  3312. fnText,
  3313. argDecl,
  3314. last;
  3315. if (typeof fn === 'function') {
  3316. if (!($inject = fn.$inject)) {
  3317. $inject = [];
  3318. if (fn.length) {
  3319. if (strictDi) {
  3320. if (!isString(name) || !name) {
  3321. name = fn.name || anonFn(fn);
  3322. }
  3323. throw $injectorMinErr('strictdi',
  3324. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3325. }
  3326. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3327. argDecl = fnText.match(FN_ARGS);
  3328. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3329. arg.replace(FN_ARG, function(all, underscore, name) {
  3330. $inject.push(name);
  3331. });
  3332. });
  3333. }
  3334. fn.$inject = $inject;
  3335. }
  3336. } else if (isArray(fn)) {
  3337. last = fn.length - 1;
  3338. assertArgFn(fn[last], 'fn');
  3339. $inject = fn.slice(0, last);
  3340. } else {
  3341. assertArgFn(fn, 'fn', true);
  3342. }
  3343. return $inject;
  3344. }
  3345. ///////////////////////////////////////
  3346. /**
  3347. * @ngdoc service
  3348. * @name $injector
  3349. *
  3350. * @description
  3351. *
  3352. * `$injector` is used to retrieve object instances as defined by
  3353. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3354. * and load modules.
  3355. *
  3356. * The following always holds true:
  3357. *
  3358. * ```js
  3359. * var $injector = angular.injector();
  3360. * expect($injector.get('$injector')).toBe($injector);
  3361. * expect($injector.invoke(function($injector) {
  3362. * return $injector;
  3363. * })).toBe($injector);
  3364. * ```
  3365. *
  3366. * # Injection Function Annotation
  3367. *
  3368. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3369. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3370. *
  3371. * ```js
  3372. * // inferred (only works if code not minified/obfuscated)
  3373. * $injector.invoke(function(serviceA){});
  3374. *
  3375. * // annotated
  3376. * function explicit(serviceA) {};
  3377. * explicit.$inject = ['serviceA'];
  3378. * $injector.invoke(explicit);
  3379. *
  3380. * // inline
  3381. * $injector.invoke(['serviceA', function(serviceA){}]);
  3382. * ```
  3383. *
  3384. * ## Inference
  3385. *
  3386. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3387. * can then be parsed and the function arguments can be extracted. This method of discovering
  3388. * annotations is disallowed when the injector is in strict mode.
  3389. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3390. * argument names.
  3391. *
  3392. * ## `$inject` Annotation
  3393. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3394. *
  3395. * ## Inline
  3396. * As an array of injection names, where the last item in the array is the function to call.
  3397. */
  3398. /**
  3399. * @ngdoc method
  3400. * @name $injector#get
  3401. *
  3402. * @description
  3403. * Return an instance of the service.
  3404. *
  3405. * @param {string} name The name of the instance to retrieve.
  3406. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3407. * @return {*} The instance.
  3408. */
  3409. /**
  3410. * @ngdoc method
  3411. * @name $injector#invoke
  3412. *
  3413. * @description
  3414. * Invoke the method and supply the method arguments from the `$injector`.
  3415. *
  3416. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3417. * injected according to the {@link guide/di $inject Annotation} rules.
  3418. * @param {Object=} self The `this` for the invoked method.
  3419. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3420. * object first, before the `$injector` is consulted.
  3421. * @returns {*} the value returned by the invoked `fn` function.
  3422. */
  3423. /**
  3424. * @ngdoc method
  3425. * @name $injector#has
  3426. *
  3427. * @description
  3428. * Allows the user to query if the particular service exists.
  3429. *
  3430. * @param {string} name Name of the service to query.
  3431. * @returns {boolean} `true` if injector has given service.
  3432. */
  3433. /**
  3434. * @ngdoc method
  3435. * @name $injector#instantiate
  3436. * @description
  3437. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3438. * operator, and supplies all of the arguments to the constructor function as specified by the
  3439. * constructor annotation.
  3440. *
  3441. * @param {Function} Type Annotated constructor function.
  3442. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3443. * object first, before the `$injector` is consulted.
  3444. * @returns {Object} new instance of `Type`.
  3445. */
  3446. /**
  3447. * @ngdoc method
  3448. * @name $injector#annotate
  3449. *
  3450. * @description
  3451. * Returns an array of service names which the function is requesting for injection. This API is
  3452. * used by the injector to determine which services need to be injected into the function when the
  3453. * function is invoked. There are three ways in which the function can be annotated with the needed
  3454. * dependencies.
  3455. *
  3456. * # Argument names
  3457. *
  3458. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3459. * by converting the function into a string using `toString()` method and extracting the argument
  3460. * names.
  3461. * ```js
  3462. * // Given
  3463. * function MyController($scope, $route) {
  3464. * // ...
  3465. * }
  3466. *
  3467. * // Then
  3468. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3469. * ```
  3470. *
  3471. * You can disallow this method by using strict injection mode.
  3472. *
  3473. * This method does not work with code minification / obfuscation. For this reason the following
  3474. * annotation strategies are supported.
  3475. *
  3476. * # The `$inject` property
  3477. *
  3478. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3479. * represent names of services to be injected into the function.
  3480. * ```js
  3481. * // Given
  3482. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3483. * // ...
  3484. * }
  3485. * // Define function dependencies
  3486. * MyController['$inject'] = ['$scope', '$route'];
  3487. *
  3488. * // Then
  3489. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3490. * ```
  3491. *
  3492. * # The array notation
  3493. *
  3494. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3495. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3496. * a way that survives minification is a better choice:
  3497. *
  3498. * ```js
  3499. * // We wish to write this (not minification / obfuscation safe)
  3500. * injector.invoke(function($compile, $rootScope) {
  3501. * // ...
  3502. * });
  3503. *
  3504. * // We are forced to write break inlining
  3505. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3506. * // ...
  3507. * };
  3508. * tmpFn.$inject = ['$compile', '$rootScope'];
  3509. * injector.invoke(tmpFn);
  3510. *
  3511. * // To better support inline function the inline annotation is supported
  3512. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3513. * // ...
  3514. * }]);
  3515. *
  3516. * // Therefore
  3517. * expect(injector.annotate(
  3518. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3519. * ).toEqual(['$compile', '$rootScope']);
  3520. * ```
  3521. *
  3522. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3523. * be retrieved as described above.
  3524. *
  3525. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3526. *
  3527. * @returns {Array.<string>} The names of the services which the function requires.
  3528. */
  3529. /**
  3530. * @ngdoc service
  3531. * @name $provide
  3532. *
  3533. * @description
  3534. *
  3535. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3536. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3537. * {@link angular.Module}.
  3538. *
  3539. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3540. * factories** are functions which, in turn, are created by a **service provider**.
  3541. * The **service providers** are constructor functions. When instantiated they must contain a
  3542. * property called `$get`, which holds the **service factory** function.
  3543. *
  3544. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3545. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3546. * function to get the instance of the **service**.
  3547. *
  3548. * Often services have no configuration options and there is no need to add methods to the service
  3549. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3550. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3551. * services without specifying a provider.
  3552. *
  3553. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3554. * {@link auto.$injector $injector}
  3555. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3556. * providers and services.
  3557. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3558. * services, not providers.
  3559. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3560. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3561. * given factory function.
  3562. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3563. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3564. * a new object using the given constructor function.
  3565. *
  3566. * See the individual methods for more information and examples.
  3567. */
  3568. /**
  3569. * @ngdoc method
  3570. * @name $provide#provider
  3571. * @description
  3572. *
  3573. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3574. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3575. * service.
  3576. *
  3577. * Service provider names start with the name of the service they provide followed by `Provider`.
  3578. * For example, the {@link ng.$log $log} service has a provider called
  3579. * {@link ng.$logProvider $logProvider}.
  3580. *
  3581. * Service provider objects can have additional methods which allow configuration of the provider
  3582. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3583. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3584. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3585. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3586. * console or not.
  3587. *
  3588. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3589. 'Provider'` key.
  3590. * @param {(Object|function())} provider If the provider is:
  3591. *
  3592. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3593. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3594. * - `Constructor`: a new instance of the provider will be created using
  3595. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3596. *
  3597. * @returns {Object} registered provider instance
  3598. * @example
  3599. *
  3600. * The following example shows how to create a simple event tracking service and register it using
  3601. * {@link auto.$provide#provider $provide.provider()}.
  3602. *
  3603. * ```js
  3604. * // Define the eventTracker provider
  3605. * function EventTrackerProvider() {
  3606. * var trackingUrl = '/track';
  3607. *
  3608. * // A provider method for configuring where the tracked events should been saved
  3609. * this.setTrackingUrl = function(url) {
  3610. * trackingUrl = url;
  3611. * };
  3612. *
  3613. * // The service factory function
  3614. * this.$get = ['$http', function($http) {
  3615. * var trackedEvents = {};
  3616. * return {
  3617. * // Call this to track an event
  3618. * event: function(event) {
  3619. * var count = trackedEvents[event] || 0;
  3620. * count += 1;
  3621. * trackedEvents[event] = count;
  3622. * return count;
  3623. * },
  3624. * // Call this to save the tracked events to the trackingUrl
  3625. * save: function() {
  3626. * $http.post(trackingUrl, trackedEvents);
  3627. * }
  3628. * };
  3629. * }];
  3630. * }
  3631. *
  3632. * describe('eventTracker', function() {
  3633. * var postSpy;
  3634. *
  3635. * beforeEach(module(function($provide) {
  3636. * // Register the eventTracker provider
  3637. * $provide.provider('eventTracker', EventTrackerProvider);
  3638. * }));
  3639. *
  3640. * beforeEach(module(function(eventTrackerProvider) {
  3641. * // Configure eventTracker provider
  3642. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3643. * }));
  3644. *
  3645. * it('tracks events', inject(function(eventTracker) {
  3646. * expect(eventTracker.event('login')).toEqual(1);
  3647. * expect(eventTracker.event('login')).toEqual(2);
  3648. * }));
  3649. *
  3650. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3651. * postSpy = spyOn($http, 'post');
  3652. * eventTracker.event('login');
  3653. * eventTracker.save();
  3654. * expect(postSpy).toHaveBeenCalled();
  3655. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3656. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3657. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3658. * }));
  3659. * });
  3660. * ```
  3661. */
  3662. /**
  3663. * @ngdoc method
  3664. * @name $provide#factory
  3665. * @description
  3666. *
  3667. * Register a **service factory**, which will be called to return the service instance.
  3668. * This is short for registering a service where its provider consists of only a `$get` property,
  3669. * which is the given service factory function.
  3670. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3671. * configure your service in a provider.
  3672. *
  3673. * @param {string} name The name of the instance.
  3674. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3675. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3676. * @returns {Object} registered provider instance
  3677. *
  3678. * @example
  3679. * Here is an example of registering a service
  3680. * ```js
  3681. * $provide.factory('ping', ['$http', function($http) {
  3682. * return function ping() {
  3683. * return $http.send('/ping');
  3684. * };
  3685. * }]);
  3686. * ```
  3687. * You would then inject and use this service like this:
  3688. * ```js
  3689. * someModule.controller('Ctrl', ['ping', function(ping) {
  3690. * ping();
  3691. * }]);
  3692. * ```
  3693. */
  3694. /**
  3695. * @ngdoc method
  3696. * @name $provide#service
  3697. * @description
  3698. *
  3699. * Register a **service constructor**, which will be invoked with `new` to create the service
  3700. * instance.
  3701. * This is short for registering a service where its provider's `$get` property is the service
  3702. * constructor function that will be used to instantiate the service instance.
  3703. *
  3704. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3705. * as a type/class.
  3706. *
  3707. * @param {string} name The name of the instance.
  3708. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3709. * that will be instantiated.
  3710. * @returns {Object} registered provider instance
  3711. *
  3712. * @example
  3713. * Here is an example of registering a service using
  3714. * {@link auto.$provide#service $provide.service(class)}.
  3715. * ```js
  3716. * var Ping = function($http) {
  3717. * this.$http = $http;
  3718. * };
  3719. *
  3720. * Ping.$inject = ['$http'];
  3721. *
  3722. * Ping.prototype.send = function() {
  3723. * return this.$http.get('/ping');
  3724. * };
  3725. * $provide.service('ping', Ping);
  3726. * ```
  3727. * You would then inject and use this service like this:
  3728. * ```js
  3729. * someModule.controller('Ctrl', ['ping', function(ping) {
  3730. * ping.send();
  3731. * }]);
  3732. * ```
  3733. */
  3734. /**
  3735. * @ngdoc method
  3736. * @name $provide#value
  3737. * @description
  3738. *
  3739. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3740. * number, an array, an object or a function. This is short for registering a service where its
  3741. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3742. * service**.
  3743. *
  3744. * Value services are similar to constant services, except that they cannot be injected into a
  3745. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3746. * an Angular
  3747. * {@link auto.$provide#decorator decorator}.
  3748. *
  3749. * @param {string} name The name of the instance.
  3750. * @param {*} value The value.
  3751. * @returns {Object} registered provider instance
  3752. *
  3753. * @example
  3754. * Here are some examples of creating value services.
  3755. * ```js
  3756. * $provide.value('ADMIN_USER', 'admin');
  3757. *
  3758. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3759. *
  3760. * $provide.value('halfOf', function(value) {
  3761. * return value / 2;
  3762. * });
  3763. * ```
  3764. */
  3765. /**
  3766. * @ngdoc method
  3767. * @name $provide#constant
  3768. * @description
  3769. *
  3770. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3771. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3772. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3773. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3774. *
  3775. * @param {string} name The name of the constant.
  3776. * @param {*} value The constant value.
  3777. * @returns {Object} registered instance
  3778. *
  3779. * @example
  3780. * Here a some examples of creating constants:
  3781. * ```js
  3782. * $provide.constant('SHARD_HEIGHT', 306);
  3783. *
  3784. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3785. *
  3786. * $provide.constant('double', function(value) {
  3787. * return value * 2;
  3788. * });
  3789. * ```
  3790. */
  3791. /**
  3792. * @ngdoc method
  3793. * @name $provide#decorator
  3794. * @description
  3795. *
  3796. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3797. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3798. * service. The object returned by the decorator may be the original service, or a new service
  3799. * object which replaces or wraps and delegates to the original service.
  3800. *
  3801. * @param {string} name The name of the service to decorate.
  3802. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3803. * instantiated and should return the decorated service instance. The function is called using
  3804. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3805. * Local injection arguments:
  3806. *
  3807. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3808. * decorated or delegated to.
  3809. *
  3810. * @example
  3811. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3812. * calls to {@link ng.$log#error $log.warn()}.
  3813. * ```js
  3814. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3815. * $delegate.warn = $delegate.error;
  3816. * return $delegate;
  3817. * }]);
  3818. * ```
  3819. */
  3820. function createInjector(modulesToLoad, strictDi) {
  3821. strictDi = (strictDi === true);
  3822. var INSTANTIATING = {},
  3823. providerSuffix = 'Provider',
  3824. path = [],
  3825. loadedModules = new HashMap([], true),
  3826. providerCache = {
  3827. $provide: {
  3828. provider: supportObject(provider),
  3829. factory: supportObject(factory),
  3830. service: supportObject(service),
  3831. value: supportObject(value),
  3832. constant: supportObject(constant),
  3833. decorator: decorator
  3834. }
  3835. },
  3836. providerInjector = (providerCache.$injector =
  3837. createInternalInjector(providerCache, function(serviceName, caller) {
  3838. if (angular.isString(caller)) {
  3839. path.push(caller);
  3840. }
  3841. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3842. })),
  3843. instanceCache = {},
  3844. instanceInjector = (instanceCache.$injector =
  3845. createInternalInjector(instanceCache, function(serviceName, caller) {
  3846. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3847. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3848. }));
  3849. forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });
  3850. return instanceInjector;
  3851. ////////////////////////////////////
  3852. // $provider
  3853. ////////////////////////////////////
  3854. function supportObject(delegate) {
  3855. return function(key, value) {
  3856. if (isObject(key)) {
  3857. forEach(key, reverseParams(delegate));
  3858. } else {
  3859. return delegate(key, value);
  3860. }
  3861. };
  3862. }
  3863. function provider(name, provider_) {
  3864. assertNotHasOwnProperty(name, 'service');
  3865. if (isFunction(provider_) || isArray(provider_)) {
  3866. provider_ = providerInjector.instantiate(provider_);
  3867. }
  3868. if (!provider_.$get) {
  3869. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3870. }
  3871. return providerCache[name + providerSuffix] = provider_;
  3872. }
  3873. function enforceReturnValue(name, factory) {
  3874. return function enforcedReturnValue() {
  3875. var result = instanceInjector.invoke(factory, this);
  3876. if (isUndefined(result)) {
  3877. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3878. }
  3879. return result;
  3880. };
  3881. }
  3882. function factory(name, factoryFn, enforce) {
  3883. return provider(name, {
  3884. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3885. });
  3886. }
  3887. function service(name, constructor) {
  3888. return factory(name, ['$injector', function($injector) {
  3889. return $injector.instantiate(constructor);
  3890. }]);
  3891. }
  3892. function value(name, val) { return factory(name, valueFn(val), false); }
  3893. function constant(name, value) {
  3894. assertNotHasOwnProperty(name, 'constant');
  3895. providerCache[name] = value;
  3896. instanceCache[name] = value;
  3897. }
  3898. function decorator(serviceName, decorFn) {
  3899. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3900. orig$get = origProvider.$get;
  3901. origProvider.$get = function() {
  3902. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3903. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3904. };
  3905. }
  3906. ////////////////////////////////////
  3907. // Module Loading
  3908. ////////////////////////////////////
  3909. function loadModules(modulesToLoad) {
  3910. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  3911. var runBlocks = [], moduleFn;
  3912. forEach(modulesToLoad, function(module) {
  3913. if (loadedModules.get(module)) return;
  3914. loadedModules.put(module, true);
  3915. function runInvokeQueue(queue) {
  3916. var i, ii;
  3917. for (i = 0, ii = queue.length; i < ii; i++) {
  3918. var invokeArgs = queue[i],
  3919. provider = providerInjector.get(invokeArgs[0]);
  3920. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3921. }
  3922. }
  3923. try {
  3924. if (isString(module)) {
  3925. moduleFn = angularModule(module);
  3926. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3927. runInvokeQueue(moduleFn._invokeQueue);
  3928. runInvokeQueue(moduleFn._configBlocks);
  3929. } else if (isFunction(module)) {
  3930. runBlocks.push(providerInjector.invoke(module));
  3931. } else if (isArray(module)) {
  3932. runBlocks.push(providerInjector.invoke(module));
  3933. } else {
  3934. assertArgFn(module, 'module');
  3935. }
  3936. } catch (e) {
  3937. if (isArray(module)) {
  3938. module = module[module.length - 1];
  3939. }
  3940. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3941. // Safari & FF's stack traces don't contain error.message content
  3942. // unlike those of Chrome and IE
  3943. // So if stack doesn't contain message, we create a new string that contains both.
  3944. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3945. /* jshint -W022 */
  3946. e = e.message + '\n' + e.stack;
  3947. }
  3948. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3949. module, e.stack || e.message || e);
  3950. }
  3951. });
  3952. return runBlocks;
  3953. }
  3954. ////////////////////////////////////
  3955. // internal Injector
  3956. ////////////////////////////////////
  3957. function createInternalInjector(cache, factory) {
  3958. function getService(serviceName, caller) {
  3959. if (cache.hasOwnProperty(serviceName)) {
  3960. if (cache[serviceName] === INSTANTIATING) {
  3961. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3962. serviceName + ' <- ' + path.join(' <- '));
  3963. }
  3964. return cache[serviceName];
  3965. } else {
  3966. try {
  3967. path.unshift(serviceName);
  3968. cache[serviceName] = INSTANTIATING;
  3969. return cache[serviceName] = factory(serviceName, caller);
  3970. } catch (err) {
  3971. if (cache[serviceName] === INSTANTIATING) {
  3972. delete cache[serviceName];
  3973. }
  3974. throw err;
  3975. } finally {
  3976. path.shift();
  3977. }
  3978. }
  3979. }
  3980. function invoke(fn, self, locals, serviceName) {
  3981. if (typeof locals === 'string') {
  3982. serviceName = locals;
  3983. locals = null;
  3984. }
  3985. var args = [],
  3986. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  3987. length, i,
  3988. key;
  3989. for (i = 0, length = $inject.length; i < length; i++) {
  3990. key = $inject[i];
  3991. if (typeof key !== 'string') {
  3992. throw $injectorMinErr('itkn',
  3993. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3994. }
  3995. args.push(
  3996. locals && locals.hasOwnProperty(key)
  3997. ? locals[key]
  3998. : getService(key, serviceName)
  3999. );
  4000. }
  4001. if (isArray(fn)) {
  4002. fn = fn[length];
  4003. }
  4004. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4005. // #5388
  4006. return fn.apply(self, args);
  4007. }
  4008. function instantiate(Type, locals, serviceName) {
  4009. // Check if Type is annotated and use just the given function at n-1 as parameter
  4010. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4011. // Object creation: http://jsperf.com/create-constructor/2
  4012. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  4013. var returnedValue = invoke(Type, instance, locals, serviceName);
  4014. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  4015. }
  4016. return {
  4017. invoke: invoke,
  4018. instantiate: instantiate,
  4019. get: getService,
  4020. annotate: createInjector.$$annotate,
  4021. has: function(name) {
  4022. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4023. }
  4024. };
  4025. }
  4026. }
  4027. createInjector.$$annotate = annotate;
  4028. /**
  4029. * @ngdoc provider
  4030. * @name $anchorScrollProvider
  4031. *
  4032. * @description
  4033. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4034. * {@link ng.$location#hash $location.hash()} changes.
  4035. */
  4036. function $AnchorScrollProvider() {
  4037. var autoScrollingEnabled = true;
  4038. /**
  4039. * @ngdoc method
  4040. * @name $anchorScrollProvider#disableAutoScrolling
  4041. *
  4042. * @description
  4043. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4044. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4045. * Use this method to disable automatic scrolling.
  4046. *
  4047. * If automatic scrolling is disabled, one must explicitly call
  4048. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4049. * current hash.
  4050. */
  4051. this.disableAutoScrolling = function() {
  4052. autoScrollingEnabled = false;
  4053. };
  4054. /**
  4055. * @ngdoc service
  4056. * @name $anchorScroll
  4057. * @kind function
  4058. * @requires $window
  4059. * @requires $location
  4060. * @requires $rootScope
  4061. *
  4062. * @description
  4063. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4064. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4065. * in the
  4066. * [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  4067. *
  4068. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4069. * match any anchor whenever it changes. This can be disabled by calling
  4070. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4071. *
  4072. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4073. * vertical scroll-offset (either fixed or dynamic).
  4074. *
  4075. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4076. * {@link ng.$location#hash $location.hash()} will be used.
  4077. *
  4078. * @property {(number|function|jqLite)} yOffset
  4079. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4080. * positioned elements at the top of the page, such as navbars, headers etc.
  4081. *
  4082. * `yOffset` can be specified in various ways:
  4083. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4084. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4085. * a number representing the offset (in pixels).<br /><br />
  4086. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4087. * the top of the page to the element's bottom will be used as offset.<br />
  4088. * **Note**: The element will be taken into account only as long as its `position` is set to
  4089. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4090. * their height and/or positioning according to the viewport's size.
  4091. *
  4092. * <br />
  4093. * <div class="alert alert-warning">
  4094. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4095. * not some child element.
  4096. * </div>
  4097. *
  4098. * @example
  4099. <example module="anchorScrollExample">
  4100. <file name="index.html">
  4101. <div id="scrollArea" ng-controller="ScrollController">
  4102. <a ng-click="gotoBottom()">Go to bottom</a>
  4103. <a id="bottom"></a> You're at the bottom!
  4104. </div>
  4105. </file>
  4106. <file name="script.js">
  4107. angular.module('anchorScrollExample', [])
  4108. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4109. function ($scope, $location, $anchorScroll) {
  4110. $scope.gotoBottom = function() {
  4111. // set the location.hash to the id of
  4112. // the element you wish to scroll to.
  4113. $location.hash('bottom');
  4114. // call $anchorScroll()
  4115. $anchorScroll();
  4116. };
  4117. }]);
  4118. </file>
  4119. <file name="style.css">
  4120. #scrollArea {
  4121. height: 280px;
  4122. overflow: auto;
  4123. }
  4124. #bottom {
  4125. display: block;
  4126. margin-top: 2000px;
  4127. }
  4128. </file>
  4129. </example>
  4130. *
  4131. * <hr />
  4132. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4133. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4134. *
  4135. * @example
  4136. <example module="anchorScrollOffsetExample">
  4137. <file name="index.html">
  4138. <div class="fixed-header" ng-controller="headerCtrl">
  4139. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4140. Go to anchor {{x}}
  4141. </a>
  4142. </div>
  4143. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4144. Anchor {{x}} of 5
  4145. </div>
  4146. </file>
  4147. <file name="script.js">
  4148. angular.module('anchorScrollOffsetExample', [])
  4149. .run(['$anchorScroll', function($anchorScroll) {
  4150. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4151. }])
  4152. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4153. function ($anchorScroll, $location, $scope) {
  4154. $scope.gotoAnchor = function(x) {
  4155. var newHash = 'anchor' + x;
  4156. if ($location.hash() !== newHash) {
  4157. // set the $location.hash to `newHash` and
  4158. // $anchorScroll will automatically scroll to it
  4159. $location.hash('anchor' + x);
  4160. } else {
  4161. // call $anchorScroll() explicitly,
  4162. // since $location.hash hasn't changed
  4163. $anchorScroll();
  4164. }
  4165. };
  4166. }
  4167. ]);
  4168. </file>
  4169. <file name="style.css">
  4170. body {
  4171. padding-top: 50px;
  4172. }
  4173. .anchor {
  4174. border: 2px dashed DarkOrchid;
  4175. padding: 10px 10px 200px 10px;
  4176. }
  4177. .fixed-header {
  4178. background-color: rgba(0, 0, 0, 0.2);
  4179. height: 50px;
  4180. position: fixed;
  4181. top: 0; left: 0; right: 0;
  4182. }
  4183. .fixed-header > a {
  4184. display: inline-block;
  4185. margin: 5px 15px;
  4186. }
  4187. </file>
  4188. </example>
  4189. */
  4190. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4191. var document = $window.document;
  4192. // Helper function to get first anchor from a NodeList
  4193. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4194. // and working in all supported browsers.)
  4195. function getFirstAnchor(list) {
  4196. var result = null;
  4197. Array.prototype.some.call(list, function(element) {
  4198. if (nodeName_(element) === 'a') {
  4199. result = element;
  4200. return true;
  4201. }
  4202. });
  4203. return result;
  4204. }
  4205. function getYOffset() {
  4206. var offset = scroll.yOffset;
  4207. if (isFunction(offset)) {
  4208. offset = offset();
  4209. } else if (isElement(offset)) {
  4210. var elem = offset[0];
  4211. var style = $window.getComputedStyle(elem);
  4212. if (style.position !== 'fixed') {
  4213. offset = 0;
  4214. } else {
  4215. offset = elem.getBoundingClientRect().bottom;
  4216. }
  4217. } else if (!isNumber(offset)) {
  4218. offset = 0;
  4219. }
  4220. return offset;
  4221. }
  4222. function scrollTo(elem) {
  4223. if (elem) {
  4224. elem.scrollIntoView();
  4225. var offset = getYOffset();
  4226. if (offset) {
  4227. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4228. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4229. // top of the viewport.
  4230. //
  4231. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4232. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4233. // way down the page.
  4234. //
  4235. // This is often the case for elements near the bottom of the page.
  4236. //
  4237. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4238. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4239. // desired position.
  4240. var elemTop = elem.getBoundingClientRect().top;
  4241. $window.scrollBy(0, elemTop - offset);
  4242. }
  4243. } else {
  4244. $window.scrollTo(0, 0);
  4245. }
  4246. }
  4247. function scroll(hash) {
  4248. hash = isString(hash) ? hash : $location.hash();
  4249. var elm;
  4250. // empty hash, scroll to the top of the page
  4251. if (!hash) scrollTo(null);
  4252. // element with given id
  4253. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4254. // first anchor with given name :-D
  4255. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4256. // no element and hash == 'top', scroll to the top of the page
  4257. else if (hash === 'top') scrollTo(null);
  4258. }
  4259. // does not scroll when user clicks on anchor link that is currently on
  4260. // (no url change, no $location.hash() change), browser native does scroll
  4261. if (autoScrollingEnabled) {
  4262. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4263. function autoScrollWatchAction(newVal, oldVal) {
  4264. // skip the initial scroll if $location.hash is empty
  4265. if (newVal === oldVal && newVal === '') return;
  4266. jqLiteDocumentLoaded(function() {
  4267. $rootScope.$evalAsync(scroll);
  4268. });
  4269. });
  4270. }
  4271. return scroll;
  4272. }];
  4273. }
  4274. var $animateMinErr = minErr('$animate');
  4275. var ELEMENT_NODE = 1;
  4276. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4277. function mergeClasses(a,b) {
  4278. if (!a && !b) return '';
  4279. if (!a) return b;
  4280. if (!b) return a;
  4281. if (isArray(a)) a = a.join(' ');
  4282. if (isArray(b)) b = b.join(' ');
  4283. return a + ' ' + b;
  4284. }
  4285. function extractElementNode(element) {
  4286. for (var i = 0; i < element.length; i++) {
  4287. var elm = element[i];
  4288. if (elm.nodeType === ELEMENT_NODE) {
  4289. return elm;
  4290. }
  4291. }
  4292. }
  4293. function splitClasses(classes) {
  4294. if (isString(classes)) {
  4295. classes = classes.split(' ');
  4296. }
  4297. // Use createMap() to prevent class assumptions involving property names in
  4298. // Object.prototype
  4299. var obj = createMap();
  4300. forEach(classes, function(klass) {
  4301. // sometimes the split leaves empty string values
  4302. // incase extra spaces were applied to the options
  4303. if (klass.length) {
  4304. obj[klass] = true;
  4305. }
  4306. });
  4307. return obj;
  4308. }
  4309. // if any other type of options value besides an Object value is
  4310. // passed into the $animate.method() animation then this helper code
  4311. // will be run which will ignore it. While this patch is not the
  4312. // greatest solution to this, a lot of existing plugins depend on
  4313. // $animate to either call the callback (< 1.2) or return a promise
  4314. // that can be changed. This helper function ensures that the options
  4315. // are wiped clean incase a callback function is provided.
  4316. function prepareAnimateOptions(options) {
  4317. return isObject(options)
  4318. ? options
  4319. : {};
  4320. }
  4321. var $$CoreAnimateRunnerProvider = function() {
  4322. this.$get = ['$q', '$$rAF', function($q, $$rAF) {
  4323. function AnimateRunner() {}
  4324. AnimateRunner.all = noop;
  4325. AnimateRunner.chain = noop;
  4326. AnimateRunner.prototype = {
  4327. end: noop,
  4328. cancel: noop,
  4329. resume: noop,
  4330. pause: noop,
  4331. complete: noop,
  4332. then: function(pass, fail) {
  4333. return $q(function(resolve) {
  4334. $$rAF(function() {
  4335. resolve();
  4336. });
  4337. }).then(pass, fail);
  4338. }
  4339. };
  4340. return AnimateRunner;
  4341. }];
  4342. };
  4343. // this is prefixed with Core since it conflicts with
  4344. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4345. var $$CoreAnimateQueueProvider = function() {
  4346. var postDigestQueue = new HashMap();
  4347. var postDigestElements = [];
  4348. this.$get = ['$$AnimateRunner', '$rootScope',
  4349. function($$AnimateRunner, $rootScope) {
  4350. return {
  4351. enabled: noop,
  4352. on: noop,
  4353. off: noop,
  4354. pin: noop,
  4355. push: function(element, event, options, domOperation) {
  4356. domOperation && domOperation();
  4357. options = options || {};
  4358. options.from && element.css(options.from);
  4359. options.to && element.css(options.to);
  4360. if (options.addClass || options.removeClass) {
  4361. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4362. }
  4363. return new $$AnimateRunner(); // jshint ignore:line
  4364. }
  4365. };
  4366. function addRemoveClassesPostDigest(element, add, remove) {
  4367. var classVal, data = postDigestQueue.get(element);
  4368. if (!data) {
  4369. postDigestQueue.put(element, data = {});
  4370. postDigestElements.push(element);
  4371. }
  4372. var updateData = function(classes, value) {
  4373. var changed = false;
  4374. if (classes) {
  4375. classes = isString(classes) ? classes.split(' ') :
  4376. isArray(classes) ? classes : [];
  4377. forEach(classes, function(className) {
  4378. if (className) {
  4379. changed = true;
  4380. data[className] = value;
  4381. }
  4382. });
  4383. }
  4384. return changed;
  4385. };
  4386. var classesAdded = updateData(add, true);
  4387. var classesRemoved = updateData(remove, false);
  4388. if ((!classesAdded && !classesRemoved) || postDigestElements.length > 1) return;
  4389. $rootScope.$$postDigest(function() {
  4390. forEach(postDigestElements, function(element) {
  4391. var data = postDigestQueue.get(element);
  4392. if (data) {
  4393. var existing = splitClasses(element.attr('class'));
  4394. var toAdd = '';
  4395. var toRemove = '';
  4396. forEach(data, function(status, className) {
  4397. var hasClass = !!existing[className];
  4398. if (status !== hasClass) {
  4399. if (status) {
  4400. toAdd += (toAdd.length ? ' ' : '') + className;
  4401. } else {
  4402. toRemove += (toRemove.length ? ' ' : '') + className;
  4403. }
  4404. }
  4405. });
  4406. forEach(element, function(elm) {
  4407. toAdd && jqLiteAddClass(elm, toAdd);
  4408. toRemove && jqLiteRemoveClass(elm, toRemove);
  4409. });
  4410. postDigestQueue.remove(element);
  4411. }
  4412. });
  4413. postDigestElements.length = 0;
  4414. });
  4415. }
  4416. }];
  4417. };
  4418. /**
  4419. * @ngdoc provider
  4420. * @name $animateProvider
  4421. *
  4422. * @description
  4423. * Default implementation of $animate that doesn't perform any animations, instead just
  4424. * synchronously performs DOM updates and resolves the returned runner promise.
  4425. *
  4426. * In order to enable animations the `ngAnimate` module has to be loaded.
  4427. *
  4428. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4429. */
  4430. var $AnimateProvider = ['$provide', function($provide) {
  4431. var provider = this;
  4432. this.$$registeredAnimations = Object.create(null);
  4433. /**
  4434. * @ngdoc method
  4435. * @name $animateProvider#register
  4436. *
  4437. * @description
  4438. * Registers a new injectable animation factory function. The factory function produces the
  4439. * animation object which contains callback functions for each event that is expected to be
  4440. * animated.
  4441. *
  4442. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4443. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4444. * on the type of animation additional arguments will be injected into the animation function. The
  4445. * list below explains the function signatures for the different animation methods:
  4446. *
  4447. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4448. * - addClass: function(element, addedClasses, doneFunction, options)
  4449. * - removeClass: function(element, removedClasses, doneFunction, options)
  4450. * - enter, leave, move: function(element, doneFunction, options)
  4451. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4452. *
  4453. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4454. *
  4455. * ```js
  4456. * return {
  4457. * //enter, leave, move signature
  4458. * eventFn : function(element, done, options) {
  4459. * //code to run the animation
  4460. * //once complete, then run done()
  4461. * return function endFunction(wasCancelled) {
  4462. * //code to cancel the animation
  4463. * }
  4464. * }
  4465. * }
  4466. * ```
  4467. *
  4468. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4469. * @param {Function} factory The factory function that will be executed to return the animation
  4470. * object.
  4471. */
  4472. this.register = function(name, factory) {
  4473. if (name && name.charAt(0) !== '.') {
  4474. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4475. }
  4476. var key = name + '-animation';
  4477. provider.$$registeredAnimations[name.substr(1)] = key;
  4478. $provide.factory(key, factory);
  4479. };
  4480. /**
  4481. * @ngdoc method
  4482. * @name $animateProvider#classNameFilter
  4483. *
  4484. * @description
  4485. * Sets and/or returns the CSS class regular expression that is checked when performing
  4486. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4487. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4488. * When setting the `classNameFilter` value, animations will only be performed on elements
  4489. * that successfully match the filter expression. This in turn can boost performance
  4490. * for low-powered devices as well as applications containing a lot of structural operations.
  4491. * @param {RegExp=} expression The className expression which will be checked against all animations
  4492. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4493. */
  4494. this.classNameFilter = function(expression) {
  4495. if (arguments.length === 1) {
  4496. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4497. if (this.$$classNameFilter) {
  4498. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4499. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4500. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4501. }
  4502. }
  4503. }
  4504. return this.$$classNameFilter;
  4505. };
  4506. this.$get = ['$$animateQueue', function($$animateQueue) {
  4507. function domInsert(element, parentElement, afterElement) {
  4508. // if for some reason the previous element was removed
  4509. // from the dom sometime before this code runs then let's
  4510. // just stick to using the parent element as the anchor
  4511. if (afterElement) {
  4512. var afterNode = extractElementNode(afterElement);
  4513. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4514. afterElement = null;
  4515. }
  4516. }
  4517. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4518. }
  4519. /**
  4520. * @ngdoc service
  4521. * @name $animate
  4522. * @description The $animate service exposes a series of DOM utility methods that provide support
  4523. * for animation hooks. The default behavior is the application of DOM operations, however,
  4524. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4525. * to ensure that animation runs with the triggered DOM operation.
  4526. *
  4527. * By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't
  4528. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4529. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4530. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4531. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4532. *
  4533. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4534. *
  4535. * To learn more about enabling animation support, click here to visit the
  4536. * {@link ngAnimate ngAnimate module page}.
  4537. */
  4538. return {
  4539. // we don't call it directly since non-existant arguments may
  4540. // be interpreted as null within the sub enabled function
  4541. /**
  4542. *
  4543. * @ngdoc method
  4544. * @name $animate#on
  4545. * @kind function
  4546. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4547. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4548. * is fired with the following params:
  4549. *
  4550. * ```js
  4551. * $animate.on('enter', container,
  4552. * function callback(element, phase) {
  4553. * // cool we detected an enter animation within the container
  4554. * }
  4555. * );
  4556. * ```
  4557. *
  4558. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4559. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4560. * as well as among its children
  4561. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4562. *
  4563. * The arguments present in the callback function are:
  4564. * * `element` - The captured DOM element that the animation was fired on.
  4565. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4566. */
  4567. on: $$animateQueue.on,
  4568. /**
  4569. *
  4570. * @ngdoc method
  4571. * @name $animate#off
  4572. * @kind function
  4573. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4574. * can be used in three different ways depending on the arguments:
  4575. *
  4576. * ```js
  4577. * // remove all the animation event listeners listening for `enter`
  4578. * $animate.off('enter');
  4579. *
  4580. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4581. * $animate.off('enter', container);
  4582. *
  4583. * // remove the event listener function provided by `listenerFn` that is set
  4584. * // to listen for `enter` on the given `element` as well as its children
  4585. * $animate.off('enter', container, callback);
  4586. * ```
  4587. *
  4588. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  4589. * @param {DOMElement=} container the container element the event listener was placed on
  4590. * @param {Function=} callback the callback function that was registered as the listener
  4591. */
  4592. off: $$animateQueue.off,
  4593. /**
  4594. * @ngdoc method
  4595. * @name $animate#pin
  4596. * @kind function
  4597. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4598. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4599. * element despite being outside the realm of the application or within another application. Say for example if the application
  4600. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4601. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4602. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4603. *
  4604. * Note that this feature is only active when the `ngAnimate` module is used.
  4605. *
  4606. * @param {DOMElement} element the external element that will be pinned
  4607. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4608. */
  4609. pin: $$animateQueue.pin,
  4610. /**
  4611. *
  4612. * @ngdoc method
  4613. * @name $animate#enabled
  4614. * @kind function
  4615. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4616. * function can be called in four ways:
  4617. *
  4618. * ```js
  4619. * // returns true or false
  4620. * $animate.enabled();
  4621. *
  4622. * // changes the enabled state for all animations
  4623. * $animate.enabled(false);
  4624. * $animate.enabled(true);
  4625. *
  4626. * // returns true or false if animations are enabled for an element
  4627. * $animate.enabled(element);
  4628. *
  4629. * // changes the enabled state for an element and its children
  4630. * $animate.enabled(element, true);
  4631. * $animate.enabled(element, false);
  4632. * ```
  4633. *
  4634. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4635. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4636. *
  4637. * @return {boolean} whether or not animations are enabled
  4638. */
  4639. enabled: $$animateQueue.enabled,
  4640. /**
  4641. * @ngdoc method
  4642. * @name $animate#cancel
  4643. * @kind function
  4644. * @description Cancels the provided animation.
  4645. *
  4646. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4647. */
  4648. cancel: function(runner) {
  4649. runner.end && runner.end();
  4650. },
  4651. /**
  4652. *
  4653. * @ngdoc method
  4654. * @name $animate#enter
  4655. * @kind function
  4656. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4657. * as the first child within the `parent` element and then triggers an animation.
  4658. * A promise is returned that will be resolved during the next digest once the animation
  4659. * has completed.
  4660. *
  4661. * @param {DOMElement} element the element which will be inserted into the DOM
  4662. * @param {DOMElement} parent the parent element which will append the element as
  4663. * a child (so long as the after element is not present)
  4664. * @param {DOMElement=} after the sibling element after which the element will be appended
  4665. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4666. *
  4667. * @return {Promise} the animation callback promise
  4668. */
  4669. enter: function(element, parent, after, options) {
  4670. parent = parent && jqLite(parent);
  4671. after = after && jqLite(after);
  4672. parent = parent || after.parent();
  4673. domInsert(element, parent, after);
  4674. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4675. },
  4676. /**
  4677. *
  4678. * @ngdoc method
  4679. * @name $animate#move
  4680. * @kind function
  4681. * @description Inserts (moves) the element into its new position in the DOM either after
  4682. * the `after` element (if provided) or as the first child within the `parent` element
  4683. * and then triggers an animation. A promise is returned that will be resolved
  4684. * during the next digest once the animation has completed.
  4685. *
  4686. * @param {DOMElement} element the element which will be moved into the new DOM position
  4687. * @param {DOMElement} parent the parent element which will append the element as
  4688. * a child (so long as the after element is not present)
  4689. * @param {DOMElement=} after the sibling element after which the element will be appended
  4690. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4691. *
  4692. * @return {Promise} the animation callback promise
  4693. */
  4694. move: function(element, parent, after, options) {
  4695. parent = parent && jqLite(parent);
  4696. after = after && jqLite(after);
  4697. parent = parent || after.parent();
  4698. domInsert(element, parent, after);
  4699. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4700. },
  4701. /**
  4702. * @ngdoc method
  4703. * @name $animate#leave
  4704. * @kind function
  4705. * @description Triggers an animation and then removes the element from the DOM.
  4706. * When the function is called a promise is returned that will be resolved during the next
  4707. * digest once the animation has completed.
  4708. *
  4709. * @param {DOMElement} element the element which will be removed from the DOM
  4710. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4711. *
  4712. * @return {Promise} the animation callback promise
  4713. */
  4714. leave: function(element, options) {
  4715. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4716. element.remove();
  4717. });
  4718. },
  4719. /**
  4720. * @ngdoc method
  4721. * @name $animate#addClass
  4722. * @kind function
  4723. *
  4724. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4725. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4726. * animation if element already contains the CSS class or if the class is removed at a later step.
  4727. * Note that class-based animations are treated differently compared to structural animations
  4728. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4729. * depending if CSS or JavaScript animations are used.
  4730. *
  4731. * @param {DOMElement} element the element which the CSS classes will be applied to
  4732. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4733. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4734. *
  4735. * @return {Promise} the animation callback promise
  4736. */
  4737. addClass: function(element, className, options) {
  4738. options = prepareAnimateOptions(options);
  4739. options.addClass = mergeClasses(options.addclass, className);
  4740. return $$animateQueue.push(element, 'addClass', options);
  4741. },
  4742. /**
  4743. * @ngdoc method
  4744. * @name $animate#removeClass
  4745. * @kind function
  4746. *
  4747. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4748. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4749. * animation if element does not contain the CSS class or if the class is added at a later step.
  4750. * Note that class-based animations are treated differently compared to structural animations
  4751. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4752. * depending if CSS or JavaScript animations are used.
  4753. *
  4754. * @param {DOMElement} element the element which the CSS classes will be applied to
  4755. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4756. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4757. *
  4758. * @return {Promise} the animation callback promise
  4759. */
  4760. removeClass: function(element, className, options) {
  4761. options = prepareAnimateOptions(options);
  4762. options.removeClass = mergeClasses(options.removeClass, className);
  4763. return $$animateQueue.push(element, 'removeClass', options);
  4764. },
  4765. /**
  4766. * @ngdoc method
  4767. * @name $animate#setClass
  4768. * @kind function
  4769. *
  4770. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  4771. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  4772. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  4773. * passed. Note that class-based animations are treated differently compared to structural animations
  4774. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4775. * depending if CSS or JavaScript animations are used.
  4776. *
  4777. * @param {DOMElement} element the element which the CSS classes will be applied to
  4778. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  4779. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4780. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4781. *
  4782. * @return {Promise} the animation callback promise
  4783. */
  4784. setClass: function(element, add, remove, options) {
  4785. options = prepareAnimateOptions(options);
  4786. options.addClass = mergeClasses(options.addClass, add);
  4787. options.removeClass = mergeClasses(options.removeClass, remove);
  4788. return $$animateQueue.push(element, 'setClass', options);
  4789. },
  4790. /**
  4791. * @ngdoc method
  4792. * @name $animate#animate
  4793. * @kind function
  4794. *
  4795. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  4796. * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
  4797. * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
  4798. * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
  4799. * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
  4800. *
  4801. * @param {DOMElement} element the element which the CSS styles will be applied to
  4802. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  4803. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  4804. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  4805. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  4806. * (Note that if no animation is detected then this value will not be appplied to the element.)
  4807. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4808. *
  4809. * @return {Promise} the animation callback promise
  4810. */
  4811. animate: function(element, from, to, className, options) {
  4812. options = prepareAnimateOptions(options);
  4813. options.from = options.from ? extend(options.from, from) : from;
  4814. options.to = options.to ? extend(options.to, to) : to;
  4815. className = className || 'ng-inline-animate';
  4816. options.tempClasses = mergeClasses(options.tempClasses, className);
  4817. return $$animateQueue.push(element, 'animate', options);
  4818. }
  4819. };
  4820. }];
  4821. }];
  4822. /**
  4823. * @ngdoc service
  4824. * @name $animateCss
  4825. * @kind object
  4826. *
  4827. * @description
  4828. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  4829. * then the `$animateCss` service will actually perform animations.
  4830. *
  4831. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  4832. */
  4833. var $CoreAnimateCssProvider = function() {
  4834. this.$get = ['$$rAF', '$q', function($$rAF, $q) {
  4835. var RAFPromise = function() {};
  4836. RAFPromise.prototype = {
  4837. done: function(cancel) {
  4838. this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();
  4839. },
  4840. end: function() {
  4841. this.done();
  4842. },
  4843. cancel: function() {
  4844. this.done(true);
  4845. },
  4846. getPromise: function() {
  4847. if (!this.defer) {
  4848. this.defer = $q.defer();
  4849. }
  4850. return this.defer.promise;
  4851. },
  4852. then: function(f1,f2) {
  4853. return this.getPromise().then(f1,f2);
  4854. },
  4855. 'catch': function(f1) {
  4856. return this.getPromise().catch(f1);
  4857. },
  4858. 'finally': function(f1) {
  4859. return this.getPromise().finally(f1);
  4860. }
  4861. };
  4862. return function(element, options) {
  4863. if (options.from) {
  4864. element.css(options.from);
  4865. options.from = null;
  4866. }
  4867. var closed, runner = new RAFPromise();
  4868. return {
  4869. start: run,
  4870. end: run
  4871. };
  4872. function run() {
  4873. $$rAF(function() {
  4874. close();
  4875. if (!closed) {
  4876. runner.done();
  4877. }
  4878. closed = true;
  4879. });
  4880. return runner;
  4881. }
  4882. function close() {
  4883. if (options.addClass) {
  4884. element.addClass(options.addClass);
  4885. options.addClass = null;
  4886. }
  4887. if (options.removeClass) {
  4888. element.removeClass(options.removeClass);
  4889. options.removeClass = null;
  4890. }
  4891. if (options.to) {
  4892. element.css(options.to);
  4893. options.to = null;
  4894. }
  4895. }
  4896. };
  4897. }];
  4898. };
  4899. /* global stripHash: true */
  4900. /**
  4901. * ! This is a private undocumented service !
  4902. *
  4903. * @name $browser
  4904. * @requires $log
  4905. * @description
  4906. * This object has two goals:
  4907. *
  4908. * - hide all the global state in the browser caused by the window object
  4909. * - abstract away all the browser specific features and inconsistencies
  4910. *
  4911. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4912. * service, which can be used for convenient testing of the application without the interaction with
  4913. * the real browser apis.
  4914. */
  4915. /**
  4916. * @param {object} window The global window object.
  4917. * @param {object} document jQuery wrapped document.
  4918. * @param {object} $log window.console or an object with the same interface.
  4919. * @param {object} $sniffer $sniffer service
  4920. */
  4921. function Browser(window, document, $log, $sniffer) {
  4922. var self = this,
  4923. rawDocument = document[0],
  4924. location = window.location,
  4925. history = window.history,
  4926. setTimeout = window.setTimeout,
  4927. clearTimeout = window.clearTimeout,
  4928. pendingDeferIds = {};
  4929. self.isMock = false;
  4930. var outstandingRequestCount = 0;
  4931. var outstandingRequestCallbacks = [];
  4932. // TODO(vojta): remove this temporary api
  4933. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4934. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4935. /**
  4936. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4937. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4938. */
  4939. function completeOutstandingRequest(fn) {
  4940. try {
  4941. fn.apply(null, sliceArgs(arguments, 1));
  4942. } finally {
  4943. outstandingRequestCount--;
  4944. if (outstandingRequestCount === 0) {
  4945. while (outstandingRequestCallbacks.length) {
  4946. try {
  4947. outstandingRequestCallbacks.pop()();
  4948. } catch (e) {
  4949. $log.error(e);
  4950. }
  4951. }
  4952. }
  4953. }
  4954. }
  4955. function getHash(url) {
  4956. var index = url.indexOf('#');
  4957. return index === -1 ? '' : url.substr(index);
  4958. }
  4959. /**
  4960. * @private
  4961. * Note: this method is used only by scenario runner
  4962. * TODO(vojta): prefix this method with $$ ?
  4963. * @param {function()} callback Function that will be called when no outstanding request
  4964. */
  4965. self.notifyWhenNoOutstandingRequests = function(callback) {
  4966. if (outstandingRequestCount === 0) {
  4967. callback();
  4968. } else {
  4969. outstandingRequestCallbacks.push(callback);
  4970. }
  4971. };
  4972. //////////////////////////////////////////////////////////////
  4973. // URL API
  4974. //////////////////////////////////////////////////////////////
  4975. var cachedState, lastHistoryState,
  4976. lastBrowserUrl = location.href,
  4977. baseElement = document.find('base'),
  4978. reloadLocation = null;
  4979. cacheState();
  4980. lastHistoryState = cachedState;
  4981. /**
  4982. * @name $browser#url
  4983. *
  4984. * @description
  4985. * GETTER:
  4986. * Without any argument, this method just returns current value of location.href.
  4987. *
  4988. * SETTER:
  4989. * With at least one argument, this method sets url to new value.
  4990. * If html5 history api supported, pushState/replaceState is used, otherwise
  4991. * location.href/location.replace is used.
  4992. * Returns its own instance to allow chaining
  4993. *
  4994. * NOTE: this api is intended for use only by the $location service. Please use the
  4995. * {@link ng.$location $location service} to change url.
  4996. *
  4997. * @param {string} url New url (when used as setter)
  4998. * @param {boolean=} replace Should new url replace current history record?
  4999. * @param {object=} state object to use with pushState/replaceState
  5000. */
  5001. self.url = function(url, replace, state) {
  5002. // In modern browsers `history.state` is `null` by default; treating it separately
  5003. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5004. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5005. if (isUndefined(state)) {
  5006. state = null;
  5007. }
  5008. // Android Browser BFCache causes location, history reference to become stale.
  5009. if (location !== window.location) location = window.location;
  5010. if (history !== window.history) history = window.history;
  5011. // setter
  5012. if (url) {
  5013. var sameState = lastHistoryState === state;
  5014. // Don't change anything if previous and current URLs and states match. This also prevents
  5015. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5016. // See https://github.com/angular/angular.js/commit/ffb2701
  5017. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5018. return self;
  5019. }
  5020. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5021. lastBrowserUrl = url;
  5022. lastHistoryState = state;
  5023. // Don't use history API if only the hash changed
  5024. // due to a bug in IE10/IE11 which leads
  5025. // to not firing a `hashchange` nor `popstate` event
  5026. // in some cases (see #9143).
  5027. if ($sniffer.history && (!sameBase || !sameState)) {
  5028. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5029. cacheState();
  5030. // Do the assignment again so that those two variables are referentially identical.
  5031. lastHistoryState = cachedState;
  5032. } else {
  5033. if (!sameBase || reloadLocation) {
  5034. reloadLocation = url;
  5035. }
  5036. if (replace) {
  5037. location.replace(url);
  5038. } else if (!sameBase) {
  5039. location.href = url;
  5040. } else {
  5041. location.hash = getHash(url);
  5042. }
  5043. }
  5044. return self;
  5045. // getter
  5046. } else {
  5047. // - reloadLocation is needed as browsers don't allow to read out
  5048. // the new location.href if a reload happened.
  5049. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5050. return reloadLocation || location.href.replace(/%27/g,"'");
  5051. }
  5052. };
  5053. /**
  5054. * @name $browser#state
  5055. *
  5056. * @description
  5057. * This method is a getter.
  5058. *
  5059. * Return history.state or null if history.state is undefined.
  5060. *
  5061. * @returns {object} state
  5062. */
  5063. self.state = function() {
  5064. return cachedState;
  5065. };
  5066. var urlChangeListeners = [],
  5067. urlChangeInit = false;
  5068. function cacheStateAndFireUrlChange() {
  5069. cacheState();
  5070. fireUrlChange();
  5071. }
  5072. function getCurrentState() {
  5073. try {
  5074. return history.state;
  5075. } catch (e) {
  5076. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5077. }
  5078. }
  5079. // This variable should be used *only* inside the cacheState function.
  5080. var lastCachedState = null;
  5081. function cacheState() {
  5082. // This should be the only place in $browser where `history.state` is read.
  5083. cachedState = getCurrentState();
  5084. cachedState = isUndefined(cachedState) ? null : cachedState;
  5085. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5086. if (equals(cachedState, lastCachedState)) {
  5087. cachedState = lastCachedState;
  5088. }
  5089. lastCachedState = cachedState;
  5090. }
  5091. function fireUrlChange() {
  5092. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5093. return;
  5094. }
  5095. lastBrowserUrl = self.url();
  5096. lastHistoryState = cachedState;
  5097. forEach(urlChangeListeners, function(listener) {
  5098. listener(self.url(), cachedState);
  5099. });
  5100. }
  5101. /**
  5102. * @name $browser#onUrlChange
  5103. *
  5104. * @description
  5105. * Register callback function that will be called, when url changes.
  5106. *
  5107. * It's only called when the url is changed from outside of angular:
  5108. * - user types different url into address bar
  5109. * - user clicks on history (forward/back) button
  5110. * - user clicks on a link
  5111. *
  5112. * It's not called when url is changed by $browser.url() method
  5113. *
  5114. * The listener gets called with new url as parameter.
  5115. *
  5116. * NOTE: this api is intended for use only by the $location service. Please use the
  5117. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5118. *
  5119. * @param {function(string)} listener Listener function to be called when url changes.
  5120. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5121. */
  5122. self.onUrlChange = function(callback) {
  5123. // TODO(vojta): refactor to use node's syntax for events
  5124. if (!urlChangeInit) {
  5125. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5126. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5127. // changed by push/replaceState
  5128. // html5 history api - popstate event
  5129. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5130. // hashchange event
  5131. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5132. urlChangeInit = true;
  5133. }
  5134. urlChangeListeners.push(callback);
  5135. return callback;
  5136. };
  5137. /**
  5138. * @private
  5139. * Remove popstate and hashchange handler from window.
  5140. *
  5141. * NOTE: this api is intended for use only by $rootScope.
  5142. */
  5143. self.$$applicationDestroyed = function() {
  5144. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5145. };
  5146. /**
  5147. * Checks whether the url has changed outside of Angular.
  5148. * Needs to be exported to be able to check for changes that have been done in sync,
  5149. * as hashchange/popstate events fire in async.
  5150. */
  5151. self.$$checkUrlChange = fireUrlChange;
  5152. //////////////////////////////////////////////////////////////
  5153. // Misc API
  5154. //////////////////////////////////////////////////////////////
  5155. /**
  5156. * @name $browser#baseHref
  5157. *
  5158. * @description
  5159. * Returns current <base href>
  5160. * (always relative - without domain)
  5161. *
  5162. * @returns {string} The current base href
  5163. */
  5164. self.baseHref = function() {
  5165. var href = baseElement.attr('href');
  5166. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5167. };
  5168. /**
  5169. * @name $browser#defer
  5170. * @param {function()} fn A function, who's execution should be deferred.
  5171. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5172. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5173. *
  5174. * @description
  5175. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5176. *
  5177. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5178. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5179. * via `$browser.defer.flush()`.
  5180. *
  5181. */
  5182. self.defer = function(fn, delay) {
  5183. var timeoutId;
  5184. outstandingRequestCount++;
  5185. timeoutId = setTimeout(function() {
  5186. delete pendingDeferIds[timeoutId];
  5187. completeOutstandingRequest(fn);
  5188. }, delay || 0);
  5189. pendingDeferIds[timeoutId] = true;
  5190. return timeoutId;
  5191. };
  5192. /**
  5193. * @name $browser#defer.cancel
  5194. *
  5195. * @description
  5196. * Cancels a deferred task identified with `deferId`.
  5197. *
  5198. * @param {*} deferId Token returned by the `$browser.defer` function.
  5199. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5200. * canceled.
  5201. */
  5202. self.defer.cancel = function(deferId) {
  5203. if (pendingDeferIds[deferId]) {
  5204. delete pendingDeferIds[deferId];
  5205. clearTimeout(deferId);
  5206. completeOutstandingRequest(noop);
  5207. return true;
  5208. }
  5209. return false;
  5210. };
  5211. }
  5212. function $BrowserProvider() {
  5213. this.$get = ['$window', '$log', '$sniffer', '$document',
  5214. function($window, $log, $sniffer, $document) {
  5215. return new Browser($window, $document, $log, $sniffer);
  5216. }];
  5217. }
  5218. /**
  5219. * @ngdoc service
  5220. * @name $cacheFactory
  5221. *
  5222. * @description
  5223. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5224. * them.
  5225. *
  5226. * ```js
  5227. *
  5228. * var cache = $cacheFactory('cacheId');
  5229. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5230. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5231. *
  5232. * cache.put("key", "value");
  5233. * cache.put("another key", "another value");
  5234. *
  5235. * // We've specified no options on creation
  5236. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5237. *
  5238. * ```
  5239. *
  5240. *
  5241. * @param {string} cacheId Name or id of the newly created cache.
  5242. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5243. *
  5244. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5245. *
  5246. * @returns {object} Newly created cache object with the following set of methods:
  5247. *
  5248. * - `{object}` `info()` — Returns id, size, and options of cache.
  5249. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5250. * it.
  5251. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5252. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5253. * - `{void}` `removeAll()` — Removes all cached values.
  5254. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5255. *
  5256. * @example
  5257. <example module="cacheExampleApp">
  5258. <file name="index.html">
  5259. <div ng-controller="CacheController">
  5260. <input ng-model="newCacheKey" placeholder="Key">
  5261. <input ng-model="newCacheValue" placeholder="Value">
  5262. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5263. <p ng-if="keys.length">Cached Values</p>
  5264. <div ng-repeat="key in keys">
  5265. <span ng-bind="key"></span>
  5266. <span>: </span>
  5267. <b ng-bind="cache.get(key)"></b>
  5268. </div>
  5269. <p>Cache Info</p>
  5270. <div ng-repeat="(key, value) in cache.info()">
  5271. <span ng-bind="key"></span>
  5272. <span>: </span>
  5273. <b ng-bind="value"></b>
  5274. </div>
  5275. </div>
  5276. </file>
  5277. <file name="script.js">
  5278. angular.module('cacheExampleApp', []).
  5279. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5280. $scope.keys = [];
  5281. $scope.cache = $cacheFactory('cacheId');
  5282. $scope.put = function(key, value) {
  5283. if ($scope.cache.get(key) === undefined) {
  5284. $scope.keys.push(key);
  5285. }
  5286. $scope.cache.put(key, value === undefined ? null : value);
  5287. };
  5288. }]);
  5289. </file>
  5290. <file name="style.css">
  5291. p {
  5292. margin: 10px 0 3px;
  5293. }
  5294. </file>
  5295. </example>
  5296. */
  5297. function $CacheFactoryProvider() {
  5298. this.$get = function() {
  5299. var caches = {};
  5300. function cacheFactory(cacheId, options) {
  5301. if (cacheId in caches) {
  5302. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5303. }
  5304. var size = 0,
  5305. stats = extend({}, options, {id: cacheId}),
  5306. data = {},
  5307. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5308. lruHash = {},
  5309. freshEnd = null,
  5310. staleEnd = null;
  5311. /**
  5312. * @ngdoc type
  5313. * @name $cacheFactory.Cache
  5314. *
  5315. * @description
  5316. * A cache object used to store and retrieve data, primarily used by
  5317. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5318. * templates and other data.
  5319. *
  5320. * ```js
  5321. * angular.module('superCache')
  5322. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5323. * return $cacheFactory('super-cache');
  5324. * }]);
  5325. * ```
  5326. *
  5327. * Example test:
  5328. *
  5329. * ```js
  5330. * it('should behave like a cache', inject(function(superCache) {
  5331. * superCache.put('key', 'value');
  5332. * superCache.put('another key', 'another value');
  5333. *
  5334. * expect(superCache.info()).toEqual({
  5335. * id: 'super-cache',
  5336. * size: 2
  5337. * });
  5338. *
  5339. * superCache.remove('another key');
  5340. * expect(superCache.get('another key')).toBeUndefined();
  5341. *
  5342. * superCache.removeAll();
  5343. * expect(superCache.info()).toEqual({
  5344. * id: 'super-cache',
  5345. * size: 0
  5346. * });
  5347. * }));
  5348. * ```
  5349. */
  5350. return caches[cacheId] = {
  5351. /**
  5352. * @ngdoc method
  5353. * @name $cacheFactory.Cache#put
  5354. * @kind function
  5355. *
  5356. * @description
  5357. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5358. * retrieved later, and incrementing the size of the cache if the key was not already
  5359. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5360. * entries from the set.
  5361. *
  5362. * It will not insert undefined values into the cache.
  5363. *
  5364. * @param {string} key the key under which the cached data is stored.
  5365. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5366. * will not be stored.
  5367. * @returns {*} the value stored.
  5368. */
  5369. put: function(key, value) {
  5370. if (isUndefined(value)) return;
  5371. if (capacity < Number.MAX_VALUE) {
  5372. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5373. refresh(lruEntry);
  5374. }
  5375. if (!(key in data)) size++;
  5376. data[key] = value;
  5377. if (size > capacity) {
  5378. this.remove(staleEnd.key);
  5379. }
  5380. return value;
  5381. },
  5382. /**
  5383. * @ngdoc method
  5384. * @name $cacheFactory.Cache#get
  5385. * @kind function
  5386. *
  5387. * @description
  5388. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5389. *
  5390. * @param {string} key the key of the data to be retrieved
  5391. * @returns {*} the value stored.
  5392. */
  5393. get: function(key) {
  5394. if (capacity < Number.MAX_VALUE) {
  5395. var lruEntry = lruHash[key];
  5396. if (!lruEntry) return;
  5397. refresh(lruEntry);
  5398. }
  5399. return data[key];
  5400. },
  5401. /**
  5402. * @ngdoc method
  5403. * @name $cacheFactory.Cache#remove
  5404. * @kind function
  5405. *
  5406. * @description
  5407. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5408. *
  5409. * @param {string} key the key of the entry to be removed
  5410. */
  5411. remove: function(key) {
  5412. if (capacity < Number.MAX_VALUE) {
  5413. var lruEntry = lruHash[key];
  5414. if (!lruEntry) return;
  5415. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5416. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5417. link(lruEntry.n,lruEntry.p);
  5418. delete lruHash[key];
  5419. }
  5420. delete data[key];
  5421. size--;
  5422. },
  5423. /**
  5424. * @ngdoc method
  5425. * @name $cacheFactory.Cache#removeAll
  5426. * @kind function
  5427. *
  5428. * @description
  5429. * Clears the cache object of any entries.
  5430. */
  5431. removeAll: function() {
  5432. data = {};
  5433. size = 0;
  5434. lruHash = {};
  5435. freshEnd = staleEnd = null;
  5436. },
  5437. /**
  5438. * @ngdoc method
  5439. * @name $cacheFactory.Cache#destroy
  5440. * @kind function
  5441. *
  5442. * @description
  5443. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5444. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5445. */
  5446. destroy: function() {
  5447. data = null;
  5448. stats = null;
  5449. lruHash = null;
  5450. delete caches[cacheId];
  5451. },
  5452. /**
  5453. * @ngdoc method
  5454. * @name $cacheFactory.Cache#info
  5455. * @kind function
  5456. *
  5457. * @description
  5458. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5459. *
  5460. * @returns {object} an object with the following properties:
  5461. * <ul>
  5462. * <li>**id**: the id of the cache instance</li>
  5463. * <li>**size**: the number of entries kept in the cache instance</li>
  5464. * <li>**...**: any additional properties from the options object when creating the
  5465. * cache.</li>
  5466. * </ul>
  5467. */
  5468. info: function() {
  5469. return extend({}, stats, {size: size});
  5470. }
  5471. };
  5472. /**
  5473. * makes the `entry` the freshEnd of the LRU linked list
  5474. */
  5475. function refresh(entry) {
  5476. if (entry != freshEnd) {
  5477. if (!staleEnd) {
  5478. staleEnd = entry;
  5479. } else if (staleEnd == entry) {
  5480. staleEnd = entry.n;
  5481. }
  5482. link(entry.n, entry.p);
  5483. link(entry, freshEnd);
  5484. freshEnd = entry;
  5485. freshEnd.n = null;
  5486. }
  5487. }
  5488. /**
  5489. * bidirectionally links two entries of the LRU linked list
  5490. */
  5491. function link(nextEntry, prevEntry) {
  5492. if (nextEntry != prevEntry) {
  5493. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5494. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5495. }
  5496. }
  5497. }
  5498. /**
  5499. * @ngdoc method
  5500. * @name $cacheFactory#info
  5501. *
  5502. * @description
  5503. * Get information about all the caches that have been created
  5504. *
  5505. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5506. */
  5507. cacheFactory.info = function() {
  5508. var info = {};
  5509. forEach(caches, function(cache, cacheId) {
  5510. info[cacheId] = cache.info();
  5511. });
  5512. return info;
  5513. };
  5514. /**
  5515. * @ngdoc method
  5516. * @name $cacheFactory#get
  5517. *
  5518. * @description
  5519. * Get access to a cache object by the `cacheId` used when it was created.
  5520. *
  5521. * @param {string} cacheId Name or id of a cache to access.
  5522. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5523. */
  5524. cacheFactory.get = function(cacheId) {
  5525. return caches[cacheId];
  5526. };
  5527. return cacheFactory;
  5528. };
  5529. }
  5530. /**
  5531. * @ngdoc service
  5532. * @name $templateCache
  5533. *
  5534. * @description
  5535. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5536. * can load templates directly into the cache in a `script` tag, or by consuming the
  5537. * `$templateCache` service directly.
  5538. *
  5539. * Adding via the `script` tag:
  5540. *
  5541. * ```html
  5542. * <script type="text/ng-template" id="templateId.html">
  5543. * <p>This is the content of the template</p>
  5544. * </script>
  5545. * ```
  5546. *
  5547. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5548. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5549. * element with ng-app attribute), otherwise the template will be ignored.
  5550. *
  5551. * Adding via the `$templateCache` service:
  5552. *
  5553. * ```js
  5554. * var myApp = angular.module('myApp', []);
  5555. * myApp.run(function($templateCache) {
  5556. * $templateCache.put('templateId.html', 'This is the content of the template');
  5557. * });
  5558. * ```
  5559. *
  5560. * To retrieve the template later, simply use it in your HTML:
  5561. * ```html
  5562. * <div ng-include=" 'templateId.html' "></div>
  5563. * ```
  5564. *
  5565. * or get it via Javascript:
  5566. * ```js
  5567. * $templateCache.get('templateId.html')
  5568. * ```
  5569. *
  5570. * See {@link ng.$cacheFactory $cacheFactory}.
  5571. *
  5572. */
  5573. function $TemplateCacheProvider() {
  5574. this.$get = ['$cacheFactory', function($cacheFactory) {
  5575. return $cacheFactory('templates');
  5576. }];
  5577. }
  5578. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5579. * Any commits to this file should be reviewed with security in mind. *
  5580. * Changes to this file can potentially create security vulnerabilities. *
  5581. * An approval from 2 Core members with history of modifying *
  5582. * this file is required. *
  5583. * *
  5584. * Does the change somehow allow for arbitrary javascript to be executed? *
  5585. * Or allows for someone to change the prototype of built-in objects? *
  5586. * Or gives undesired access to variables likes document or window? *
  5587. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5588. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5589. *
  5590. * DOM-related variables:
  5591. *
  5592. * - "node" - DOM Node
  5593. * - "element" - DOM Element or Node
  5594. * - "$node" or "$element" - jqLite-wrapped node or element
  5595. *
  5596. *
  5597. * Compiler related stuff:
  5598. *
  5599. * - "linkFn" - linking fn of a single directive
  5600. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5601. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5602. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5603. */
  5604. /**
  5605. * @ngdoc service
  5606. * @name $compile
  5607. * @kind function
  5608. *
  5609. * @description
  5610. * Compiles an HTML string or DOM into a template and produces a template function, which
  5611. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5612. *
  5613. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5614. * {@link ng.$compileProvider#directive directives}.
  5615. *
  5616. * <div class="alert alert-warning">
  5617. * **Note:** This document is an in-depth reference of all directive options.
  5618. * For a gentle introduction to directives with examples of common use cases,
  5619. * see the {@link guide/directive directive guide}.
  5620. * </div>
  5621. *
  5622. * ## Comprehensive Directive API
  5623. *
  5624. * There are many different options for a directive.
  5625. *
  5626. * The difference resides in the return value of the factory function.
  5627. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5628. * or just the `postLink` function (all other properties will have the default values).
  5629. *
  5630. * <div class="alert alert-success">
  5631. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5632. * </div>
  5633. *
  5634. * Here's an example directive declared with a Directive Definition Object:
  5635. *
  5636. * ```js
  5637. * var myModule = angular.module(...);
  5638. *
  5639. * myModule.directive('directiveName', function factory(injectables) {
  5640. * var directiveDefinitionObject = {
  5641. * priority: 0,
  5642. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5643. * // or
  5644. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5645. * transclude: false,
  5646. * restrict: 'A',
  5647. * templateNamespace: 'html',
  5648. * scope: false,
  5649. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5650. * controllerAs: 'stringIdentifier',
  5651. * bindToController: false,
  5652. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5653. * compile: function compile(tElement, tAttrs, transclude) {
  5654. * return {
  5655. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5656. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5657. * }
  5658. * // or
  5659. * // return function postLink( ... ) { ... }
  5660. * },
  5661. * // or
  5662. * // link: {
  5663. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5664. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5665. * // }
  5666. * // or
  5667. * // link: function postLink( ... ) { ... }
  5668. * };
  5669. * return directiveDefinitionObject;
  5670. * });
  5671. * ```
  5672. *
  5673. * <div class="alert alert-warning">
  5674. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5675. * </div>
  5676. *
  5677. * Therefore the above can be simplified as:
  5678. *
  5679. * ```js
  5680. * var myModule = angular.module(...);
  5681. *
  5682. * myModule.directive('directiveName', function factory(injectables) {
  5683. * var directiveDefinitionObject = {
  5684. * link: function postLink(scope, iElement, iAttrs) { ... }
  5685. * };
  5686. * return directiveDefinitionObject;
  5687. * // or
  5688. * // return function postLink(scope, iElement, iAttrs) { ... }
  5689. * });
  5690. * ```
  5691. *
  5692. *
  5693. *
  5694. * ### Directive Definition Object
  5695. *
  5696. * The directive definition object provides instructions to the {@link ng.$compile
  5697. * compiler}. The attributes are:
  5698. *
  5699. * #### `multiElement`
  5700. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5701. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5702. * together as the directive elements. It is recommended that this feature be used on directives
  5703. * which are not strictly behavioural (such as {@link ngClick}), and which
  5704. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5705. *
  5706. * #### `priority`
  5707. * When there are multiple directives defined on a single DOM element, sometimes it
  5708. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5709. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5710. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5711. * are also run in priority order, but post-link functions are run in reverse order. The order
  5712. * of directives with the same priority is undefined. The default priority is `0`.
  5713. *
  5714. * #### `terminal`
  5715. * If set to true then the current `priority` will be the last set of directives
  5716. * which will execute (any directives at the current priority will still execute
  5717. * as the order of execution on same `priority` is undefined). Note that expressions
  5718. * and other directives used in the directive's template will also be excluded from execution.
  5719. *
  5720. * #### `scope`
  5721. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5722. * same element request a new scope, only one new scope is created. The new scope rule does not
  5723. * apply for the root of the template since the root of the template always gets a new scope.
  5724. *
  5725. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5726. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5727. * when creating reusable components, which should not accidentally read or modify data in the
  5728. * parent scope.
  5729. *
  5730. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5731. * derived from the parent scope. These local properties are useful for aliasing values for
  5732. * templates. Locals definition is a hash of local scope property to its source:
  5733. *
  5734. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5735. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5736. * attribute name is assumed to be the same as the local name.
  5737. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5738. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5739. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5740. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5741. * component scope).
  5742. *
  5743. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5744. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5745. * name is specified then the attribute name is assumed to be the same as the local name.
  5746. * Given `<widget my-attr="parentModel">` and widget definition of
  5747. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5748. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5749. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5750. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5751. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5752. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5753. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5754. *
  5755. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5756. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5757. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5758. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5759. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5760. * pass data from the isolated scope via an expression to the parent scope, this can be
  5761. * done by passing a map of local variable names and values into the expression wrapper fn.
  5762. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5763. * by calling the `localFn` as `localFn({amount: 22})`.
  5764. *
  5765. *
  5766. * #### `bindToController`
  5767. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5768. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5769. * is instantiated, the initial values of the isolate scope bindings are already available.
  5770. *
  5771. * #### `controller`
  5772. * Controller constructor function. The controller is instantiated before the
  5773. * pre-linking phase and it is shared with other directives (see
  5774. * `require` attribute). This allows the directives to communicate with each other and augment
  5775. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5776. *
  5777. * * `$scope` - Current scope associated with the element
  5778. * * `$element` - Current element
  5779. * * `$attrs` - Current attributes object for the element
  5780. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5781. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5782. * * `scope`: optional argument to override the scope.
  5783. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5784. * * `futureParentElement`:
  5785. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5786. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5787. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5788. * and when the `cloneLinkinFn` is passed,
  5789. * as those elements need to created and cloned in a special way when they are defined outside their
  5790. * usual containers (e.g. like `<svg>`).
  5791. * * See also the `directive.templateNamespace` property.
  5792. *
  5793. *
  5794. * #### `require`
  5795. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5796. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5797. * injected argument will be an array in corresponding order. If no such directive can be
  5798. * found, or if the directive does not have a controller, then an error is raised (unless no link function
  5799. * is specified, in which case error checking is skipped). The name can be prefixed with:
  5800. *
  5801. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5802. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5803. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5804. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5805. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5806. * `null` to the `link` fn if not found.
  5807. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5808. * `null` to the `link` fn if not found.
  5809. *
  5810. *
  5811. * #### `controllerAs`
  5812. * Identifier name for a reference to the controller in the directive's scope.
  5813. * This allows the controller to be referenced from the directive template. The directive
  5814. * needs to define a scope for this configuration to be used. Useful in the case when
  5815. * directive is used as component.
  5816. *
  5817. *
  5818. * #### `restrict`
  5819. * String of subset of `EACM` which restricts the directive to a specific directive
  5820. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5821. *
  5822. * * `E` - Element name (default): `<my-directive></my-directive>`
  5823. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5824. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5825. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5826. *
  5827. *
  5828. * #### `templateNamespace`
  5829. * String representing the document type used by the markup in the template.
  5830. * AngularJS needs this information as those elements need to be created and cloned
  5831. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5832. *
  5833. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5834. * top-level elements such as `<svg>` or `<math>`.
  5835. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5836. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5837. *
  5838. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5839. *
  5840. * #### `template`
  5841. * HTML markup that may:
  5842. * * Replace the contents of the directive's element (default).
  5843. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5844. * * Wrap the contents of the directive's element (if `transclude` is true).
  5845. *
  5846. * Value may be:
  5847. *
  5848. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5849. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5850. * function api below) and returns a string value.
  5851. *
  5852. *
  5853. * #### `templateUrl`
  5854. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5855. *
  5856. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5857. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5858. * sibling and parent elements as though this element had not contained any directives.
  5859. *
  5860. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5861. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5862. * case when only one deeply nested directive has `templateUrl`.
  5863. *
  5864. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5865. *
  5866. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5867. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5868. * a string value representing the url. In either case, the template URL is passed through {@link
  5869. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5870. *
  5871. *
  5872. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5873. * specify what the template should replace. Defaults to `false`.
  5874. *
  5875. * * `true` - the template will replace the directive's element.
  5876. * * `false` - the template will replace the contents of the directive's element.
  5877. *
  5878. * The replacement process migrates all of the attributes / classes from the old element to the new
  5879. * one. See the {@link guide/directive#template-expanding-directive
  5880. * Directives Guide} for an example.
  5881. *
  5882. * There are very few scenarios where element replacement is required for the application function,
  5883. * the main one being reusable custom components that are used within SVG contexts
  5884. * (because SVG doesn't work with custom elements in the DOM tree).
  5885. *
  5886. * #### `transclude`
  5887. * Extract the contents of the element where the directive appears and make it available to the directive.
  5888. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5889. * {@link $compile#transclusion Transclusion} section below.
  5890. *
  5891. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5892. * directive's element or the entire element:
  5893. *
  5894. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5895. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5896. * element that defined at a lower priority than this directive. When used, the `template`
  5897. * property is ignored.
  5898. *
  5899. *
  5900. * #### `compile`
  5901. *
  5902. * ```js
  5903. * function compile(tElement, tAttrs, transclude) { ... }
  5904. * ```
  5905. *
  5906. * The compile function deals with transforming the template DOM. Since most directives do not do
  5907. * template transformation, it is not used often. The compile function takes the following arguments:
  5908. *
  5909. * * `tElement` - template element - The element where the directive has been declared. It is
  5910. * safe to do template transformation on the element and child elements only.
  5911. *
  5912. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5913. * between all directive compile functions.
  5914. *
  5915. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5916. *
  5917. * <div class="alert alert-warning">
  5918. * **Note:** The template instance and the link instance may be different objects if the template has
  5919. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5920. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5921. * should be done in a linking function rather than in a compile function.
  5922. * </div>
  5923. * <div class="alert alert-warning">
  5924. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5925. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5926. * stack overflow errors.
  5927. *
  5928. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5929. * a directive's template instead of relying on automatic template compilation via `template` or
  5930. * `templateUrl` declaration or manual compilation inside the compile function.
  5931. * </div>
  5932. *
  5933. * <div class="alert alert-danger">
  5934. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5935. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5936. * to the link function instead.
  5937. * </div>
  5938. * A compile function can have a return value which can be either a function or an object.
  5939. *
  5940. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5941. * `link` property of the config object when the compile function is empty.
  5942. *
  5943. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5944. * control when a linking function should be called during the linking phase. See info about
  5945. * pre-linking and post-linking functions below.
  5946. *
  5947. *
  5948. * #### `link`
  5949. * This property is used only if the `compile` property is not defined.
  5950. *
  5951. * ```js
  5952. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5953. * ```
  5954. *
  5955. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5956. * executed after the template has been cloned. This is where most of the directive logic will be
  5957. * put.
  5958. *
  5959. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5960. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5961. *
  5962. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5963. * manipulate the children of the element only in `postLink` function since the children have
  5964. * already been linked.
  5965. *
  5966. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5967. * between all directive linking functions.
  5968. *
  5969. * * `controller` - the directive's required controller instance(s) - Instances are shared
  5970. * among all directives, which allows the directives to use the controllers as a communication
  5971. * channel. The exact value depends on the directive's `require` property:
  5972. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  5973. * * `string`: the controller instance
  5974. * * `array`: array of controller instances
  5975. *
  5976. * If a required controller cannot be found, and it is optional, the instance is `null`,
  5977. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  5978. *
  5979. * Note that you can also require the directive's own controller - it will be made available like
  5980. * any other controller.
  5981. *
  5982. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5983. * This is the same as the `$transclude`
  5984. * parameter of directive controllers, see there for details.
  5985. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5986. *
  5987. * #### Pre-linking function
  5988. *
  5989. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5990. * compiler linking function will fail to locate the correct elements for linking.
  5991. *
  5992. * #### Post-linking function
  5993. *
  5994. * Executed after the child elements are linked.
  5995. *
  5996. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5997. * and linked since they are waiting for their template to load asynchronously and their own
  5998. * compilation and linking has been suspended until that occurs.
  5999. *
  6000. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6001. * for their async templates to be resolved.
  6002. *
  6003. *
  6004. * ### Transclusion
  6005. *
  6006. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6007. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6008. * scope from where they were taken.
  6009. *
  6010. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6011. * original contents of a directive's element into a specified place in the template of the directive.
  6012. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6013. * content has access to the properties on the scope from which it was taken, even if the directive
  6014. * has isolated scope.
  6015. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6016. *
  6017. * This makes it possible for the widget to have private state for its template, while the transcluded
  6018. * content has access to its originating scope.
  6019. *
  6020. * <div class="alert alert-warning">
  6021. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6022. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6023. * Testing Transclusion Directives}.
  6024. * </div>
  6025. *
  6026. * #### Transclusion Functions
  6027. *
  6028. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6029. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6030. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6031. *
  6032. * <div class="alert alert-info">
  6033. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6034. * ngTransclude will deal with it for us.
  6035. * </div>
  6036. *
  6037. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6038. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6039. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6040. *
  6041. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6042. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6043. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  6044. *
  6045. * <div class="alert alert-info">
  6046. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  6047. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6048. * </div>
  6049. *
  6050. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6051. * attach function**:
  6052. *
  6053. * ```js
  6054. * var transcludedContent, transclusionScope;
  6055. *
  6056. * $transclude(function(clone, scope) {
  6057. * element.append(clone);
  6058. * transcludedContent = clone;
  6059. * transclusionScope = scope;
  6060. * });
  6061. * ```
  6062. *
  6063. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6064. * associated transclusion scope:
  6065. *
  6066. * ```js
  6067. * transcludedContent.remove();
  6068. * transclusionScope.$destroy();
  6069. * ```
  6070. *
  6071. * <div class="alert alert-info">
  6072. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6073. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6074. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6075. * </div>
  6076. *
  6077. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6078. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  6079. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6080. *
  6081. *
  6082. * #### Transclusion Scopes
  6083. *
  6084. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6085. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6086. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6087. * was taken.
  6088. *
  6089. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6090. * like this:
  6091. *
  6092. * ```html
  6093. * <div ng-app>
  6094. * <div isolate>
  6095. * <div transclusion>
  6096. * </div>
  6097. * </div>
  6098. * </div>
  6099. * ```
  6100. *
  6101. * The `$parent` scope hierarchy will look like this:
  6102. *
  6103. * ```
  6104. * - $rootScope
  6105. * - isolate
  6106. * - transclusion
  6107. * ```
  6108. *
  6109. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6110. *
  6111. * ```
  6112. * - $rootScope
  6113. * - transclusion
  6114. * - isolate
  6115. * ```
  6116. *
  6117. *
  6118. * ### Attributes
  6119. *
  6120. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6121. * `link()` or `compile()` functions. It has a variety of uses.
  6122. *
  6123. * accessing *Normalized attribute names:*
  6124. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  6125. * the attributes object allows for normalized access to
  6126. * the attributes.
  6127. *
  6128. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6129. * object which allows the directives to use the attributes object as inter directive
  6130. * communication.
  6131. *
  6132. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6133. * allowing other directives to read the interpolated value.
  6134. *
  6135. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6136. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6137. * the only way to easily get the actual value because during the linking phase the interpolation
  6138. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6139. *
  6140. * ```js
  6141. * function linkingFn(scope, elm, attrs, ctrl) {
  6142. * // get the attribute value
  6143. * console.log(attrs.ngModel);
  6144. *
  6145. * // change the attribute
  6146. * attrs.$set('ngModel', 'new value');
  6147. *
  6148. * // observe changes to interpolated attribute
  6149. * attrs.$observe('ngModel', function(value) {
  6150. * console.log('ngModel has changed value to ' + value);
  6151. * });
  6152. * }
  6153. * ```
  6154. *
  6155. * ## Example
  6156. *
  6157. * <div class="alert alert-warning">
  6158. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6159. * to illustrate how `$compile` works.
  6160. * </div>
  6161. *
  6162. <example module="compileExample">
  6163. <file name="index.html">
  6164. <script>
  6165. angular.module('compileExample', [], function($compileProvider) {
  6166. // configure new 'compile' directive by passing a directive
  6167. // factory function. The factory function injects the '$compile'
  6168. $compileProvider.directive('compile', function($compile) {
  6169. // directive factory creates a link function
  6170. return function(scope, element, attrs) {
  6171. scope.$watch(
  6172. function(scope) {
  6173. // watch the 'compile' expression for changes
  6174. return scope.$eval(attrs.compile);
  6175. },
  6176. function(value) {
  6177. // when the 'compile' expression changes
  6178. // assign it into the current DOM
  6179. element.html(value);
  6180. // compile the new DOM and link it to the current
  6181. // scope.
  6182. // NOTE: we only compile .childNodes so that
  6183. // we don't get into infinite loop compiling ourselves
  6184. $compile(element.contents())(scope);
  6185. }
  6186. );
  6187. };
  6188. });
  6189. })
  6190. .controller('GreeterController', ['$scope', function($scope) {
  6191. $scope.name = 'Angular';
  6192. $scope.html = 'Hello {{name}}';
  6193. }]);
  6194. </script>
  6195. <div ng-controller="GreeterController">
  6196. <input ng-model="name"> <br/>
  6197. <textarea ng-model="html"></textarea> <br/>
  6198. <div compile="html"></div>
  6199. </div>
  6200. </file>
  6201. <file name="protractor.js" type="protractor">
  6202. it('should auto compile', function() {
  6203. var textarea = $('textarea');
  6204. var output = $('div[compile]');
  6205. // The initial state reads 'Hello Angular'.
  6206. expect(output.getText()).toBe('Hello Angular');
  6207. textarea.clear();
  6208. textarea.sendKeys('{{name}}!');
  6209. expect(output.getText()).toBe('Angular!');
  6210. });
  6211. </file>
  6212. </example>
  6213. *
  6214. *
  6215. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6216. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6217. *
  6218. * <div class="alert alert-danger">
  6219. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6220. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6221. * `parentBoundTranscludeFn` to the link function instead.
  6222. * </div>
  6223. *
  6224. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6225. * root element(s), not their children)
  6226. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6227. * (a DOM element/tree) to a scope. Where:
  6228. *
  6229. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6230. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6231. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6232. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6233. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6234. *
  6235. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6236. * * `scope` - is the current scope with which the linking function is working with.
  6237. *
  6238. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6239. * keys may be used to control linking behavior:
  6240. *
  6241. * * `parentBoundTranscludeFn` - the transclude function made available to
  6242. * directives; if given, it will be passed through to the link functions of
  6243. * directives found in `element` during compilation.
  6244. * * `transcludeControllers` - an object hash with keys that map controller names
  6245. * to controller instances; if given, it will make the controllers
  6246. * available to directives.
  6247. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6248. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6249. * elements (e.g. SVG elements). See also the directive.controller property.
  6250. *
  6251. * Calling the linking function returns the element of the template. It is either the original
  6252. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6253. *
  6254. * After linking the view is not updated until after a call to $digest which typically is done by
  6255. * Angular automatically.
  6256. *
  6257. * If you need access to the bound view, there are two ways to do it:
  6258. *
  6259. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6260. * before you send them to the compiler and keep this reference around.
  6261. * ```js
  6262. * var element = $compile('<p>{{total}}</p>')(scope);
  6263. * ```
  6264. *
  6265. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6266. * example would not point to the clone, but rather to the original template that was cloned. In
  6267. * this case, you can access the clone via the cloneAttachFn:
  6268. * ```js
  6269. * var templateElement = angular.element('<p>{{total}}</p>'),
  6270. * scope = ....;
  6271. *
  6272. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6273. * //attach the clone to DOM document at the right place
  6274. * });
  6275. *
  6276. * //now we have reference to the cloned DOM via `clonedElement`
  6277. * ```
  6278. *
  6279. *
  6280. * For information on how the compiler works, see the
  6281. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6282. */
  6283. var $compileMinErr = minErr('$compile');
  6284. /**
  6285. * @ngdoc provider
  6286. * @name $compileProvider
  6287. *
  6288. * @description
  6289. */
  6290. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6291. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6292. var hasDirectives = {},
  6293. Suffix = 'Directive',
  6294. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6295. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6296. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6297. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6298. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6299. // The assumption is that future DOM event attribute names will begin with
  6300. // 'on' and be composed of only English letters.
  6301. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6302. function parseIsolateBindings(scope, directiveName, isController) {
  6303. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  6304. var bindings = {};
  6305. forEach(scope, function(definition, scopeName) {
  6306. var match = definition.match(LOCAL_REGEXP);
  6307. if (!match) {
  6308. throw $compileMinErr('iscp',
  6309. "Invalid {3} for directive '{0}'." +
  6310. " Definition: {... {1}: '{2}' ...}",
  6311. directiveName, scopeName, definition,
  6312. (isController ? "controller bindings definition" :
  6313. "isolate scope definition"));
  6314. }
  6315. bindings[scopeName] = {
  6316. mode: match[1][0],
  6317. collection: match[2] === '*',
  6318. optional: match[3] === '?',
  6319. attrName: match[4] || scopeName
  6320. };
  6321. });
  6322. return bindings;
  6323. }
  6324. function parseDirectiveBindings(directive, directiveName) {
  6325. var bindings = {
  6326. isolateScope: null,
  6327. bindToController: null
  6328. };
  6329. if (isObject(directive.scope)) {
  6330. if (directive.bindToController === true) {
  6331. bindings.bindToController = parseIsolateBindings(directive.scope,
  6332. directiveName, true);
  6333. bindings.isolateScope = {};
  6334. } else {
  6335. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6336. directiveName, false);
  6337. }
  6338. }
  6339. if (isObject(directive.bindToController)) {
  6340. bindings.bindToController =
  6341. parseIsolateBindings(directive.bindToController, directiveName, true);
  6342. }
  6343. if (isObject(bindings.bindToController)) {
  6344. var controller = directive.controller;
  6345. var controllerAs = directive.controllerAs;
  6346. if (!controller) {
  6347. // There is no controller, there may or may not be a controllerAs property
  6348. throw $compileMinErr('noctrl',
  6349. "Cannot bind to controller without directive '{0}'s controller.",
  6350. directiveName);
  6351. } else if (!identifierForController(controller, controllerAs)) {
  6352. // There is a controller, but no identifier or controllerAs property
  6353. throw $compileMinErr('noident',
  6354. "Cannot bind to controller without identifier for directive '{0}'.",
  6355. directiveName);
  6356. }
  6357. }
  6358. return bindings;
  6359. }
  6360. function assertValidDirectiveName(name) {
  6361. var letter = name.charAt(0);
  6362. if (!letter || letter !== lowercase(letter)) {
  6363. throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
  6364. }
  6365. if (name !== name.trim()) {
  6366. throw $compileMinErr('baddir',
  6367. "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6368. name);
  6369. }
  6370. }
  6371. /**
  6372. * @ngdoc method
  6373. * @name $compileProvider#directive
  6374. * @kind function
  6375. *
  6376. * @description
  6377. * Register a new directive with the compiler.
  6378. *
  6379. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6380. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6381. * names and the values are the factories.
  6382. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  6383. * {@link guide/directive} for more info.
  6384. * @returns {ng.$compileProvider} Self for chaining.
  6385. */
  6386. this.directive = function registerDirective(name, directiveFactory) {
  6387. assertNotHasOwnProperty(name, 'directive');
  6388. if (isString(name)) {
  6389. assertValidDirectiveName(name);
  6390. assertArg(directiveFactory, 'directiveFactory');
  6391. if (!hasDirectives.hasOwnProperty(name)) {
  6392. hasDirectives[name] = [];
  6393. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6394. function($injector, $exceptionHandler) {
  6395. var directives = [];
  6396. forEach(hasDirectives[name], function(directiveFactory, index) {
  6397. try {
  6398. var directive = $injector.invoke(directiveFactory);
  6399. if (isFunction(directive)) {
  6400. directive = { compile: valueFn(directive) };
  6401. } else if (!directive.compile && directive.link) {
  6402. directive.compile = valueFn(directive.link);
  6403. }
  6404. directive.priority = directive.priority || 0;
  6405. directive.index = index;
  6406. directive.name = directive.name || name;
  6407. directive.require = directive.require || (directive.controller && directive.name);
  6408. directive.restrict = directive.restrict || 'EA';
  6409. var bindings = directive.$$bindings =
  6410. parseDirectiveBindings(directive, directive.name);
  6411. if (isObject(bindings.isolateScope)) {
  6412. directive.$$isolateBindings = bindings.isolateScope;
  6413. }
  6414. directive.$$moduleName = directiveFactory.$$moduleName;
  6415. directives.push(directive);
  6416. } catch (e) {
  6417. $exceptionHandler(e);
  6418. }
  6419. });
  6420. return directives;
  6421. }]);
  6422. }
  6423. hasDirectives[name].push(directiveFactory);
  6424. } else {
  6425. forEach(name, reverseParams(registerDirective));
  6426. }
  6427. return this;
  6428. };
  6429. /**
  6430. * @ngdoc method
  6431. * @name $compileProvider#aHrefSanitizationWhitelist
  6432. * @kind function
  6433. *
  6434. * @description
  6435. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6436. * urls during a[href] sanitization.
  6437. *
  6438. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  6439. *
  6440. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  6441. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  6442. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6443. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6444. *
  6445. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6446. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6447. * chaining otherwise.
  6448. */
  6449. this.aHrefSanitizationWhitelist = function(regexp) {
  6450. if (isDefined(regexp)) {
  6451. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  6452. return this;
  6453. } else {
  6454. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  6455. }
  6456. };
  6457. /**
  6458. * @ngdoc method
  6459. * @name $compileProvider#imgSrcSanitizationWhitelist
  6460. * @kind function
  6461. *
  6462. * @description
  6463. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6464. * urls during img[src] sanitization.
  6465. *
  6466. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6467. *
  6468. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  6469. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  6470. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6471. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6472. *
  6473. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6474. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6475. * chaining otherwise.
  6476. */
  6477. this.imgSrcSanitizationWhitelist = function(regexp) {
  6478. if (isDefined(regexp)) {
  6479. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  6480. return this;
  6481. } else {
  6482. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  6483. }
  6484. };
  6485. /**
  6486. * @ngdoc method
  6487. * @name $compileProvider#debugInfoEnabled
  6488. *
  6489. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6490. * current debugInfoEnabled state
  6491. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  6492. *
  6493. * @kind function
  6494. *
  6495. * @description
  6496. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  6497. * binding information and a reference to the current scope on to DOM elements.
  6498. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  6499. * * `ng-binding` CSS class
  6500. * * `$binding` data property containing an array of the binding expressions
  6501. *
  6502. * You may want to disable this in production for a significant performance boost. See
  6503. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  6504. *
  6505. * The default value is true.
  6506. */
  6507. var debugInfoEnabled = true;
  6508. this.debugInfoEnabled = function(enabled) {
  6509. if (isDefined(enabled)) {
  6510. debugInfoEnabled = enabled;
  6511. return this;
  6512. }
  6513. return debugInfoEnabled;
  6514. };
  6515. this.$get = [
  6516. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6517. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6518. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6519. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6520. var Attributes = function(element, attributesToCopy) {
  6521. if (attributesToCopy) {
  6522. var keys = Object.keys(attributesToCopy);
  6523. var i, l, key;
  6524. for (i = 0, l = keys.length; i < l; i++) {
  6525. key = keys[i];
  6526. this[key] = attributesToCopy[key];
  6527. }
  6528. } else {
  6529. this.$attr = {};
  6530. }
  6531. this.$$element = element;
  6532. };
  6533. Attributes.prototype = {
  6534. /**
  6535. * @ngdoc method
  6536. * @name $compile.directive.Attributes#$normalize
  6537. * @kind function
  6538. *
  6539. * @description
  6540. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6541. * `data-`) to its normalized, camelCase form.
  6542. *
  6543. * Also there is special case for Moz prefix starting with upper case letter.
  6544. *
  6545. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6546. *
  6547. * @param {string} name Name to normalize
  6548. */
  6549. $normalize: directiveNormalize,
  6550. /**
  6551. * @ngdoc method
  6552. * @name $compile.directive.Attributes#$addClass
  6553. * @kind function
  6554. *
  6555. * @description
  6556. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6557. * are enabled then an animation will be triggered for the class addition.
  6558. *
  6559. * @param {string} classVal The className value that will be added to the element
  6560. */
  6561. $addClass: function(classVal) {
  6562. if (classVal && classVal.length > 0) {
  6563. $animate.addClass(this.$$element, classVal);
  6564. }
  6565. },
  6566. /**
  6567. * @ngdoc method
  6568. * @name $compile.directive.Attributes#$removeClass
  6569. * @kind function
  6570. *
  6571. * @description
  6572. * Removes the CSS class value specified by the classVal parameter from the element. If
  6573. * animations are enabled then an animation will be triggered for the class removal.
  6574. *
  6575. * @param {string} classVal The className value that will be removed from the element
  6576. */
  6577. $removeClass: function(classVal) {
  6578. if (classVal && classVal.length > 0) {
  6579. $animate.removeClass(this.$$element, classVal);
  6580. }
  6581. },
  6582. /**
  6583. * @ngdoc method
  6584. * @name $compile.directive.Attributes#$updateClass
  6585. * @kind function
  6586. *
  6587. * @description
  6588. * Adds and removes the appropriate CSS class values to the element based on the difference
  6589. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6590. *
  6591. * @param {string} newClasses The current CSS className value
  6592. * @param {string} oldClasses The former CSS className value
  6593. */
  6594. $updateClass: function(newClasses, oldClasses) {
  6595. var toAdd = tokenDifference(newClasses, oldClasses);
  6596. if (toAdd && toAdd.length) {
  6597. $animate.addClass(this.$$element, toAdd);
  6598. }
  6599. var toRemove = tokenDifference(oldClasses, newClasses);
  6600. if (toRemove && toRemove.length) {
  6601. $animate.removeClass(this.$$element, toRemove);
  6602. }
  6603. },
  6604. /**
  6605. * Set a normalized attribute on the element in a way such that all directives
  6606. * can share the attribute. This function properly handles boolean attributes.
  6607. * @param {string} key Normalized key. (ie ngAttribute)
  6608. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6609. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6610. * Defaults to true.
  6611. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6612. */
  6613. $set: function(key, value, writeAttr, attrName) {
  6614. // TODO: decide whether or not to throw an error if "class"
  6615. //is set through this function since it may cause $updateClass to
  6616. //become unstable.
  6617. var node = this.$$element[0],
  6618. booleanKey = getBooleanAttrName(node, key),
  6619. aliasedKey = getAliasedAttrName(node, key),
  6620. observer = key,
  6621. nodeName;
  6622. if (booleanKey) {
  6623. this.$$element.prop(key, value);
  6624. attrName = booleanKey;
  6625. } else if (aliasedKey) {
  6626. this[aliasedKey] = value;
  6627. observer = aliasedKey;
  6628. }
  6629. this[key] = value;
  6630. // translate normalized key to actual key
  6631. if (attrName) {
  6632. this.$attr[key] = attrName;
  6633. } else {
  6634. attrName = this.$attr[key];
  6635. if (!attrName) {
  6636. this.$attr[key] = attrName = snake_case(key, '-');
  6637. }
  6638. }
  6639. nodeName = nodeName_(this.$$element);
  6640. if ((nodeName === 'a' && key === 'href') ||
  6641. (nodeName === 'img' && key === 'src')) {
  6642. // sanitize a[href] and img[src] values
  6643. this[key] = value = $$sanitizeUri(value, key === 'src');
  6644. } else if (nodeName === 'img' && key === 'srcset') {
  6645. // sanitize img[srcset] values
  6646. var result = "";
  6647. // first check if there are spaces because it's not the same pattern
  6648. var trimmedSrcset = trim(value);
  6649. // ( 999x ,| 999w ,| ,|, )
  6650. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6651. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6652. // split srcset into tuple of uri and descriptor except for the last item
  6653. var rawUris = trimmedSrcset.split(pattern);
  6654. // for each tuples
  6655. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6656. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6657. var innerIdx = i * 2;
  6658. // sanitize the uri
  6659. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6660. // add the descriptor
  6661. result += (" " + trim(rawUris[innerIdx + 1]));
  6662. }
  6663. // split the last item into uri and descriptor
  6664. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6665. // sanitize the last uri
  6666. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6667. // and add the last descriptor if any
  6668. if (lastTuple.length === 2) {
  6669. result += (" " + trim(lastTuple[1]));
  6670. }
  6671. this[key] = value = result;
  6672. }
  6673. if (writeAttr !== false) {
  6674. if (value === null || value === undefined) {
  6675. this.$$element.removeAttr(attrName);
  6676. } else {
  6677. this.$$element.attr(attrName, value);
  6678. }
  6679. }
  6680. // fire observers
  6681. var $$observers = this.$$observers;
  6682. $$observers && forEach($$observers[observer], function(fn) {
  6683. try {
  6684. fn(value);
  6685. } catch (e) {
  6686. $exceptionHandler(e);
  6687. }
  6688. });
  6689. },
  6690. /**
  6691. * @ngdoc method
  6692. * @name $compile.directive.Attributes#$observe
  6693. * @kind function
  6694. *
  6695. * @description
  6696. * Observes an interpolated attribute.
  6697. *
  6698. * The observer function will be invoked once during the next `$digest` following
  6699. * compilation. The observer is then invoked whenever the interpolated value
  6700. * changes.
  6701. *
  6702. * @param {string} key Normalized key. (ie ngAttribute) .
  6703. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6704. the interpolated value of the attribute changes.
  6705. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6706. * @returns {function()} Returns a deregistration function for this observer.
  6707. */
  6708. $observe: function(key, fn) {
  6709. var attrs = this,
  6710. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6711. listeners = ($$observers[key] || ($$observers[key] = []));
  6712. listeners.push(fn);
  6713. $rootScope.$evalAsync(function() {
  6714. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  6715. // no one registered attribute interpolation function, so lets call it manually
  6716. fn(attrs[key]);
  6717. }
  6718. });
  6719. return function() {
  6720. arrayRemove(listeners, fn);
  6721. };
  6722. }
  6723. };
  6724. function safeAddClass($element, className) {
  6725. try {
  6726. $element.addClass(className);
  6727. } catch (e) {
  6728. // ignore, since it means that we are trying to set class on
  6729. // SVG element, where class name is read-only.
  6730. }
  6731. }
  6732. var startSymbol = $interpolate.startSymbol(),
  6733. endSymbol = $interpolate.endSymbol(),
  6734. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6735. ? identity
  6736. : function denormalizeTemplate(template) {
  6737. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6738. },
  6739. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6740. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6741. var bindings = $element.data('$binding') || [];
  6742. if (isArray(binding)) {
  6743. bindings = bindings.concat(binding);
  6744. } else {
  6745. bindings.push(binding);
  6746. }
  6747. $element.data('$binding', bindings);
  6748. } : noop;
  6749. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6750. safeAddClass($element, 'ng-binding');
  6751. } : noop;
  6752. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6753. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6754. $element.data(dataName, scope);
  6755. } : noop;
  6756. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6757. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6758. } : noop;
  6759. return compile;
  6760. //================================
  6761. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6762. previousCompileContext) {
  6763. if (!($compileNodes instanceof jqLite)) {
  6764. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6765. // modify it.
  6766. $compileNodes = jqLite($compileNodes);
  6767. }
  6768. // We can not compile top level text elements since text nodes can be merged and we will
  6769. // not be able to attach scope data to them, so we will wrap them in <span>
  6770. forEach($compileNodes, function(node, index) {
  6771. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6772. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6773. }
  6774. });
  6775. var compositeLinkFn =
  6776. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6777. maxPriority, ignoreDirective, previousCompileContext);
  6778. compile.$$addScopeClass($compileNodes);
  6779. var namespace = null;
  6780. return function publicLinkFn(scope, cloneConnectFn, options) {
  6781. assertArg(scope, 'scope');
  6782. options = options || {};
  6783. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6784. transcludeControllers = options.transcludeControllers,
  6785. futureParentElement = options.futureParentElement;
  6786. // When `parentBoundTranscludeFn` is passed, it is a
  6787. // `controllersBoundTransclude` function (it was previously passed
  6788. // as `transclude` to directive.link) so we must unwrap it to get
  6789. // its `boundTranscludeFn`
  6790. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6791. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6792. }
  6793. if (!namespace) {
  6794. namespace = detectNamespaceForChildElements(futureParentElement);
  6795. }
  6796. var $linkNode;
  6797. if (namespace !== 'html') {
  6798. // When using a directive with replace:true and templateUrl the $compileNodes
  6799. // (or a child element inside of them)
  6800. // might change, so we need to recreate the namespace adapted compileNodes
  6801. // for call to the link function.
  6802. // Note: This will already clone the nodes...
  6803. $linkNode = jqLite(
  6804. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6805. );
  6806. } else if (cloneConnectFn) {
  6807. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6808. // and sometimes changes the structure of the DOM.
  6809. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6810. } else {
  6811. $linkNode = $compileNodes;
  6812. }
  6813. if (transcludeControllers) {
  6814. for (var controllerName in transcludeControllers) {
  6815. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6816. }
  6817. }
  6818. compile.$$addScopeInfo($linkNode, scope);
  6819. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6820. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6821. return $linkNode;
  6822. };
  6823. }
  6824. function detectNamespaceForChildElements(parentElement) {
  6825. // TODO: Make this detect MathML as well...
  6826. var node = parentElement && parentElement[0];
  6827. if (!node) {
  6828. return 'html';
  6829. } else {
  6830. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6831. }
  6832. }
  6833. /**
  6834. * Compile function matches each node in nodeList against the directives. Once all directives
  6835. * for a particular node are collected their compile functions are executed. The compile
  6836. * functions return values - the linking functions - are combined into a composite linking
  6837. * function, which is the a linking function for the node.
  6838. *
  6839. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6840. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6841. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6842. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6843. * the rootElement must be set the jqLite collection of the compile root. This is
  6844. * needed so that the jqLite collection items can be replaced with widgets.
  6845. * @param {number=} maxPriority Max directive priority.
  6846. * @returns {Function} A composite linking function of all of the matched directives or null.
  6847. */
  6848. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6849. previousCompileContext) {
  6850. var linkFns = [],
  6851. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6852. for (var i = 0; i < nodeList.length; i++) {
  6853. attrs = new Attributes();
  6854. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6855. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6856. ignoreDirective);
  6857. nodeLinkFn = (directives.length)
  6858. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6859. null, [], [], previousCompileContext)
  6860. : null;
  6861. if (nodeLinkFn && nodeLinkFn.scope) {
  6862. compile.$$addScopeClass(attrs.$$element);
  6863. }
  6864. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6865. !(childNodes = nodeList[i].childNodes) ||
  6866. !childNodes.length)
  6867. ? null
  6868. : compileNodes(childNodes,
  6869. nodeLinkFn ? (
  6870. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6871. && nodeLinkFn.transclude) : transcludeFn);
  6872. if (nodeLinkFn || childLinkFn) {
  6873. linkFns.push(i, nodeLinkFn, childLinkFn);
  6874. linkFnFound = true;
  6875. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6876. }
  6877. //use the previous context only for the first element in the virtual group
  6878. previousCompileContext = null;
  6879. }
  6880. // return a linking function if we have found anything, null otherwise
  6881. return linkFnFound ? compositeLinkFn : null;
  6882. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6883. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6884. var stableNodeList;
  6885. if (nodeLinkFnFound) {
  6886. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6887. // offsets don't get screwed up
  6888. var nodeListLength = nodeList.length;
  6889. stableNodeList = new Array(nodeListLength);
  6890. // create a sparse array by only copying the elements which have a linkFn
  6891. for (i = 0; i < linkFns.length; i+=3) {
  6892. idx = linkFns[i];
  6893. stableNodeList[idx] = nodeList[idx];
  6894. }
  6895. } else {
  6896. stableNodeList = nodeList;
  6897. }
  6898. for (i = 0, ii = linkFns.length; i < ii;) {
  6899. node = stableNodeList[linkFns[i++]];
  6900. nodeLinkFn = linkFns[i++];
  6901. childLinkFn = linkFns[i++];
  6902. if (nodeLinkFn) {
  6903. if (nodeLinkFn.scope) {
  6904. childScope = scope.$new();
  6905. compile.$$addScopeInfo(jqLite(node), childScope);
  6906. var destroyBindings = nodeLinkFn.$$destroyBindings;
  6907. if (destroyBindings) {
  6908. nodeLinkFn.$$destroyBindings = null;
  6909. childScope.$on('$destroyed', destroyBindings);
  6910. }
  6911. } else {
  6912. childScope = scope;
  6913. }
  6914. if (nodeLinkFn.transcludeOnThisElement) {
  6915. childBoundTranscludeFn = createBoundTranscludeFn(
  6916. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  6917. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6918. childBoundTranscludeFn = parentBoundTranscludeFn;
  6919. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6920. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6921. } else {
  6922. childBoundTranscludeFn = null;
  6923. }
  6924. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,
  6925. nodeLinkFn);
  6926. } else if (childLinkFn) {
  6927. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6928. }
  6929. }
  6930. }
  6931. }
  6932. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  6933. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6934. if (!transcludedScope) {
  6935. transcludedScope = scope.$new(false, containingScope);
  6936. transcludedScope.$$transcluded = true;
  6937. }
  6938. return transcludeFn(transcludedScope, cloneFn, {
  6939. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6940. transcludeControllers: controllers,
  6941. futureParentElement: futureParentElement
  6942. });
  6943. };
  6944. return boundTranscludeFn;
  6945. }
  6946. /**
  6947. * Looks for directives on the given node and adds them to the directive collection which is
  6948. * sorted.
  6949. *
  6950. * @param node Node to search.
  6951. * @param directives An array to which the directives are added to. This array is sorted before
  6952. * the function returns.
  6953. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6954. * @param {number=} maxPriority Max directive priority.
  6955. */
  6956. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6957. var nodeType = node.nodeType,
  6958. attrsMap = attrs.$attr,
  6959. match,
  6960. className;
  6961. switch (nodeType) {
  6962. case NODE_TYPE_ELEMENT: /* Element */
  6963. // use the node name: <directive>
  6964. addDirective(directives,
  6965. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6966. // iterate over the attributes
  6967. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6968. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6969. var attrStartName = false;
  6970. var attrEndName = false;
  6971. attr = nAttrs[j];
  6972. name = attr.name;
  6973. value = trim(attr.value);
  6974. // support ngAttr attribute binding
  6975. ngAttrName = directiveNormalize(name);
  6976. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6977. name = name.replace(PREFIX_REGEXP, '')
  6978. .substr(8).replace(/_(.)/g, function(match, letter) {
  6979. return letter.toUpperCase();
  6980. });
  6981. }
  6982. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6983. if (directiveIsMultiElement(directiveNName)) {
  6984. if (ngAttrName === directiveNName + 'Start') {
  6985. attrStartName = name;
  6986. attrEndName = name.substr(0, name.length - 5) + 'end';
  6987. name = name.substr(0, name.length - 6);
  6988. }
  6989. }
  6990. nName = directiveNormalize(name.toLowerCase());
  6991. attrsMap[nName] = name;
  6992. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6993. attrs[nName] = value;
  6994. if (getBooleanAttrName(node, nName)) {
  6995. attrs[nName] = true; // presence means true
  6996. }
  6997. }
  6998. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6999. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  7000. attrEndName);
  7001. }
  7002. // use class as directive
  7003. className = node.className;
  7004. if (isObject(className)) {
  7005. // Maybe SVGAnimatedString
  7006. className = className.animVal;
  7007. }
  7008. if (isString(className) && className !== '') {
  7009. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  7010. nName = directiveNormalize(match[2]);
  7011. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  7012. attrs[nName] = trim(match[3]);
  7013. }
  7014. className = className.substr(match.index + match[0].length);
  7015. }
  7016. }
  7017. break;
  7018. case NODE_TYPE_TEXT: /* Text Node */
  7019. if (msie === 11) {
  7020. // Workaround for #11781
  7021. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  7022. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  7023. node.parentNode.removeChild(node.nextSibling);
  7024. }
  7025. }
  7026. addTextInterpolateDirective(directives, node.nodeValue);
  7027. break;
  7028. case NODE_TYPE_COMMENT: /* Comment */
  7029. try {
  7030. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  7031. if (match) {
  7032. nName = directiveNormalize(match[1]);
  7033. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  7034. attrs[nName] = trim(match[2]);
  7035. }
  7036. }
  7037. } catch (e) {
  7038. // turns out that under some circumstances IE9 throws errors when one attempts to read
  7039. // comment's node value.
  7040. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  7041. }
  7042. break;
  7043. }
  7044. directives.sort(byPriority);
  7045. return directives;
  7046. }
  7047. /**
  7048. * Given a node with an directive-start it collects all of the siblings until it finds
  7049. * directive-end.
  7050. * @param node
  7051. * @param attrStart
  7052. * @param attrEnd
  7053. * @returns {*}
  7054. */
  7055. function groupScan(node, attrStart, attrEnd) {
  7056. var nodes = [];
  7057. var depth = 0;
  7058. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  7059. do {
  7060. if (!node) {
  7061. throw $compileMinErr('uterdir',
  7062. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  7063. attrStart, attrEnd);
  7064. }
  7065. if (node.nodeType == NODE_TYPE_ELEMENT) {
  7066. if (node.hasAttribute(attrStart)) depth++;
  7067. if (node.hasAttribute(attrEnd)) depth--;
  7068. }
  7069. nodes.push(node);
  7070. node = node.nextSibling;
  7071. } while (depth > 0);
  7072. } else {
  7073. nodes.push(node);
  7074. }
  7075. return jqLite(nodes);
  7076. }
  7077. /**
  7078. * Wrapper for linking function which converts normal linking function into a grouped
  7079. * linking function.
  7080. * @param linkFn
  7081. * @param attrStart
  7082. * @param attrEnd
  7083. * @returns {Function}
  7084. */
  7085. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  7086. return function(scope, element, attrs, controllers, transcludeFn) {
  7087. element = groupScan(element[0], attrStart, attrEnd);
  7088. return linkFn(scope, element, attrs, controllers, transcludeFn);
  7089. };
  7090. }
  7091. /**
  7092. * Once the directives have been collected, their compile functions are executed. This method
  7093. * is responsible for inlining directive templates as well as terminating the application
  7094. * of the directives if the terminal directive has been reached.
  7095. *
  7096. * @param {Array} directives Array of collected directives to execute their compile function.
  7097. * this needs to be pre-sorted by priority order.
  7098. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  7099. * @param {Object} templateAttrs The shared attribute function
  7100. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7101. * scope argument is auto-generated to the new
  7102. * child of the transcluded parent scope.
  7103. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  7104. * argument has the root jqLite array so that we can replace nodes
  7105. * on it.
  7106. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  7107. * compiling the transclusion.
  7108. * @param {Array.<Function>} preLinkFns
  7109. * @param {Array.<Function>} postLinkFns
  7110. * @param {Object} previousCompileContext Context used for previous compilation of the current
  7111. * node
  7112. * @returns {Function} linkFn
  7113. */
  7114. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  7115. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  7116. previousCompileContext) {
  7117. previousCompileContext = previousCompileContext || {};
  7118. var terminalPriority = -Number.MAX_VALUE,
  7119. newScopeDirective = previousCompileContext.newScopeDirective,
  7120. controllerDirectives = previousCompileContext.controllerDirectives,
  7121. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7122. templateDirective = previousCompileContext.templateDirective,
  7123. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7124. hasTranscludeDirective = false,
  7125. hasTemplate = false,
  7126. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7127. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7128. directive,
  7129. directiveName,
  7130. $template,
  7131. replaceDirective = originalReplaceDirective,
  7132. childTranscludeFn = transcludeFn,
  7133. linkFn,
  7134. directiveValue;
  7135. // executes all directives on the current element
  7136. for (var i = 0, ii = directives.length; i < ii; i++) {
  7137. directive = directives[i];
  7138. var attrStart = directive.$$start;
  7139. var attrEnd = directive.$$end;
  7140. // collect multiblock sections
  7141. if (attrStart) {
  7142. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7143. }
  7144. $template = undefined;
  7145. if (terminalPriority > directive.priority) {
  7146. break; // prevent further processing of directives
  7147. }
  7148. if (directiveValue = directive.scope) {
  7149. // skip the check for directives with async templates, we'll check the derived sync
  7150. // directive when the template arrives
  7151. if (!directive.templateUrl) {
  7152. if (isObject(directiveValue)) {
  7153. // This directive is trying to add an isolated scope.
  7154. // Check that there is no scope of any kind already
  7155. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7156. directive, $compileNode);
  7157. newIsolateScopeDirective = directive;
  7158. } else {
  7159. // This directive is trying to add a child scope.
  7160. // Check that there is no isolated scope already
  7161. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7162. $compileNode);
  7163. }
  7164. }
  7165. newScopeDirective = newScopeDirective || directive;
  7166. }
  7167. directiveName = directive.name;
  7168. if (!directive.templateUrl && directive.controller) {
  7169. directiveValue = directive.controller;
  7170. controllerDirectives = controllerDirectives || createMap();
  7171. assertNoDuplicate("'" + directiveName + "' controller",
  7172. controllerDirectives[directiveName], directive, $compileNode);
  7173. controllerDirectives[directiveName] = directive;
  7174. }
  7175. if (directiveValue = directive.transclude) {
  7176. hasTranscludeDirective = true;
  7177. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  7178. // This option should only be used by directives that know how to safely handle element transclusion,
  7179. // where the transcluded nodes are added or replaced after linking.
  7180. if (!directive.$$tlb) {
  7181. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  7182. nonTlbTranscludeDirective = directive;
  7183. }
  7184. if (directiveValue == 'element') {
  7185. hasElementTranscludeDirective = true;
  7186. terminalPriority = directive.priority;
  7187. $template = $compileNode;
  7188. $compileNode = templateAttrs.$$element =
  7189. jqLite(document.createComment(' ' + directiveName + ': ' +
  7190. templateAttrs[directiveName] + ' '));
  7191. compileNode = $compileNode[0];
  7192. replaceWith(jqCollection, sliceArgs($template), compileNode);
  7193. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  7194. replaceDirective && replaceDirective.name, {
  7195. // Don't pass in:
  7196. // - controllerDirectives - otherwise we'll create duplicates controllers
  7197. // - newIsolateScopeDirective or templateDirective - combining templates with
  7198. // element transclusion doesn't make sense.
  7199. //
  7200. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  7201. // on the same element more than once.
  7202. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7203. });
  7204. } else {
  7205. $template = jqLite(jqLiteClone(compileNode)).contents();
  7206. $compileNode.empty(); // clear contents
  7207. childTranscludeFn = compile($template, transcludeFn);
  7208. }
  7209. }
  7210. if (directive.template) {
  7211. hasTemplate = true;
  7212. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7213. templateDirective = directive;
  7214. directiveValue = (isFunction(directive.template))
  7215. ? directive.template($compileNode, templateAttrs)
  7216. : directive.template;
  7217. directiveValue = denormalizeTemplate(directiveValue);
  7218. if (directive.replace) {
  7219. replaceDirective = directive;
  7220. if (jqLiteIsTextNode(directiveValue)) {
  7221. $template = [];
  7222. } else {
  7223. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  7224. }
  7225. compileNode = $template[0];
  7226. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7227. throw $compileMinErr('tplrt',
  7228. "Template for directive '{0}' must have exactly one root element. {1}",
  7229. directiveName, '');
  7230. }
  7231. replaceWith(jqCollection, $compileNode, compileNode);
  7232. var newTemplateAttrs = {$attr: {}};
  7233. // combine directives from the original node and from the template:
  7234. // - take the array of directives for this element
  7235. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  7236. // - collect directives from the template and sort them by priority
  7237. // - combine directives as: processed + template + unprocessed
  7238. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  7239. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  7240. if (newIsolateScopeDirective) {
  7241. markDirectivesAsIsolate(templateDirectives);
  7242. }
  7243. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  7244. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  7245. ii = directives.length;
  7246. } else {
  7247. $compileNode.html(directiveValue);
  7248. }
  7249. }
  7250. if (directive.templateUrl) {
  7251. hasTemplate = true;
  7252. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7253. templateDirective = directive;
  7254. if (directive.replace) {
  7255. replaceDirective = directive;
  7256. }
  7257. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  7258. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  7259. controllerDirectives: controllerDirectives,
  7260. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  7261. newIsolateScopeDirective: newIsolateScopeDirective,
  7262. templateDirective: templateDirective,
  7263. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7264. });
  7265. ii = directives.length;
  7266. } else if (directive.compile) {
  7267. try {
  7268. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  7269. if (isFunction(linkFn)) {
  7270. addLinkFns(null, linkFn, attrStart, attrEnd);
  7271. } else if (linkFn) {
  7272. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  7273. }
  7274. } catch (e) {
  7275. $exceptionHandler(e, startingTag($compileNode));
  7276. }
  7277. }
  7278. if (directive.terminal) {
  7279. nodeLinkFn.terminal = true;
  7280. terminalPriority = Math.max(terminalPriority, directive.priority);
  7281. }
  7282. }
  7283. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  7284. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  7285. nodeLinkFn.templateOnThisElement = hasTemplate;
  7286. nodeLinkFn.transclude = childTranscludeFn;
  7287. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  7288. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  7289. return nodeLinkFn;
  7290. ////////////////////
  7291. function addLinkFns(pre, post, attrStart, attrEnd) {
  7292. if (pre) {
  7293. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  7294. pre.require = directive.require;
  7295. pre.directiveName = directiveName;
  7296. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7297. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  7298. }
  7299. preLinkFns.push(pre);
  7300. }
  7301. if (post) {
  7302. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  7303. post.require = directive.require;
  7304. post.directiveName = directiveName;
  7305. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7306. post = cloneAndAnnotateFn(post, {isolateScope: true});
  7307. }
  7308. postLinkFns.push(post);
  7309. }
  7310. }
  7311. function getControllers(directiveName, require, $element, elementControllers) {
  7312. var value;
  7313. if (isString(require)) {
  7314. var match = require.match(REQUIRE_PREFIX_REGEXP);
  7315. var name = require.substring(match[0].length);
  7316. var inheritType = match[1] || match[3];
  7317. var optional = match[2] === '?';
  7318. //If only parents then start at the parent element
  7319. if (inheritType === '^^') {
  7320. $element = $element.parent();
  7321. //Otherwise attempt getting the controller from elementControllers in case
  7322. //the element is transcluded (and has no data) and to avoid .data if possible
  7323. } else {
  7324. value = elementControllers && elementControllers[name];
  7325. value = value && value.instance;
  7326. }
  7327. if (!value) {
  7328. var dataName = '$' + name + 'Controller';
  7329. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  7330. }
  7331. if (!value && !optional) {
  7332. throw $compileMinErr('ctreq',
  7333. "Controller '{0}', required by directive '{1}', can't be found!",
  7334. name, directiveName);
  7335. }
  7336. } else if (isArray(require)) {
  7337. value = [];
  7338. for (var i = 0, ii = require.length; i < ii; i++) {
  7339. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  7340. }
  7341. }
  7342. return value || null;
  7343. }
  7344. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
  7345. var elementControllers = createMap();
  7346. for (var controllerKey in controllerDirectives) {
  7347. var directive = controllerDirectives[controllerKey];
  7348. var locals = {
  7349. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  7350. $element: $element,
  7351. $attrs: attrs,
  7352. $transclude: transcludeFn
  7353. };
  7354. var controller = directive.controller;
  7355. if (controller == '@') {
  7356. controller = attrs[directive.name];
  7357. }
  7358. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  7359. // For directives with element transclusion the element is a comment,
  7360. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  7361. // clean up (http://bugs.jquery.com/ticket/8335).
  7362. // Instead, we save the controllers for the element in a local hash and attach to .data
  7363. // later, once we have the actual element.
  7364. elementControllers[directive.name] = controllerInstance;
  7365. if (!hasElementTranscludeDirective) {
  7366. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  7367. }
  7368. }
  7369. return elementControllers;
  7370. }
  7371. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,
  7372. thisLinkFn) {
  7373. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  7374. attrs;
  7375. if (compileNode === linkNode) {
  7376. attrs = templateAttrs;
  7377. $element = templateAttrs.$$element;
  7378. } else {
  7379. $element = jqLite(linkNode);
  7380. attrs = new Attributes($element, templateAttrs);
  7381. }
  7382. if (newIsolateScopeDirective) {
  7383. isolateScope = scope.$new(true);
  7384. }
  7385. if (boundTranscludeFn) {
  7386. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  7387. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  7388. transcludeFn = controllersBoundTransclude;
  7389. transcludeFn.$$boundTransclude = boundTranscludeFn;
  7390. }
  7391. if (controllerDirectives) {
  7392. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
  7393. }
  7394. if (newIsolateScopeDirective) {
  7395. // Initialize isolate scope bindings for new isolate scope directive.
  7396. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  7397. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  7398. compile.$$addScopeClass($element, true);
  7399. isolateScope.$$isolateBindings =
  7400. newIsolateScopeDirective.$$isolateBindings;
  7401. initializeDirectiveBindings(scope, attrs, isolateScope,
  7402. isolateScope.$$isolateBindings,
  7403. newIsolateScopeDirective, isolateScope);
  7404. }
  7405. if (elementControllers) {
  7406. // Initialize bindToController bindings for new/isolate scopes
  7407. var scopeDirective = newIsolateScopeDirective || newScopeDirective;
  7408. var bindings;
  7409. var controllerForBindings;
  7410. if (scopeDirective && elementControllers[scopeDirective.name]) {
  7411. bindings = scopeDirective.$$bindings.bindToController;
  7412. controller = elementControllers[scopeDirective.name];
  7413. if (controller && controller.identifier && bindings) {
  7414. controllerForBindings = controller;
  7415. thisLinkFn.$$destroyBindings =
  7416. initializeDirectiveBindings(scope, attrs, controller.instance,
  7417. bindings, scopeDirective);
  7418. }
  7419. }
  7420. for (i in elementControllers) {
  7421. controller = elementControllers[i];
  7422. var controllerResult = controller();
  7423. if (controllerResult !== controller.instance) {
  7424. // If the controller constructor has a return value, overwrite the instance
  7425. // from setupControllers and update the element data
  7426. controller.instance = controllerResult;
  7427. $element.data('$' + i + 'Controller', controllerResult);
  7428. if (controller === controllerForBindings) {
  7429. // Remove and re-install bindToController bindings
  7430. thisLinkFn.$$destroyBindings();
  7431. thisLinkFn.$$destroyBindings =
  7432. initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);
  7433. }
  7434. }
  7435. }
  7436. }
  7437. // PRELINKING
  7438. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  7439. linkFn = preLinkFns[i];
  7440. invokeLinkFn(linkFn,
  7441. linkFn.isolateScope ? isolateScope : scope,
  7442. $element,
  7443. attrs,
  7444. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7445. transcludeFn
  7446. );
  7447. }
  7448. // RECURSION
  7449. // We only pass the isolate scope, if the isolate directive has a template,
  7450. // otherwise the child elements do not belong to the isolate directive.
  7451. var scopeToChild = scope;
  7452. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  7453. scopeToChild = isolateScope;
  7454. }
  7455. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  7456. // POSTLINKING
  7457. for (i = postLinkFns.length - 1; i >= 0; i--) {
  7458. linkFn = postLinkFns[i];
  7459. invokeLinkFn(linkFn,
  7460. linkFn.isolateScope ? isolateScope : scope,
  7461. $element,
  7462. attrs,
  7463. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7464. transcludeFn
  7465. );
  7466. }
  7467. // This is the function that is injected as `$transclude`.
  7468. // Note: all arguments are optional!
  7469. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  7470. var transcludeControllers;
  7471. // No scope passed in:
  7472. if (!isScope(scope)) {
  7473. futureParentElement = cloneAttachFn;
  7474. cloneAttachFn = scope;
  7475. scope = undefined;
  7476. }
  7477. if (hasElementTranscludeDirective) {
  7478. transcludeControllers = elementControllers;
  7479. }
  7480. if (!futureParentElement) {
  7481. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7482. }
  7483. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7484. }
  7485. }
  7486. }
  7487. function markDirectivesAsIsolate(directives) {
  7488. // mark all directives as needing isolate scope.
  7489. for (var j = 0, jj = directives.length; j < jj; j++) {
  7490. directives[j] = inherit(directives[j], {$$isolateScope: true});
  7491. }
  7492. }
  7493. /**
  7494. * looks up the directive and decorates it with exception handling and proper parameters. We
  7495. * call this the boundDirective.
  7496. *
  7497. * @param {string} name name of the directive to look up.
  7498. * @param {string} location The directive must be found in specific format.
  7499. * String containing any of theses characters:
  7500. *
  7501. * * `E`: element name
  7502. * * `A': attribute
  7503. * * `C`: class
  7504. * * `M`: comment
  7505. * @returns {boolean} true if directive was added.
  7506. */
  7507. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7508. endAttrName) {
  7509. if (name === ignoreDirective) return null;
  7510. var match = null;
  7511. if (hasDirectives.hasOwnProperty(name)) {
  7512. for (var directive, directives = $injector.get(name + Suffix),
  7513. i = 0, ii = directives.length; i < ii; i++) {
  7514. try {
  7515. directive = directives[i];
  7516. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  7517. directive.restrict.indexOf(location) != -1) {
  7518. if (startAttrName) {
  7519. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7520. }
  7521. tDirectives.push(directive);
  7522. match = directive;
  7523. }
  7524. } catch (e) { $exceptionHandler(e); }
  7525. }
  7526. }
  7527. return match;
  7528. }
  7529. /**
  7530. * looks up the directive and returns true if it is a multi-element directive,
  7531. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7532. * together.
  7533. *
  7534. * @param {string} name name of the directive to look up.
  7535. * @returns true if directive was registered as multi-element.
  7536. */
  7537. function directiveIsMultiElement(name) {
  7538. if (hasDirectives.hasOwnProperty(name)) {
  7539. for (var directive, directives = $injector.get(name + Suffix),
  7540. i = 0, ii = directives.length; i < ii; i++) {
  7541. directive = directives[i];
  7542. if (directive.multiElement) {
  7543. return true;
  7544. }
  7545. }
  7546. }
  7547. return false;
  7548. }
  7549. /**
  7550. * When the element is replaced with HTML template then the new attributes
  7551. * on the template need to be merged with the existing attributes in the DOM.
  7552. * The desired effect is to have both of the attributes present.
  7553. *
  7554. * @param {object} dst destination attributes (original DOM)
  7555. * @param {object} src source attributes (from the directive template)
  7556. */
  7557. function mergeTemplateAttributes(dst, src) {
  7558. var srcAttr = src.$attr,
  7559. dstAttr = dst.$attr,
  7560. $element = dst.$$element;
  7561. // reapply the old attributes to the new element
  7562. forEach(dst, function(value, key) {
  7563. if (key.charAt(0) != '$') {
  7564. if (src[key] && src[key] !== value) {
  7565. value += (key === 'style' ? ';' : ' ') + src[key];
  7566. }
  7567. dst.$set(key, value, true, srcAttr[key]);
  7568. }
  7569. });
  7570. // copy the new attributes on the old attrs object
  7571. forEach(src, function(value, key) {
  7572. if (key == 'class') {
  7573. safeAddClass($element, value);
  7574. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7575. } else if (key == 'style') {
  7576. $element.attr('style', $element.attr('style') + ';' + value);
  7577. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7578. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7579. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7580. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7581. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7582. dst[key] = value;
  7583. dstAttr[key] = srcAttr[key];
  7584. }
  7585. });
  7586. }
  7587. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7588. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7589. var linkQueue = [],
  7590. afterTemplateNodeLinkFn,
  7591. afterTemplateChildLinkFn,
  7592. beforeTemplateCompileNode = $compileNode[0],
  7593. origAsyncDirective = directives.shift(),
  7594. derivedSyncDirective = inherit(origAsyncDirective, {
  7595. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7596. }),
  7597. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7598. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7599. : origAsyncDirective.templateUrl,
  7600. templateNamespace = origAsyncDirective.templateNamespace;
  7601. $compileNode.empty();
  7602. $templateRequest(templateUrl)
  7603. .then(function(content) {
  7604. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7605. content = denormalizeTemplate(content);
  7606. if (origAsyncDirective.replace) {
  7607. if (jqLiteIsTextNode(content)) {
  7608. $template = [];
  7609. } else {
  7610. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7611. }
  7612. compileNode = $template[0];
  7613. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7614. throw $compileMinErr('tplrt',
  7615. "Template for directive '{0}' must have exactly one root element. {1}",
  7616. origAsyncDirective.name, templateUrl);
  7617. }
  7618. tempTemplateAttrs = {$attr: {}};
  7619. replaceWith($rootElement, $compileNode, compileNode);
  7620. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7621. if (isObject(origAsyncDirective.scope)) {
  7622. markDirectivesAsIsolate(templateDirectives);
  7623. }
  7624. directives = templateDirectives.concat(directives);
  7625. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7626. } else {
  7627. compileNode = beforeTemplateCompileNode;
  7628. $compileNode.html(content);
  7629. }
  7630. directives.unshift(derivedSyncDirective);
  7631. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7632. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7633. previousCompileContext);
  7634. forEach($rootElement, function(node, i) {
  7635. if (node == compileNode) {
  7636. $rootElement[i] = $compileNode[0];
  7637. }
  7638. });
  7639. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7640. while (linkQueue.length) {
  7641. var scope = linkQueue.shift(),
  7642. beforeTemplateLinkNode = linkQueue.shift(),
  7643. linkRootElement = linkQueue.shift(),
  7644. boundTranscludeFn = linkQueue.shift(),
  7645. linkNode = $compileNode[0];
  7646. if (scope.$$destroyed) continue;
  7647. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7648. var oldClasses = beforeTemplateLinkNode.className;
  7649. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7650. origAsyncDirective.replace)) {
  7651. // it was cloned therefore we have to clone as well.
  7652. linkNode = jqLiteClone(compileNode);
  7653. }
  7654. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7655. // Copy in CSS classes from original node
  7656. safeAddClass(jqLite(linkNode), oldClasses);
  7657. }
  7658. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7659. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7660. } else {
  7661. childBoundTranscludeFn = boundTranscludeFn;
  7662. }
  7663. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7664. childBoundTranscludeFn, afterTemplateNodeLinkFn);
  7665. }
  7666. linkQueue = null;
  7667. });
  7668. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7669. var childBoundTranscludeFn = boundTranscludeFn;
  7670. if (scope.$$destroyed) return;
  7671. if (linkQueue) {
  7672. linkQueue.push(scope,
  7673. node,
  7674. rootElement,
  7675. childBoundTranscludeFn);
  7676. } else {
  7677. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7678. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7679. }
  7680. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,
  7681. afterTemplateNodeLinkFn);
  7682. }
  7683. };
  7684. }
  7685. /**
  7686. * Sorting function for bound directives.
  7687. */
  7688. function byPriority(a, b) {
  7689. var diff = b.priority - a.priority;
  7690. if (diff !== 0) return diff;
  7691. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7692. return a.index - b.index;
  7693. }
  7694. function assertNoDuplicate(what, previousDirective, directive, element) {
  7695. function wrapModuleNameIfDefined(moduleName) {
  7696. return moduleName ?
  7697. (' (module: ' + moduleName + ')') :
  7698. '';
  7699. }
  7700. if (previousDirective) {
  7701. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  7702. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  7703. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  7704. }
  7705. }
  7706. function addTextInterpolateDirective(directives, text) {
  7707. var interpolateFn = $interpolate(text, true);
  7708. if (interpolateFn) {
  7709. directives.push({
  7710. priority: 0,
  7711. compile: function textInterpolateCompileFn(templateNode) {
  7712. var templateNodeParent = templateNode.parent(),
  7713. hasCompileParent = !!templateNodeParent.length;
  7714. // When transcluding a template that has bindings in the root
  7715. // we don't have a parent and thus need to add the class during linking fn.
  7716. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7717. return function textInterpolateLinkFn(scope, node) {
  7718. var parent = node.parent();
  7719. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7720. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7721. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7722. node[0].nodeValue = value;
  7723. });
  7724. };
  7725. }
  7726. });
  7727. }
  7728. }
  7729. function wrapTemplate(type, template) {
  7730. type = lowercase(type || 'html');
  7731. switch (type) {
  7732. case 'svg':
  7733. case 'math':
  7734. var wrapper = document.createElement('div');
  7735. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7736. return wrapper.childNodes[0].childNodes;
  7737. default:
  7738. return template;
  7739. }
  7740. }
  7741. function getTrustedContext(node, attrNormalizedName) {
  7742. if (attrNormalizedName == "srcdoc") {
  7743. return $sce.HTML;
  7744. }
  7745. var tag = nodeName_(node);
  7746. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7747. if (attrNormalizedName == "xlinkHref" ||
  7748. (tag == "form" && attrNormalizedName == "action") ||
  7749. (tag != "img" && (attrNormalizedName == "src" ||
  7750. attrNormalizedName == "ngSrc"))) {
  7751. return $sce.RESOURCE_URL;
  7752. }
  7753. }
  7754. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7755. var trustedContext = getTrustedContext(node, name);
  7756. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7757. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7758. // no interpolation found -> ignore
  7759. if (!interpolateFn) return;
  7760. if (name === "multiple" && nodeName_(node) === "select") {
  7761. throw $compileMinErr("selmulti",
  7762. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7763. startingTag(node));
  7764. }
  7765. directives.push({
  7766. priority: 100,
  7767. compile: function() {
  7768. return {
  7769. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7770. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7771. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7772. throw $compileMinErr('nodomevents',
  7773. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7774. "ng- versions (such as ng-click instead of onclick) instead.");
  7775. }
  7776. // If the attribute has changed since last $interpolate()ed
  7777. var newValue = attr[name];
  7778. if (newValue !== value) {
  7779. // we need to interpolate again since the attribute value has been updated
  7780. // (e.g. by another directive's compile function)
  7781. // ensure unset/empty values make interpolateFn falsy
  7782. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7783. value = newValue;
  7784. }
  7785. // if attribute was updated so that there is no interpolation going on we don't want to
  7786. // register any observers
  7787. if (!interpolateFn) return;
  7788. // initialize attr object so that it's ready in case we need the value for isolate
  7789. // scope initialization, otherwise the value would not be available from isolate
  7790. // directive's linking fn during linking phase
  7791. attr[name] = interpolateFn(scope);
  7792. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7793. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7794. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7795. //special case for class attribute addition + removal
  7796. //so that class changes can tap into the animation
  7797. //hooks provided by the $animate service. Be sure to
  7798. //skip animations when the first digest occurs (when
  7799. //both the new and the old values are the same) since
  7800. //the CSS classes are the non-interpolated values
  7801. if (name === 'class' && newValue != oldValue) {
  7802. attr.$updateClass(newValue, oldValue);
  7803. } else {
  7804. attr.$set(name, newValue);
  7805. }
  7806. });
  7807. }
  7808. };
  7809. }
  7810. });
  7811. }
  7812. /**
  7813. * This is a special jqLite.replaceWith, which can replace items which
  7814. * have no parents, provided that the containing jqLite collection is provided.
  7815. *
  7816. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7817. * in the root of the tree.
  7818. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7819. * the shell, but replace its DOM node reference.
  7820. * @param {Node} newNode The new DOM node.
  7821. */
  7822. function replaceWith($rootElement, elementsToRemove, newNode) {
  7823. var firstElementToRemove = elementsToRemove[0],
  7824. removeCount = elementsToRemove.length,
  7825. parent = firstElementToRemove.parentNode,
  7826. i, ii;
  7827. if ($rootElement) {
  7828. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7829. if ($rootElement[i] == firstElementToRemove) {
  7830. $rootElement[i++] = newNode;
  7831. for (var j = i, j2 = j + removeCount - 1,
  7832. jj = $rootElement.length;
  7833. j < jj; j++, j2++) {
  7834. if (j2 < jj) {
  7835. $rootElement[j] = $rootElement[j2];
  7836. } else {
  7837. delete $rootElement[j];
  7838. }
  7839. }
  7840. $rootElement.length -= removeCount - 1;
  7841. // If the replaced element is also the jQuery .context then replace it
  7842. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7843. // http://api.jquery.com/context/
  7844. if ($rootElement.context === firstElementToRemove) {
  7845. $rootElement.context = newNode;
  7846. }
  7847. break;
  7848. }
  7849. }
  7850. }
  7851. if (parent) {
  7852. parent.replaceChild(newNode, firstElementToRemove);
  7853. }
  7854. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7855. var fragment = document.createDocumentFragment();
  7856. fragment.appendChild(firstElementToRemove);
  7857. if (jqLite.hasData(firstElementToRemove)) {
  7858. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7859. // data here because there's no public interface in jQuery to do that and copying over
  7860. // event listeners (which is the main use of private data) wouldn't work anyway.
  7861. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7862. // Remove data of the replaced element. We cannot just call .remove()
  7863. // on the element it since that would deallocate scope that is needed
  7864. // for the new node. Instead, remove the data "manually".
  7865. if (!jQuery) {
  7866. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7867. } else {
  7868. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7869. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7870. // the scope to be trashed and we do need the very same scope to work with the new
  7871. // element. However, we cannot just cache the non-patched version and use it here as
  7872. // that would break if another library patches the method after Angular does (one
  7873. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7874. // skipped this one time.
  7875. skipDestroyOnNextJQueryCleanData = true;
  7876. jQuery.cleanData([firstElementToRemove]);
  7877. }
  7878. }
  7879. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7880. var element = elementsToRemove[k];
  7881. jqLite(element).remove(); // must do this way to clean up expando
  7882. fragment.appendChild(element);
  7883. delete elementsToRemove[k];
  7884. }
  7885. elementsToRemove[0] = newNode;
  7886. elementsToRemove.length = 1;
  7887. }
  7888. function cloneAndAnnotateFn(fn, annotation) {
  7889. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7890. }
  7891. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7892. try {
  7893. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7894. } catch (e) {
  7895. $exceptionHandler(e, startingTag($element));
  7896. }
  7897. }
  7898. // Set up $watches for isolate scope and controller bindings. This process
  7899. // only occurs for isolate scopes and new scopes with controllerAs.
  7900. function initializeDirectiveBindings(scope, attrs, destination, bindings,
  7901. directive, newScope) {
  7902. var onNewScopeDestroyed;
  7903. forEach(bindings, function(definition, scopeName) {
  7904. var attrName = definition.attrName,
  7905. optional = definition.optional,
  7906. mode = definition.mode, // @, =, or &
  7907. lastValue,
  7908. parentGet, parentSet, compare;
  7909. switch (mode) {
  7910. case '@':
  7911. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  7912. destination[scopeName] = attrs[attrName] = void 0;
  7913. }
  7914. attrs.$observe(attrName, function(value) {
  7915. if (isString(value)) {
  7916. destination[scopeName] = value;
  7917. }
  7918. });
  7919. attrs.$$observers[attrName].$$scope = scope;
  7920. if (isString(attrs[attrName])) {
  7921. // If the attribute has been provided then we trigger an interpolation to ensure
  7922. // the value is there for use in the link fn
  7923. destination[scopeName] = $interpolate(attrs[attrName])(scope);
  7924. }
  7925. break;
  7926. case '=':
  7927. if (!hasOwnProperty.call(attrs, attrName)) {
  7928. if (optional) break;
  7929. attrs[attrName] = void 0;
  7930. }
  7931. if (optional && !attrs[attrName]) break;
  7932. parentGet = $parse(attrs[attrName]);
  7933. if (parentGet.literal) {
  7934. compare = equals;
  7935. } else {
  7936. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  7937. }
  7938. parentSet = parentGet.assign || function() {
  7939. // reset the change, or we will throw this exception on every $digest
  7940. lastValue = destination[scopeName] = parentGet(scope);
  7941. throw $compileMinErr('nonassign',
  7942. "Expression '{0}' used with directive '{1}' is non-assignable!",
  7943. attrs[attrName], directive.name);
  7944. };
  7945. lastValue = destination[scopeName] = parentGet(scope);
  7946. var parentValueWatch = function parentValueWatch(parentValue) {
  7947. if (!compare(parentValue, destination[scopeName])) {
  7948. // we are out of sync and need to copy
  7949. if (!compare(parentValue, lastValue)) {
  7950. // parent changed and it has precedence
  7951. destination[scopeName] = parentValue;
  7952. } else {
  7953. // if the parent can be assigned then do so
  7954. parentSet(scope, parentValue = destination[scopeName]);
  7955. }
  7956. }
  7957. return lastValue = parentValue;
  7958. };
  7959. parentValueWatch.$stateful = true;
  7960. var unwatch;
  7961. if (definition.collection) {
  7962. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  7963. } else {
  7964. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  7965. }
  7966. onNewScopeDestroyed = (onNewScopeDestroyed || []);
  7967. onNewScopeDestroyed.push(unwatch);
  7968. break;
  7969. case '&':
  7970. // Don't assign Object.prototype method to scope
  7971. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  7972. // Don't assign noop to destination if expression is not valid
  7973. if (parentGet === noop && optional) break;
  7974. destination[scopeName] = function(locals) {
  7975. return parentGet(scope, locals);
  7976. };
  7977. break;
  7978. }
  7979. });
  7980. var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {
  7981. for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {
  7982. onNewScopeDestroyed[i]();
  7983. }
  7984. } : noop;
  7985. if (newScope && destroyBindings !== noop) {
  7986. newScope.$on('$destroy', destroyBindings);
  7987. return noop;
  7988. }
  7989. return destroyBindings;
  7990. }
  7991. }];
  7992. }
  7993. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7994. /**
  7995. * Converts all accepted directives format into proper directive name.
  7996. * @param name Name to normalize
  7997. */
  7998. function directiveNormalize(name) {
  7999. return camelCase(name.replace(PREFIX_REGEXP, ''));
  8000. }
  8001. /**
  8002. * @ngdoc type
  8003. * @name $compile.directive.Attributes
  8004. *
  8005. * @description
  8006. * A shared object between directive compile / linking functions which contains normalized DOM
  8007. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  8008. * needed since all of these are treated as equivalent in Angular:
  8009. *
  8010. * ```
  8011. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  8012. * ```
  8013. */
  8014. /**
  8015. * @ngdoc property
  8016. * @name $compile.directive.Attributes#$attr
  8017. *
  8018. * @description
  8019. * A map of DOM element attribute names to the normalized name. This is
  8020. * needed to do reverse lookup from normalized name back to actual name.
  8021. */
  8022. /**
  8023. * @ngdoc method
  8024. * @name $compile.directive.Attributes#$set
  8025. * @kind function
  8026. *
  8027. * @description
  8028. * Set DOM element attribute value.
  8029. *
  8030. *
  8031. * @param {string} name Normalized element attribute name of the property to modify. The name is
  8032. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  8033. * property to the original name.
  8034. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  8035. */
  8036. /**
  8037. * Closure compiler type information
  8038. */
  8039. function nodesetLinkingFn(
  8040. /* angular.Scope */ scope,
  8041. /* NodeList */ nodeList,
  8042. /* Element */ rootElement,
  8043. /* function(Function) */ boundTranscludeFn
  8044. ) {}
  8045. function directiveLinkingFn(
  8046. /* nodesetLinkingFn */ nodesetLinkingFn,
  8047. /* angular.Scope */ scope,
  8048. /* Node */ node,
  8049. /* Element */ rootElement,
  8050. /* function(Function) */ boundTranscludeFn
  8051. ) {}
  8052. function tokenDifference(str1, str2) {
  8053. var values = '',
  8054. tokens1 = str1.split(/\s+/),
  8055. tokens2 = str2.split(/\s+/);
  8056. outer:
  8057. for (var i = 0; i < tokens1.length; i++) {
  8058. var token = tokens1[i];
  8059. for (var j = 0; j < tokens2.length; j++) {
  8060. if (token == tokens2[j]) continue outer;
  8061. }
  8062. values += (values.length > 0 ? ' ' : '') + token;
  8063. }
  8064. return values;
  8065. }
  8066. function removeComments(jqNodes) {
  8067. jqNodes = jqLite(jqNodes);
  8068. var i = jqNodes.length;
  8069. if (i <= 1) {
  8070. return jqNodes;
  8071. }
  8072. while (i--) {
  8073. var node = jqNodes[i];
  8074. if (node.nodeType === NODE_TYPE_COMMENT) {
  8075. splice.call(jqNodes, i, 1);
  8076. }
  8077. }
  8078. return jqNodes;
  8079. }
  8080. var $controllerMinErr = minErr('$controller');
  8081. var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  8082. function identifierForController(controller, ident) {
  8083. if (ident && isString(ident)) return ident;
  8084. if (isString(controller)) {
  8085. var match = CNTRL_REG.exec(controller);
  8086. if (match) return match[3];
  8087. }
  8088. }
  8089. /**
  8090. * @ngdoc provider
  8091. * @name $controllerProvider
  8092. * @description
  8093. * The {@link ng.$controller $controller service} is used by Angular to create new
  8094. * controllers.
  8095. *
  8096. * This provider allows controller registration via the
  8097. * {@link ng.$controllerProvider#register register} method.
  8098. */
  8099. function $ControllerProvider() {
  8100. var controllers = {},
  8101. globals = false;
  8102. /**
  8103. * @ngdoc method
  8104. * @name $controllerProvider#register
  8105. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  8106. * the names and the values are the constructors.
  8107. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  8108. * annotations in the array notation).
  8109. */
  8110. this.register = function(name, constructor) {
  8111. assertNotHasOwnProperty(name, 'controller');
  8112. if (isObject(name)) {
  8113. extend(controllers, name);
  8114. } else {
  8115. controllers[name] = constructor;
  8116. }
  8117. };
  8118. /**
  8119. * @ngdoc method
  8120. * @name $controllerProvider#allowGlobals
  8121. * @description If called, allows `$controller` to find controller constructors on `window`
  8122. */
  8123. this.allowGlobals = function() {
  8124. globals = true;
  8125. };
  8126. this.$get = ['$injector', '$window', function($injector, $window) {
  8127. /**
  8128. * @ngdoc service
  8129. * @name $controller
  8130. * @requires $injector
  8131. *
  8132. * @param {Function|string} constructor If called with a function then it's considered to be the
  8133. * controller constructor function. Otherwise it's considered to be a string which is used
  8134. * to retrieve the controller constructor using the following steps:
  8135. *
  8136. * * check if a controller with given name is registered via `$controllerProvider`
  8137. * * check if evaluating the string on the current scope returns a constructor
  8138. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  8139. * `window` object (not recommended)
  8140. *
  8141. * The string can use the `controller as property` syntax, where the controller instance is published
  8142. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  8143. * to work correctly.
  8144. *
  8145. * @param {Object} locals Injection locals for Controller.
  8146. * @return {Object} Instance of given controller.
  8147. *
  8148. * @description
  8149. * `$controller` service is responsible for instantiating controllers.
  8150. *
  8151. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  8152. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  8153. */
  8154. return function(expression, locals, later, ident) {
  8155. // PRIVATE API:
  8156. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  8157. // If true, $controller will allocate the object with the correct
  8158. // prototype chain, but will not invoke the controller until a returned
  8159. // callback is invoked.
  8160. // param `ident` --- An optional label which overrides the label parsed from the controller
  8161. // expression, if any.
  8162. var instance, match, constructor, identifier;
  8163. later = later === true;
  8164. if (ident && isString(ident)) {
  8165. identifier = ident;
  8166. }
  8167. if (isString(expression)) {
  8168. match = expression.match(CNTRL_REG);
  8169. if (!match) {
  8170. throw $controllerMinErr('ctrlfmt',
  8171. "Badly formed controller string '{0}'. " +
  8172. "Must match `__name__ as __id__` or `__name__`.", expression);
  8173. }
  8174. constructor = match[1],
  8175. identifier = identifier || match[3];
  8176. expression = controllers.hasOwnProperty(constructor)
  8177. ? controllers[constructor]
  8178. : getter(locals.$scope, constructor, true) ||
  8179. (globals ? getter($window, constructor, true) : undefined);
  8180. assertArgFn(expression, constructor, true);
  8181. }
  8182. if (later) {
  8183. // Instantiate controller later:
  8184. // This machinery is used to create an instance of the object before calling the
  8185. // controller's constructor itself.
  8186. //
  8187. // This allows properties to be added to the controller before the constructor is
  8188. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  8189. //
  8190. // This feature is not intended for use by applications, and is thus not documented
  8191. // publicly.
  8192. // Object creation: http://jsperf.com/create-constructor/2
  8193. var controllerPrototype = (isArray(expression) ?
  8194. expression[expression.length - 1] : expression).prototype;
  8195. instance = Object.create(controllerPrototype || null);
  8196. if (identifier) {
  8197. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8198. }
  8199. var instantiate;
  8200. return instantiate = extend(function() {
  8201. var result = $injector.invoke(expression, instance, locals, constructor);
  8202. if (result !== instance && (isObject(result) || isFunction(result))) {
  8203. instance = result;
  8204. if (identifier) {
  8205. // If result changed, re-assign controllerAs value to scope.
  8206. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8207. }
  8208. }
  8209. return instance;
  8210. }, {
  8211. instance: instance,
  8212. identifier: identifier
  8213. });
  8214. }
  8215. instance = $injector.instantiate(expression, locals, constructor);
  8216. if (identifier) {
  8217. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8218. }
  8219. return instance;
  8220. };
  8221. function addIdentifier(locals, identifier, instance, name) {
  8222. if (!(locals && isObject(locals.$scope))) {
  8223. throw minErr('$controller')('noscp',
  8224. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  8225. name, identifier);
  8226. }
  8227. locals.$scope[identifier] = instance;
  8228. }
  8229. }];
  8230. }
  8231. /**
  8232. * @ngdoc service
  8233. * @name $document
  8234. * @requires $window
  8235. *
  8236. * @description
  8237. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  8238. *
  8239. * @example
  8240. <example module="documentExample">
  8241. <file name="index.html">
  8242. <div ng-controller="ExampleController">
  8243. <p>$document title: <b ng-bind="title"></b></p>
  8244. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  8245. </div>
  8246. </file>
  8247. <file name="script.js">
  8248. angular.module('documentExample', [])
  8249. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  8250. $scope.title = $document[0].title;
  8251. $scope.windowTitle = angular.element(window.document)[0].title;
  8252. }]);
  8253. </file>
  8254. </example>
  8255. */
  8256. function $DocumentProvider() {
  8257. this.$get = ['$window', function(window) {
  8258. return jqLite(window.document);
  8259. }];
  8260. }
  8261. /**
  8262. * @ngdoc service
  8263. * @name $exceptionHandler
  8264. * @requires ng.$log
  8265. *
  8266. * @description
  8267. * Any uncaught exception in angular expressions is delegated to this service.
  8268. * The default implementation simply delegates to `$log.error` which logs it into
  8269. * the browser console.
  8270. *
  8271. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  8272. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  8273. *
  8274. * ## Example:
  8275. *
  8276. * ```js
  8277. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  8278. * return function(exception, cause) {
  8279. * exception.message += ' (caused by "' + cause + '")';
  8280. * throw exception;
  8281. * };
  8282. * });
  8283. * ```
  8284. *
  8285. * This example will override the normal action of `$exceptionHandler`, to make angular
  8286. * exceptions fail hard when they happen, instead of just logging to the console.
  8287. *
  8288. * <hr />
  8289. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  8290. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  8291. * (unless executed during a digest).
  8292. *
  8293. * If you wish, you can manually delegate exceptions, e.g.
  8294. * `try { ... } catch(e) { $exceptionHandler(e); }`
  8295. *
  8296. * @param {Error} exception Exception associated with the error.
  8297. * @param {string=} cause optional information about the context in which
  8298. * the error was thrown.
  8299. *
  8300. */
  8301. function $ExceptionHandlerProvider() {
  8302. this.$get = ['$log', function($log) {
  8303. return function(exception, cause) {
  8304. $log.error.apply($log, arguments);
  8305. };
  8306. }];
  8307. }
  8308. var $$ForceReflowProvider = function() {
  8309. this.$get = ['$document', function($document) {
  8310. return function(domNode) {
  8311. //the line below will force the browser to perform a repaint so
  8312. //that all the animated elements within the animation frame will
  8313. //be properly updated and drawn on screen. This is required to
  8314. //ensure that the preparation animation is properly flushed so that
  8315. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  8316. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  8317. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  8318. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  8319. if (domNode) {
  8320. if (!domNode.nodeType && domNode instanceof jqLite) {
  8321. domNode = domNode[0];
  8322. }
  8323. } else {
  8324. domNode = $document[0].body;
  8325. }
  8326. return domNode.offsetWidth + 1;
  8327. };
  8328. }];
  8329. };
  8330. var APPLICATION_JSON = 'application/json';
  8331. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  8332. var JSON_START = /^\[|^\{(?!\{)/;
  8333. var JSON_ENDS = {
  8334. '[': /]$/,
  8335. '{': /}$/
  8336. };
  8337. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  8338. var $httpMinErr = minErr('$http');
  8339. var $httpMinErrLegacyFn = function(method) {
  8340. return function() {
  8341. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  8342. };
  8343. };
  8344. function serializeValue(v) {
  8345. if (isObject(v)) {
  8346. return isDate(v) ? v.toISOString() : toJson(v);
  8347. }
  8348. return v;
  8349. }
  8350. function $HttpParamSerializerProvider() {
  8351. /**
  8352. * @ngdoc service
  8353. * @name $httpParamSerializer
  8354. * @description
  8355. *
  8356. * Default {@link $http `$http`} params serializer that converts objects to strings
  8357. * according to the following rules:
  8358. *
  8359. * * `{'foo': 'bar'}` results in `foo=bar`
  8360. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  8361. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  8362. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  8363. *
  8364. * Note that serializer will sort the request parameters alphabetically.
  8365. * */
  8366. this.$get = function() {
  8367. return function ngParamSerializer(params) {
  8368. if (!params) return '';
  8369. var parts = [];
  8370. forEachSorted(params, function(value, key) {
  8371. if (value === null || isUndefined(value)) return;
  8372. if (isArray(value)) {
  8373. forEach(value, function(v, k) {
  8374. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  8375. });
  8376. } else {
  8377. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  8378. }
  8379. });
  8380. return parts.join('&');
  8381. };
  8382. };
  8383. }
  8384. function $HttpParamSerializerJQLikeProvider() {
  8385. /**
  8386. * @ngdoc service
  8387. * @name $httpParamSerializerJQLike
  8388. * @description
  8389. *
  8390. * Alternative {@link $http `$http`} params serializer that follows
  8391. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  8392. * The serializer will also sort the params alphabetically.
  8393. *
  8394. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  8395. *
  8396. * ```js
  8397. * $http({
  8398. * url: myUrl,
  8399. * method: 'GET',
  8400. * params: myParams,
  8401. * paramSerializer: '$httpParamSerializerJQLike'
  8402. * });
  8403. * ```
  8404. *
  8405. * It is also possible to set it as the default `paramSerializer` in the
  8406. * {@link $httpProvider#defaults `$httpProvider`}.
  8407. *
  8408. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  8409. * form data for submission:
  8410. *
  8411. * ```js
  8412. * .controller(function($http, $httpParamSerializerJQLike) {
  8413. * //...
  8414. *
  8415. * $http({
  8416. * url: myUrl,
  8417. * method: 'POST',
  8418. * data: $httpParamSerializerJQLike(myData),
  8419. * headers: {
  8420. * 'Content-Type': 'application/x-www-form-urlencoded'
  8421. * }
  8422. * });
  8423. *
  8424. * });
  8425. * ```
  8426. *
  8427. * */
  8428. this.$get = function() {
  8429. return function jQueryLikeParamSerializer(params) {
  8430. if (!params) return '';
  8431. var parts = [];
  8432. serialize(params, '', true);
  8433. return parts.join('&');
  8434. function serialize(toSerialize, prefix, topLevel) {
  8435. if (toSerialize === null || isUndefined(toSerialize)) return;
  8436. if (isArray(toSerialize)) {
  8437. forEach(toSerialize, function(value, index) {
  8438. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  8439. });
  8440. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  8441. forEachSorted(toSerialize, function(value, key) {
  8442. serialize(value, prefix +
  8443. (topLevel ? '' : '[') +
  8444. key +
  8445. (topLevel ? '' : ']'));
  8446. });
  8447. } else {
  8448. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  8449. }
  8450. }
  8451. };
  8452. };
  8453. }
  8454. function defaultHttpResponseTransform(data, headers) {
  8455. if (isString(data)) {
  8456. // Strip json vulnerability protection prefix and trim whitespace
  8457. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  8458. if (tempData) {
  8459. var contentType = headers('Content-Type');
  8460. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  8461. data = fromJson(tempData);
  8462. }
  8463. }
  8464. }
  8465. return data;
  8466. }
  8467. function isJsonLike(str) {
  8468. var jsonStart = str.match(JSON_START);
  8469. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  8470. }
  8471. /**
  8472. * Parse headers into key value object
  8473. *
  8474. * @param {string} headers Raw headers as a string
  8475. * @returns {Object} Parsed headers as key value object
  8476. */
  8477. function parseHeaders(headers) {
  8478. var parsed = createMap(), i;
  8479. function fillInParsed(key, val) {
  8480. if (key) {
  8481. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  8482. }
  8483. }
  8484. if (isString(headers)) {
  8485. forEach(headers.split('\n'), function(line) {
  8486. i = line.indexOf(':');
  8487. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  8488. });
  8489. } else if (isObject(headers)) {
  8490. forEach(headers, function(headerVal, headerKey) {
  8491. fillInParsed(lowercase(headerKey), trim(headerVal));
  8492. });
  8493. }
  8494. return parsed;
  8495. }
  8496. /**
  8497. * Returns a function that provides access to parsed headers.
  8498. *
  8499. * Headers are lazy parsed when first requested.
  8500. * @see parseHeaders
  8501. *
  8502. * @param {(string|Object)} headers Headers to provide access to.
  8503. * @returns {function(string=)} Returns a getter function which if called with:
  8504. *
  8505. * - if called with single an argument returns a single header value or null
  8506. * - if called with no arguments returns an object containing all headers.
  8507. */
  8508. function headersGetter(headers) {
  8509. var headersObj;
  8510. return function(name) {
  8511. if (!headersObj) headersObj = parseHeaders(headers);
  8512. if (name) {
  8513. var value = headersObj[lowercase(name)];
  8514. if (value === void 0) {
  8515. value = null;
  8516. }
  8517. return value;
  8518. }
  8519. return headersObj;
  8520. };
  8521. }
  8522. /**
  8523. * Chain all given functions
  8524. *
  8525. * This function is used for both request and response transforming
  8526. *
  8527. * @param {*} data Data to transform.
  8528. * @param {function(string=)} headers HTTP headers getter fn.
  8529. * @param {number} status HTTP status code of the response.
  8530. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  8531. * @returns {*} Transformed data.
  8532. */
  8533. function transformData(data, headers, status, fns) {
  8534. if (isFunction(fns)) {
  8535. return fns(data, headers, status);
  8536. }
  8537. forEach(fns, function(fn) {
  8538. data = fn(data, headers, status);
  8539. });
  8540. return data;
  8541. }
  8542. function isSuccess(status) {
  8543. return 200 <= status && status < 300;
  8544. }
  8545. /**
  8546. * @ngdoc provider
  8547. * @name $httpProvider
  8548. * @description
  8549. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  8550. * */
  8551. function $HttpProvider() {
  8552. /**
  8553. * @ngdoc property
  8554. * @name $httpProvider#defaults
  8555. * @description
  8556. *
  8557. * Object containing default values for all {@link ng.$http $http} requests.
  8558. *
  8559. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  8560. * that will provide the cache for all requests who set their `cache` property to `true`.
  8561. * If you set the `defaults.cache = false` then only requests that specify their own custom
  8562. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  8563. *
  8564. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  8565. * Defaults value is `'XSRF-TOKEN'`.
  8566. *
  8567. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  8568. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  8569. *
  8570. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  8571. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  8572. * setting default headers.
  8573. * - **`defaults.headers.common`**
  8574. * - **`defaults.headers.post`**
  8575. * - **`defaults.headers.put`**
  8576. * - **`defaults.headers.patch`**
  8577. *
  8578. *
  8579. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  8580. * used to the prepare string representation of request parameters (specified as an object).
  8581. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  8582. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  8583. *
  8584. **/
  8585. var defaults = this.defaults = {
  8586. // transform incoming response data
  8587. transformResponse: [defaultHttpResponseTransform],
  8588. // transform outgoing request data
  8589. transformRequest: [function(d) {
  8590. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  8591. }],
  8592. // default headers
  8593. headers: {
  8594. common: {
  8595. 'Accept': 'application/json, text/plain, */*'
  8596. },
  8597. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8598. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8599. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  8600. },
  8601. xsrfCookieName: 'XSRF-TOKEN',
  8602. xsrfHeaderName: 'X-XSRF-TOKEN',
  8603. paramSerializer: '$httpParamSerializer'
  8604. };
  8605. var useApplyAsync = false;
  8606. /**
  8607. * @ngdoc method
  8608. * @name $httpProvider#useApplyAsync
  8609. * @description
  8610. *
  8611. * Configure $http service to combine processing of multiple http responses received at around
  8612. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  8613. * significant performance improvement for bigger applications that make many HTTP requests
  8614. * concurrently (common during application bootstrap).
  8615. *
  8616. * Defaults to false. If no value is specified, returns the current configured value.
  8617. *
  8618. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  8619. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  8620. * to load and share the same digest cycle.
  8621. *
  8622. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8623. * otherwise, returns the current configured value.
  8624. **/
  8625. this.useApplyAsync = function(value) {
  8626. if (isDefined(value)) {
  8627. useApplyAsync = !!value;
  8628. return this;
  8629. }
  8630. return useApplyAsync;
  8631. };
  8632. var useLegacyPromise = true;
  8633. /**
  8634. * @ngdoc method
  8635. * @name $httpProvider#useLegacyPromiseExtensions
  8636. * @description
  8637. *
  8638. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  8639. * This should be used to make sure that applications work without these methods.
  8640. *
  8641. * Defaults to false. If no value is specified, returns the current configured value.
  8642. *
  8643. * @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods.
  8644. *
  8645. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8646. * otherwise, returns the current configured value.
  8647. **/
  8648. this.useLegacyPromiseExtensions = function(value) {
  8649. if (isDefined(value)) {
  8650. useLegacyPromise = !!value;
  8651. return this;
  8652. }
  8653. return useLegacyPromise;
  8654. };
  8655. /**
  8656. * @ngdoc property
  8657. * @name $httpProvider#interceptors
  8658. * @description
  8659. *
  8660. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  8661. * pre-processing of request or postprocessing of responses.
  8662. *
  8663. * These service factories are ordered by request, i.e. they are applied in the same order as the
  8664. * array, on request, but reverse order, on response.
  8665. *
  8666. * {@link ng.$http#interceptors Interceptors detailed info}
  8667. **/
  8668. var interceptorFactories = this.interceptors = [];
  8669. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  8670. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  8671. var defaultCache = $cacheFactory('$http');
  8672. /**
  8673. * Make sure that default param serializer is exposed as a function
  8674. */
  8675. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  8676. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  8677. /**
  8678. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  8679. * The reversal is needed so that we can build up the interception chain around the
  8680. * server request.
  8681. */
  8682. var reversedInterceptors = [];
  8683. forEach(interceptorFactories, function(interceptorFactory) {
  8684. reversedInterceptors.unshift(isString(interceptorFactory)
  8685. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  8686. });
  8687. /**
  8688. * @ngdoc service
  8689. * @kind function
  8690. * @name $http
  8691. * @requires ng.$httpBackend
  8692. * @requires $cacheFactory
  8693. * @requires $rootScope
  8694. * @requires $q
  8695. * @requires $injector
  8696. *
  8697. * @description
  8698. * The `$http` service is a core Angular service that facilitates communication with the remote
  8699. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  8700. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  8701. *
  8702. * For unit testing applications that use `$http` service, see
  8703. * {@link ngMock.$httpBackend $httpBackend mock}.
  8704. *
  8705. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  8706. * $resource} service.
  8707. *
  8708. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  8709. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  8710. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  8711. *
  8712. *
  8713. * ## General usage
  8714. * The `$http` service is a function which takes a single argument — a configuration object —
  8715. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  8716. *
  8717. * ```js
  8718. * // Simple GET request example :
  8719. * $http.get('/someUrl').
  8720. * then(function(response) {
  8721. * // this callback will be called asynchronously
  8722. * // when the response is available
  8723. * }, function(response) {
  8724. * // called asynchronously if an error occurs
  8725. * // or server returns response with an error status.
  8726. * });
  8727. * ```
  8728. *
  8729. * ```js
  8730. * // Simple POST request example (passing data) :
  8731. * $http.post('/someUrl', {msg:'hello word!'}).
  8732. * then(function(response) {
  8733. * // this callback will be called asynchronously
  8734. * // when the response is available
  8735. * }, function(response) {
  8736. * // called asynchronously if an error occurs
  8737. * // or server returns response with an error status.
  8738. * });
  8739. * ```
  8740. *
  8741. * The response object has these properties:
  8742. *
  8743. * - **data** – `{string|Object}` – The response body transformed with the transform
  8744. * functions.
  8745. * - **status** – `{number}` – HTTP status code of the response.
  8746. * - **headers** – `{function([headerName])}` – Header getter function.
  8747. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8748. * - **statusText** – `{string}` – HTTP status text of the response.
  8749. *
  8750. * A response status code between 200 and 299 is considered a success status and
  8751. * will result in the success callback being called. Note that if the response is a redirect,
  8752. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  8753. * called for such responses.
  8754. *
  8755. * ## Writing Unit Tests that use $http
  8756. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  8757. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  8758. * request using trained responses.
  8759. *
  8760. * ```
  8761. * $httpBackend.expectGET(...);
  8762. * $http.get(...);
  8763. * $httpBackend.flush();
  8764. * ```
  8765. *
  8766. * ## Shortcut methods
  8767. *
  8768. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  8769. * request data must be passed in for POST/PUT requests.
  8770. *
  8771. * ```js
  8772. * $http.get('/someUrl').then(successCallback);
  8773. * $http.post('/someUrl', data).then(successCallback);
  8774. * ```
  8775. *
  8776. * Complete list of shortcut methods:
  8777. *
  8778. * - {@link ng.$http#get $http.get}
  8779. * - {@link ng.$http#head $http.head}
  8780. * - {@link ng.$http#post $http.post}
  8781. * - {@link ng.$http#put $http.put}
  8782. * - {@link ng.$http#delete $http.delete}
  8783. * - {@link ng.$http#jsonp $http.jsonp}
  8784. * - {@link ng.$http#patch $http.patch}
  8785. *
  8786. *
  8787. * ## Deprecation Notice
  8788. * <div class="alert alert-danger">
  8789. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  8790. * Use the standard `then` method instead.
  8791. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  8792. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  8793. * </div>
  8794. *
  8795. * ## Setting HTTP Headers
  8796. *
  8797. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8798. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8799. * object, which currently contains this default configuration:
  8800. *
  8801. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8802. * - `Accept: application/json, text/plain, * / *`
  8803. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8804. * - `Content-Type: application/json`
  8805. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8806. * - `Content-Type: application/json`
  8807. *
  8808. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8809. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8810. * with the lowercased HTTP method name as the key, e.g.
  8811. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  8812. *
  8813. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8814. * fashion. For example:
  8815. *
  8816. * ```
  8817. * module.run(function($http) {
  8818. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8819. * });
  8820. * ```
  8821. *
  8822. * In addition, you can supply a `headers` property in the config object passed when
  8823. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8824. *
  8825. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8826. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8827. *
  8828. * ```js
  8829. * var req = {
  8830. * method: 'POST',
  8831. * url: 'http://example.com',
  8832. * headers: {
  8833. * 'Content-Type': undefined
  8834. * },
  8835. * data: { test: 'test' }
  8836. * }
  8837. *
  8838. * $http(req).then(function(){...}, function(){...});
  8839. * ```
  8840. *
  8841. * ## Transforming Requests and Responses
  8842. *
  8843. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8844. * and `transformResponse`. These properties can be a single function that returns
  8845. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  8846. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8847. *
  8848. * ### Default Transformations
  8849. *
  8850. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8851. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8852. * then these will be applied.
  8853. *
  8854. * You can augment or replace the default transformations by modifying these properties by adding to or
  8855. * replacing the array.
  8856. *
  8857. * Angular provides the following default transformations:
  8858. *
  8859. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8860. *
  8861. * - If the `data` property of the request configuration object contains an object, serialize it
  8862. * into JSON format.
  8863. *
  8864. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8865. *
  8866. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8867. * - If JSON response is detected, deserialize it using a JSON parser.
  8868. *
  8869. *
  8870. * ### Overriding the Default Transformations Per Request
  8871. *
  8872. * If you wish override the request/response transformations only for a single request then provide
  8873. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8874. * into `$http`.
  8875. *
  8876. * Note that if you provide these properties on the config object the default transformations will be
  8877. * overwritten. If you wish to augment the default transformations then you must include them in your
  8878. * local transformation array.
  8879. *
  8880. * The following code demonstrates adding a new response transformation to be run after the default response
  8881. * transformations have been run.
  8882. *
  8883. * ```js
  8884. * function appendTransform(defaults, transform) {
  8885. *
  8886. * // We can't guarantee that the default transformation is an array
  8887. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8888. *
  8889. * // Append the new transformation to the defaults
  8890. * return defaults.concat(transform);
  8891. * }
  8892. *
  8893. * $http({
  8894. * url: '...',
  8895. * method: 'GET',
  8896. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8897. * return doTransform(value);
  8898. * })
  8899. * });
  8900. * ```
  8901. *
  8902. *
  8903. * ## Caching
  8904. *
  8905. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8906. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8907. * When the cache is enabled, `$http` stores the response from the server in the specified
  8908. * cache. The next time the same request is made, the response is served from the cache without
  8909. * sending a request to the server.
  8910. *
  8911. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8912. * the same way that real requests are.
  8913. *
  8914. * If there are multiple GET requests for the same URL that should be cached using the same
  8915. * cache, but the cache is not populated yet, only one request to the server will be made and
  8916. * the remaining requests will be fulfilled using the response from the first request.
  8917. *
  8918. * You can change the default cache to a new object (built with
  8919. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8920. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8921. * their `cache` property to `true` will now use this cache object.
  8922. *
  8923. * If you set the default cache to `false` then only requests that specify their own custom
  8924. * cache object will be cached.
  8925. *
  8926. * ## Interceptors
  8927. *
  8928. * Before you start creating interceptors, be sure to understand the
  8929. * {@link ng.$q $q and deferred/promise APIs}.
  8930. *
  8931. * For purposes of global error handling, authentication, or any kind of synchronous or
  8932. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8933. * able to intercept requests before they are handed to the server and
  8934. * responses before they are handed over to the application code that
  8935. * initiated these requests. The interceptors leverage the {@link ng.$q
  8936. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8937. *
  8938. * The interceptors are service factories that are registered with the `$httpProvider` by
  8939. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8940. * injected with dependencies (if specified) and returns the interceptor.
  8941. *
  8942. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8943. *
  8944. * * `request`: interceptors get called with a http `config` object. The function is free to
  8945. * modify the `config` object or create a new one. The function needs to return the `config`
  8946. * object directly, or a promise containing the `config` or a new `config` object.
  8947. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8948. * resolved with a rejection.
  8949. * * `response`: interceptors get called with http `response` object. The function is free to
  8950. * modify the `response` object or create a new one. The function needs to return the `response`
  8951. * object directly, or as a promise containing the `response` or a new `response` object.
  8952. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8953. * resolved with a rejection.
  8954. *
  8955. *
  8956. * ```js
  8957. * // register the interceptor as a service
  8958. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8959. * return {
  8960. * // optional method
  8961. * 'request': function(config) {
  8962. * // do something on success
  8963. * return config;
  8964. * },
  8965. *
  8966. * // optional method
  8967. * 'requestError': function(rejection) {
  8968. * // do something on error
  8969. * if (canRecover(rejection)) {
  8970. * return responseOrNewPromise
  8971. * }
  8972. * return $q.reject(rejection);
  8973. * },
  8974. *
  8975. *
  8976. *
  8977. * // optional method
  8978. * 'response': function(response) {
  8979. * // do something on success
  8980. * return response;
  8981. * },
  8982. *
  8983. * // optional method
  8984. * 'responseError': function(rejection) {
  8985. * // do something on error
  8986. * if (canRecover(rejection)) {
  8987. * return responseOrNewPromise
  8988. * }
  8989. * return $q.reject(rejection);
  8990. * }
  8991. * };
  8992. * });
  8993. *
  8994. * $httpProvider.interceptors.push('myHttpInterceptor');
  8995. *
  8996. *
  8997. * // alternatively, register the interceptor via an anonymous factory
  8998. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8999. * return {
  9000. * 'request': function(config) {
  9001. * // same as above
  9002. * },
  9003. *
  9004. * 'response': function(response) {
  9005. * // same as above
  9006. * }
  9007. * };
  9008. * });
  9009. * ```
  9010. *
  9011. * ## Security Considerations
  9012. *
  9013. * When designing web applications, consider security threats from:
  9014. *
  9015. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9016. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  9017. *
  9018. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  9019. * pre-configured with strategies that address these issues, but for this to work backend server
  9020. * cooperation is required.
  9021. *
  9022. * ### JSON Vulnerability Protection
  9023. *
  9024. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9025. * allows third party website to turn your JSON resource URL into
  9026. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  9027. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  9028. * Angular will automatically strip the prefix before processing it as JSON.
  9029. *
  9030. * For example if your server needs to return:
  9031. * ```js
  9032. * ['one','two']
  9033. * ```
  9034. *
  9035. * which is vulnerable to attack, your server can return:
  9036. * ```js
  9037. * )]}',
  9038. * ['one','two']
  9039. * ```
  9040. *
  9041. * Angular will strip the prefix, before processing the JSON.
  9042. *
  9043. *
  9044. * ### Cross Site Request Forgery (XSRF) Protection
  9045. *
  9046. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  9047. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  9048. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  9049. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  9050. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  9051. * the XHR came from JavaScript running on your domain. The header will not be set for
  9052. * cross-domain requests.
  9053. *
  9054. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  9055. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  9056. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  9057. * that only JavaScript running on your domain could have sent the request. The token must be
  9058. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  9059. * making up its own tokens). We recommend that the token is a digest of your site's
  9060. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  9061. * for added security.
  9062. *
  9063. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  9064. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  9065. * or the per-request config object.
  9066. *
  9067. * In order to prevent collisions in environments where multiple Angular apps share the
  9068. * same domain or subdomain, we recommend that each application uses unique cookie name.
  9069. *
  9070. * @param {object} config Object describing the request to be made and how it should be
  9071. * processed. The object has following properties:
  9072. *
  9073. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  9074. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  9075. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  9076. * with the `paramSerializer` and appended as GET parameters.
  9077. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  9078. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  9079. * HTTP headers to send to the server. If the return value of a function is null, the
  9080. * header will not be sent. Functions accept a config object as an argument.
  9081. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  9082. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  9083. * - **transformRequest** –
  9084. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  9085. * transform function or an array of such functions. The transform function takes the http
  9086. * request body and headers and returns its transformed (typically serialized) version.
  9087. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9088. * Overriding the Default Transformations}
  9089. * - **transformResponse** –
  9090. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  9091. * transform function or an array of such functions. The transform function takes the http
  9092. * response body, headers and status and returns its transformed (typically deserialized) version.
  9093. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9094. * Overriding the Default TransformationjqLiks}
  9095. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  9096. * prepare the string representation of request parameters (specified as an object).
  9097. * If specified as string, it is interpreted as function registered with the
  9098. * {@link $injector $injector}, which means you can create your own serializer
  9099. * by registering it as a {@link auto.$provide#service service}.
  9100. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  9101. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  9102. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  9103. * GET request, otherwise if a cache instance built with
  9104. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  9105. * caching.
  9106. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  9107. * that should abort the request when resolved.
  9108. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  9109. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  9110. * for more information.
  9111. * - **responseType** - `{string}` - see
  9112. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  9113. *
  9114. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  9115. * when the request succeeds or fails.
  9116. *
  9117. *
  9118. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  9119. * requests. This is primarily meant to be used for debugging purposes.
  9120. *
  9121. *
  9122. * @example
  9123. <example module="httpExample">
  9124. <file name="index.html">
  9125. <div ng-controller="FetchController">
  9126. <select ng-model="method" aria-label="Request method">
  9127. <option>GET</option>
  9128. <option>JSONP</option>
  9129. </select>
  9130. <input type="text" ng-model="url" size="80" aria-label="URL" />
  9131. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  9132. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  9133. <button id="samplejsonpbtn"
  9134. ng-click="updateModel('JSONP',
  9135. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  9136. Sample JSONP
  9137. </button>
  9138. <button id="invalidjsonpbtn"
  9139. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  9140. Invalid JSONP
  9141. </button>
  9142. <pre>http status code: {{status}}</pre>
  9143. <pre>http response data: {{data}}</pre>
  9144. </div>
  9145. </file>
  9146. <file name="script.js">
  9147. angular.module('httpExample', [])
  9148. .controller('FetchController', ['$scope', '$http', '$templateCache',
  9149. function($scope, $http, $templateCache) {
  9150. $scope.method = 'GET';
  9151. $scope.url = 'http-hello.html';
  9152. $scope.fetch = function() {
  9153. $scope.code = null;
  9154. $scope.response = null;
  9155. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  9156. then(function(response) {
  9157. $scope.status = response.status;
  9158. $scope.data = response.data;
  9159. }, function(response) {
  9160. $scope.data = response.data || "Request failed";
  9161. $scope.status = response.status;
  9162. });
  9163. };
  9164. $scope.updateModel = function(method, url) {
  9165. $scope.method = method;
  9166. $scope.url = url;
  9167. };
  9168. }]);
  9169. </file>
  9170. <file name="http-hello.html">
  9171. Hello, $http!
  9172. </file>
  9173. <file name="protractor.js" type="protractor">
  9174. var status = element(by.binding('status'));
  9175. var data = element(by.binding('data'));
  9176. var fetchBtn = element(by.id('fetchbtn'));
  9177. var sampleGetBtn = element(by.id('samplegetbtn'));
  9178. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  9179. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  9180. it('should make an xhr GET request', function() {
  9181. sampleGetBtn.click();
  9182. fetchBtn.click();
  9183. expect(status.getText()).toMatch('200');
  9184. expect(data.getText()).toMatch(/Hello, \$http!/);
  9185. });
  9186. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  9187. // it('should make a JSONP request to angularjs.org', function() {
  9188. // sampleJsonpBtn.click();
  9189. // fetchBtn.click();
  9190. // expect(status.getText()).toMatch('200');
  9191. // expect(data.getText()).toMatch(/Super Hero!/);
  9192. // });
  9193. it('should make JSONP request to invalid URL and invoke the error handler',
  9194. function() {
  9195. invalidJsonpBtn.click();
  9196. fetchBtn.click();
  9197. expect(status.getText()).toMatch('0');
  9198. expect(data.getText()).toMatch('Request failed');
  9199. });
  9200. </file>
  9201. </example>
  9202. */
  9203. function $http(requestConfig) {
  9204. if (!angular.isObject(requestConfig)) {
  9205. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  9206. }
  9207. var config = extend({
  9208. method: 'get',
  9209. transformRequest: defaults.transformRequest,
  9210. transformResponse: defaults.transformResponse,
  9211. paramSerializer: defaults.paramSerializer
  9212. }, requestConfig);
  9213. config.headers = mergeHeaders(requestConfig);
  9214. config.method = uppercase(config.method);
  9215. config.paramSerializer = isString(config.paramSerializer) ?
  9216. $injector.get(config.paramSerializer) : config.paramSerializer;
  9217. var serverRequest = function(config) {
  9218. var headers = config.headers;
  9219. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  9220. // strip content-type if data is undefined
  9221. if (isUndefined(reqData)) {
  9222. forEach(headers, function(value, header) {
  9223. if (lowercase(header) === 'content-type') {
  9224. delete headers[header];
  9225. }
  9226. });
  9227. }
  9228. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  9229. config.withCredentials = defaults.withCredentials;
  9230. }
  9231. // send request
  9232. return sendReq(config, reqData).then(transformResponse, transformResponse);
  9233. };
  9234. var chain = [serverRequest, undefined];
  9235. var promise = $q.when(config);
  9236. // apply interceptors
  9237. forEach(reversedInterceptors, function(interceptor) {
  9238. if (interceptor.request || interceptor.requestError) {
  9239. chain.unshift(interceptor.request, interceptor.requestError);
  9240. }
  9241. if (interceptor.response || interceptor.responseError) {
  9242. chain.push(interceptor.response, interceptor.responseError);
  9243. }
  9244. });
  9245. while (chain.length) {
  9246. var thenFn = chain.shift();
  9247. var rejectFn = chain.shift();
  9248. promise = promise.then(thenFn, rejectFn);
  9249. }
  9250. if (useLegacyPromise) {
  9251. promise.success = function(fn) {
  9252. assertArgFn(fn, 'fn');
  9253. promise.then(function(response) {
  9254. fn(response.data, response.status, response.headers, config);
  9255. });
  9256. return promise;
  9257. };
  9258. promise.error = function(fn) {
  9259. assertArgFn(fn, 'fn');
  9260. promise.then(null, function(response) {
  9261. fn(response.data, response.status, response.headers, config);
  9262. });
  9263. return promise;
  9264. };
  9265. } else {
  9266. promise.success = $httpMinErrLegacyFn('success');
  9267. promise.error = $httpMinErrLegacyFn('error');
  9268. }
  9269. return promise;
  9270. function transformResponse(response) {
  9271. // make a copy since the response must be cacheable
  9272. var resp = extend({}, response);
  9273. if (!response.data) {
  9274. resp.data = response.data;
  9275. } else {
  9276. resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
  9277. }
  9278. return (isSuccess(response.status))
  9279. ? resp
  9280. : $q.reject(resp);
  9281. }
  9282. function executeHeaderFns(headers, config) {
  9283. var headerContent, processedHeaders = {};
  9284. forEach(headers, function(headerFn, header) {
  9285. if (isFunction(headerFn)) {
  9286. headerContent = headerFn(config);
  9287. if (headerContent != null) {
  9288. processedHeaders[header] = headerContent;
  9289. }
  9290. } else {
  9291. processedHeaders[header] = headerFn;
  9292. }
  9293. });
  9294. return processedHeaders;
  9295. }
  9296. function mergeHeaders(config) {
  9297. var defHeaders = defaults.headers,
  9298. reqHeaders = extend({}, config.headers),
  9299. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  9300. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  9301. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  9302. defaultHeadersIteration:
  9303. for (defHeaderName in defHeaders) {
  9304. lowercaseDefHeaderName = lowercase(defHeaderName);
  9305. for (reqHeaderName in reqHeaders) {
  9306. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  9307. continue defaultHeadersIteration;
  9308. }
  9309. }
  9310. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  9311. }
  9312. // execute if header value is a function for merged headers
  9313. return executeHeaderFns(reqHeaders, shallowCopy(config));
  9314. }
  9315. }
  9316. $http.pendingRequests = [];
  9317. /**
  9318. * @ngdoc method
  9319. * @name $http#get
  9320. *
  9321. * @description
  9322. * Shortcut method to perform `GET` request.
  9323. *
  9324. * @param {string} url Relative or absolute URL specifying the destination of the request
  9325. * @param {Object=} config Optional configuration object
  9326. * @returns {HttpPromise} Future object
  9327. */
  9328. /**
  9329. * @ngdoc method
  9330. * @name $http#delete
  9331. *
  9332. * @description
  9333. * Shortcut method to perform `DELETE` request.
  9334. *
  9335. * @param {string} url Relative or absolute URL specifying the destination of the request
  9336. * @param {Object=} config Optional configuration object
  9337. * @returns {HttpPromise} Future object
  9338. */
  9339. /**
  9340. * @ngdoc method
  9341. * @name $http#head
  9342. *
  9343. * @description
  9344. * Shortcut method to perform `HEAD` request.
  9345. *
  9346. * @param {string} url Relative or absolute URL specifying the destination of the request
  9347. * @param {Object=} config Optional configuration object
  9348. * @returns {HttpPromise} Future object
  9349. */
  9350. /**
  9351. * @ngdoc method
  9352. * @name $http#jsonp
  9353. *
  9354. * @description
  9355. * Shortcut method to perform `JSONP` request.
  9356. *
  9357. * @param {string} url Relative or absolute URL specifying the destination of the request.
  9358. * The name of the callback should be the string `JSON_CALLBACK`.
  9359. * @param {Object=} config Optional configuration object
  9360. * @returns {HttpPromise} Future object
  9361. */
  9362. createShortMethods('get', 'delete', 'head', 'jsonp');
  9363. /**
  9364. * @ngdoc method
  9365. * @name $http#post
  9366. *
  9367. * @description
  9368. * Shortcut method to perform `POST` request.
  9369. *
  9370. * @param {string} url Relative or absolute URL specifying the destination of the request
  9371. * @param {*} data Request content
  9372. * @param {Object=} config Optional configuration object
  9373. * @returns {HttpPromise} Future object
  9374. */
  9375. /**
  9376. * @ngdoc method
  9377. * @name $http#put
  9378. *
  9379. * @description
  9380. * Shortcut method to perform `PUT` request.
  9381. *
  9382. * @param {string} url Relative or absolute URL specifying the destination of the request
  9383. * @param {*} data Request content
  9384. * @param {Object=} config Optional configuration object
  9385. * @returns {HttpPromise} Future object
  9386. */
  9387. /**
  9388. * @ngdoc method
  9389. * @name $http#patch
  9390. *
  9391. * @description
  9392. * Shortcut method to perform `PATCH` request.
  9393. *
  9394. * @param {string} url Relative or absolute URL specifying the destination of the request
  9395. * @param {*} data Request content
  9396. * @param {Object=} config Optional configuration object
  9397. * @returns {HttpPromise} Future object
  9398. */
  9399. createShortMethodsWithData('post', 'put', 'patch');
  9400. /**
  9401. * @ngdoc property
  9402. * @name $http#defaults
  9403. *
  9404. * @description
  9405. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  9406. * default headers, withCredentials as well as request and response transformations.
  9407. *
  9408. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  9409. */
  9410. $http.defaults = defaults;
  9411. return $http;
  9412. function createShortMethods(names) {
  9413. forEach(arguments, function(name) {
  9414. $http[name] = function(url, config) {
  9415. return $http(extend({}, config || {}, {
  9416. method: name,
  9417. url: url
  9418. }));
  9419. };
  9420. });
  9421. }
  9422. function createShortMethodsWithData(name) {
  9423. forEach(arguments, function(name) {
  9424. $http[name] = function(url, data, config) {
  9425. return $http(extend({}, config || {}, {
  9426. method: name,
  9427. url: url,
  9428. data: data
  9429. }));
  9430. };
  9431. });
  9432. }
  9433. /**
  9434. * Makes the request.
  9435. *
  9436. * !!! ACCESSES CLOSURE VARS:
  9437. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  9438. */
  9439. function sendReq(config, reqData) {
  9440. var deferred = $q.defer(),
  9441. promise = deferred.promise,
  9442. cache,
  9443. cachedResp,
  9444. reqHeaders = config.headers,
  9445. url = buildUrl(config.url, config.paramSerializer(config.params));
  9446. $http.pendingRequests.push(config);
  9447. promise.then(removePendingReq, removePendingReq);
  9448. if ((config.cache || defaults.cache) && config.cache !== false &&
  9449. (config.method === 'GET' || config.method === 'JSONP')) {
  9450. cache = isObject(config.cache) ? config.cache
  9451. : isObject(defaults.cache) ? defaults.cache
  9452. : defaultCache;
  9453. }
  9454. if (cache) {
  9455. cachedResp = cache.get(url);
  9456. if (isDefined(cachedResp)) {
  9457. if (isPromiseLike(cachedResp)) {
  9458. // cached request has already been sent, but there is no response yet
  9459. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  9460. } else {
  9461. // serving from cache
  9462. if (isArray(cachedResp)) {
  9463. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  9464. } else {
  9465. resolvePromise(cachedResp, 200, {}, 'OK');
  9466. }
  9467. }
  9468. } else {
  9469. // put the promise for the non-transformed response into cache as a placeholder
  9470. cache.put(url, promise);
  9471. }
  9472. }
  9473. // if we won't have the response in cache, set the xsrf headers and
  9474. // send the request to the backend
  9475. if (isUndefined(cachedResp)) {
  9476. var xsrfValue = urlIsSameOrigin(config.url)
  9477. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  9478. : undefined;
  9479. if (xsrfValue) {
  9480. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  9481. }
  9482. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  9483. config.withCredentials, config.responseType);
  9484. }
  9485. return promise;
  9486. /**
  9487. * Callback registered to $httpBackend():
  9488. * - caches the response if desired
  9489. * - resolves the raw $http promise
  9490. * - calls $apply
  9491. */
  9492. function done(status, response, headersString, statusText) {
  9493. if (cache) {
  9494. if (isSuccess(status)) {
  9495. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  9496. } else {
  9497. // remove promise from the cache
  9498. cache.remove(url);
  9499. }
  9500. }
  9501. function resolveHttpPromise() {
  9502. resolvePromise(response, status, headersString, statusText);
  9503. }
  9504. if (useApplyAsync) {
  9505. $rootScope.$applyAsync(resolveHttpPromise);
  9506. } else {
  9507. resolveHttpPromise();
  9508. if (!$rootScope.$$phase) $rootScope.$apply();
  9509. }
  9510. }
  9511. /**
  9512. * Resolves the raw $http promise.
  9513. */
  9514. function resolvePromise(response, status, headers, statusText) {
  9515. // normalize internal statuses to 0
  9516. status = Math.max(status, 0);
  9517. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  9518. data: response,
  9519. status: status,
  9520. headers: headersGetter(headers),
  9521. config: config,
  9522. statusText: statusText
  9523. });
  9524. }
  9525. function resolvePromiseWithResult(result) {
  9526. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  9527. }
  9528. function removePendingReq() {
  9529. var idx = $http.pendingRequests.indexOf(config);
  9530. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  9531. }
  9532. }
  9533. function buildUrl(url, serializedParams) {
  9534. if (serializedParams.length > 0) {
  9535. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  9536. }
  9537. return url;
  9538. }
  9539. }];
  9540. }
  9541. function createXhr() {
  9542. return new window.XMLHttpRequest();
  9543. }
  9544. /**
  9545. * @ngdoc service
  9546. * @name $httpBackend
  9547. * @requires $window
  9548. * @requires $document
  9549. *
  9550. * @description
  9551. * HTTP backend used by the {@link ng.$http service} that delegates to
  9552. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  9553. *
  9554. * You should never need to use this service directly, instead use the higher-level abstractions:
  9555. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  9556. *
  9557. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  9558. * $httpBackend} which can be trained with responses.
  9559. */
  9560. function $HttpBackendProvider() {
  9561. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  9562. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  9563. }];
  9564. }
  9565. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  9566. // TODO(vojta): fix the signature
  9567. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  9568. $browser.$$incOutstandingRequestCount();
  9569. url = url || $browser.url();
  9570. if (lowercase(method) == 'jsonp') {
  9571. var callbackId = '_' + (callbacks.counter++).toString(36);
  9572. callbacks[callbackId] = function(data) {
  9573. callbacks[callbackId].data = data;
  9574. callbacks[callbackId].called = true;
  9575. };
  9576. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  9577. callbackId, function(status, text) {
  9578. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  9579. callbacks[callbackId] = noop;
  9580. });
  9581. } else {
  9582. var xhr = createXhr();
  9583. xhr.open(method, url, true);
  9584. forEach(headers, function(value, key) {
  9585. if (isDefined(value)) {
  9586. xhr.setRequestHeader(key, value);
  9587. }
  9588. });
  9589. xhr.onload = function requestLoaded() {
  9590. var statusText = xhr.statusText || '';
  9591. // responseText is the old-school way of retrieving response (supported by IE9)
  9592. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  9593. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  9594. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  9595. var status = xhr.status === 1223 ? 204 : xhr.status;
  9596. // fix status code when it is 0 (0 status is undocumented).
  9597. // Occurs when accessing file resources or on Android 4.1 stock browser
  9598. // while retrieving files from application cache.
  9599. if (status === 0) {
  9600. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  9601. }
  9602. completeRequest(callback,
  9603. status,
  9604. response,
  9605. xhr.getAllResponseHeaders(),
  9606. statusText);
  9607. };
  9608. var requestError = function() {
  9609. // The response is always empty
  9610. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  9611. completeRequest(callback, -1, null, null, '');
  9612. };
  9613. xhr.onerror = requestError;
  9614. xhr.onabort = requestError;
  9615. if (withCredentials) {
  9616. xhr.withCredentials = true;
  9617. }
  9618. if (responseType) {
  9619. try {
  9620. xhr.responseType = responseType;
  9621. } catch (e) {
  9622. // WebKit added support for the json responseType value on 09/03/2013
  9623. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  9624. // known to throw when setting the value "json" as the response type. Other older
  9625. // browsers implementing the responseType
  9626. //
  9627. // The json response type can be ignored if not supported, because JSON payloads are
  9628. // parsed on the client-side regardless.
  9629. if (responseType !== 'json') {
  9630. throw e;
  9631. }
  9632. }
  9633. }
  9634. xhr.send(post);
  9635. }
  9636. if (timeout > 0) {
  9637. var timeoutId = $browserDefer(timeoutRequest, timeout);
  9638. } else if (isPromiseLike(timeout)) {
  9639. timeout.then(timeoutRequest);
  9640. }
  9641. function timeoutRequest() {
  9642. jsonpDone && jsonpDone();
  9643. xhr && xhr.abort();
  9644. }
  9645. function completeRequest(callback, status, response, headersString, statusText) {
  9646. // cancel timeout and subsequent timeout promise resolution
  9647. if (timeoutId !== undefined) {
  9648. $browserDefer.cancel(timeoutId);
  9649. }
  9650. jsonpDone = xhr = null;
  9651. callback(status, response, headersString, statusText);
  9652. $browser.$$completeOutstandingRequest(noop);
  9653. }
  9654. };
  9655. function jsonpReq(url, callbackId, done) {
  9656. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  9657. // - fetches local scripts via XHR and evals them
  9658. // - adds and immediately removes script elements from the document
  9659. var script = rawDocument.createElement('script'), callback = null;
  9660. script.type = "text/javascript";
  9661. script.src = url;
  9662. script.async = true;
  9663. callback = function(event) {
  9664. removeEventListenerFn(script, "load", callback);
  9665. removeEventListenerFn(script, "error", callback);
  9666. rawDocument.body.removeChild(script);
  9667. script = null;
  9668. var status = -1;
  9669. var text = "unknown";
  9670. if (event) {
  9671. if (event.type === "load" && !callbacks[callbackId].called) {
  9672. event = { type: "error" };
  9673. }
  9674. text = event.type;
  9675. status = event.type === "error" ? 404 : 200;
  9676. }
  9677. if (done) {
  9678. done(status, text);
  9679. }
  9680. };
  9681. addEventListenerFn(script, "load", callback);
  9682. addEventListenerFn(script, "error", callback);
  9683. rawDocument.body.appendChild(script);
  9684. return callback;
  9685. }
  9686. }
  9687. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  9688. $interpolateMinErr.throwNoconcat = function(text) {
  9689. throw $interpolateMinErr('noconcat',
  9690. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9691. "interpolations that concatenate multiple expressions when a trusted value is " +
  9692. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9693. };
  9694. $interpolateMinErr.interr = function(text, err) {
  9695. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  9696. };
  9697. /**
  9698. * @ngdoc provider
  9699. * @name $interpolateProvider
  9700. *
  9701. * @description
  9702. *
  9703. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  9704. *
  9705. * @example
  9706. <example module="customInterpolationApp">
  9707. <file name="index.html">
  9708. <script>
  9709. var customInterpolationApp = angular.module('customInterpolationApp', []);
  9710. customInterpolationApp.config(function($interpolateProvider) {
  9711. $interpolateProvider.startSymbol('//');
  9712. $interpolateProvider.endSymbol('//');
  9713. });
  9714. customInterpolationApp.controller('DemoController', function() {
  9715. this.label = "This binding is brought you by // interpolation symbols.";
  9716. });
  9717. </script>
  9718. <div ng-app="App" ng-controller="DemoController as demo">
  9719. //demo.label//
  9720. </div>
  9721. </file>
  9722. <file name="protractor.js" type="protractor">
  9723. it('should interpolate binding with custom symbols', function() {
  9724. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  9725. });
  9726. </file>
  9727. </example>
  9728. */
  9729. function $InterpolateProvider() {
  9730. var startSymbol = '{{';
  9731. var endSymbol = '}}';
  9732. /**
  9733. * @ngdoc method
  9734. * @name $interpolateProvider#startSymbol
  9735. * @description
  9736. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  9737. *
  9738. * @param {string=} value new value to set the starting symbol to.
  9739. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9740. */
  9741. this.startSymbol = function(value) {
  9742. if (value) {
  9743. startSymbol = value;
  9744. return this;
  9745. } else {
  9746. return startSymbol;
  9747. }
  9748. };
  9749. /**
  9750. * @ngdoc method
  9751. * @name $interpolateProvider#endSymbol
  9752. * @description
  9753. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9754. *
  9755. * @param {string=} value new value to set the ending symbol to.
  9756. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9757. */
  9758. this.endSymbol = function(value) {
  9759. if (value) {
  9760. endSymbol = value;
  9761. return this;
  9762. } else {
  9763. return endSymbol;
  9764. }
  9765. };
  9766. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  9767. var startSymbolLength = startSymbol.length,
  9768. endSymbolLength = endSymbol.length,
  9769. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  9770. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  9771. function escape(ch) {
  9772. return '\\\\\\' + ch;
  9773. }
  9774. function unescapeText(text) {
  9775. return text.replace(escapedStartRegexp, startSymbol).
  9776. replace(escapedEndRegexp, endSymbol);
  9777. }
  9778. function stringify(value) {
  9779. if (value == null) { // null || undefined
  9780. return '';
  9781. }
  9782. switch (typeof value) {
  9783. case 'string':
  9784. break;
  9785. case 'number':
  9786. value = '' + value;
  9787. break;
  9788. default:
  9789. value = toJson(value);
  9790. }
  9791. return value;
  9792. }
  9793. /**
  9794. * @ngdoc service
  9795. * @name $interpolate
  9796. * @kind function
  9797. *
  9798. * @requires $parse
  9799. * @requires $sce
  9800. *
  9801. * @description
  9802. *
  9803. * Compiles a string with markup into an interpolation function. This service is used by the
  9804. * HTML {@link ng.$compile $compile} service for data binding. See
  9805. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  9806. * interpolation markup.
  9807. *
  9808. *
  9809. * ```js
  9810. * var $interpolate = ...; // injected
  9811. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9812. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  9813. * ```
  9814. *
  9815. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9816. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9817. * evaluate to a value other than `undefined`.
  9818. *
  9819. * ```js
  9820. * var $interpolate = ...; // injected
  9821. * var context = {greeting: 'Hello', name: undefined };
  9822. *
  9823. * // default "forgiving" mode
  9824. * var exp = $interpolate('{{greeting}} {{name}}!');
  9825. * expect(exp(context)).toEqual('Hello !');
  9826. *
  9827. * // "allOrNothing" mode
  9828. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9829. * expect(exp(context)).toBeUndefined();
  9830. * context.name = 'Angular';
  9831. * expect(exp(context)).toEqual('Hello Angular!');
  9832. * ```
  9833. *
  9834. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9835. *
  9836. * ####Escaped Interpolation
  9837. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9838. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9839. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9840. * or binding.
  9841. *
  9842. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9843. * degree, while also enabling code examples to work without relying on the
  9844. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9845. *
  9846. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9847. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9848. * interpolation start/end markers with their escaped counterparts.**
  9849. *
  9850. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9851. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9852. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9853. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9854. * this is typically useful only when user-data is used in rendering a template from the server, or
  9855. * when otherwise untrusted data is used by a directive.
  9856. *
  9857. * <example>
  9858. * <file name="index.html">
  9859. * <div ng-init="username='A user'">
  9860. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9861. * </p>
  9862. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9863. * application, but fails to accomplish their task, because the server has correctly
  9864. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9865. * characters.</p>
  9866. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9867. * from the database by an administrator.</p>
  9868. * </div>
  9869. * </file>
  9870. * </example>
  9871. *
  9872. * @param {string} text The text with markup to interpolate.
  9873. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9874. * embedded expression in order to return an interpolation function. Strings with no
  9875. * embedded expression will return null for the interpolation function.
  9876. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9877. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9878. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9879. * provides Strict Contextual Escaping for details.
  9880. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9881. * unless all embedded expressions evaluate to a value other than `undefined`.
  9882. * @returns {function(context)} an interpolation function which is used to compute the
  9883. * interpolated string. The function has these parameters:
  9884. *
  9885. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9886. */
  9887. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9888. allOrNothing = !!allOrNothing;
  9889. var startIndex,
  9890. endIndex,
  9891. index = 0,
  9892. expressions = [],
  9893. parseFns = [],
  9894. textLength = text.length,
  9895. exp,
  9896. concat = [],
  9897. expressionPositions = [];
  9898. while (index < textLength) {
  9899. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9900. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9901. if (index !== startIndex) {
  9902. concat.push(unescapeText(text.substring(index, startIndex)));
  9903. }
  9904. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9905. expressions.push(exp);
  9906. parseFns.push($parse(exp, parseStringifyInterceptor));
  9907. index = endIndex + endSymbolLength;
  9908. expressionPositions.push(concat.length);
  9909. concat.push('');
  9910. } else {
  9911. // we did not find an interpolation, so we have to add the remainder to the separators array
  9912. if (index !== textLength) {
  9913. concat.push(unescapeText(text.substring(index)));
  9914. }
  9915. break;
  9916. }
  9917. }
  9918. // Concatenating expressions makes it hard to reason about whether some combination of
  9919. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9920. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9921. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9922. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9923. // the load when auditing for XSS issues.
  9924. if (trustedContext && concat.length > 1) {
  9925. $interpolateMinErr.throwNoconcat(text);
  9926. }
  9927. if (!mustHaveExpression || expressions.length) {
  9928. var compute = function(values) {
  9929. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9930. if (allOrNothing && isUndefined(values[i])) return;
  9931. concat[expressionPositions[i]] = values[i];
  9932. }
  9933. return concat.join('');
  9934. };
  9935. var getValue = function(value) {
  9936. return trustedContext ?
  9937. $sce.getTrusted(trustedContext, value) :
  9938. $sce.valueOf(value);
  9939. };
  9940. return extend(function interpolationFn(context) {
  9941. var i = 0;
  9942. var ii = expressions.length;
  9943. var values = new Array(ii);
  9944. try {
  9945. for (; i < ii; i++) {
  9946. values[i] = parseFns[i](context);
  9947. }
  9948. return compute(values);
  9949. } catch (err) {
  9950. $exceptionHandler($interpolateMinErr.interr(text, err));
  9951. }
  9952. }, {
  9953. // all of these properties are undocumented for now
  9954. exp: text, //just for compatibility with regular watchers created via $watch
  9955. expressions: expressions,
  9956. $$watchDelegate: function(scope, listener) {
  9957. var lastValue;
  9958. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9959. var currValue = compute(values);
  9960. if (isFunction(listener)) {
  9961. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9962. }
  9963. lastValue = currValue;
  9964. });
  9965. }
  9966. });
  9967. }
  9968. function parseStringifyInterceptor(value) {
  9969. try {
  9970. value = getValue(value);
  9971. return allOrNothing && !isDefined(value) ? value : stringify(value);
  9972. } catch (err) {
  9973. $exceptionHandler($interpolateMinErr.interr(text, err));
  9974. }
  9975. }
  9976. }
  9977. /**
  9978. * @ngdoc method
  9979. * @name $interpolate#startSymbol
  9980. * @description
  9981. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9982. *
  9983. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9984. * the symbol.
  9985. *
  9986. * @returns {string} start symbol.
  9987. */
  9988. $interpolate.startSymbol = function() {
  9989. return startSymbol;
  9990. };
  9991. /**
  9992. * @ngdoc method
  9993. * @name $interpolate#endSymbol
  9994. * @description
  9995. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9996. *
  9997. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9998. * the symbol.
  9999. *
  10000. * @returns {string} end symbol.
  10001. */
  10002. $interpolate.endSymbol = function() {
  10003. return endSymbol;
  10004. };
  10005. return $interpolate;
  10006. }];
  10007. }
  10008. function $IntervalProvider() {
  10009. this.$get = ['$rootScope', '$window', '$q', '$$q',
  10010. function($rootScope, $window, $q, $$q) {
  10011. var intervals = {};
  10012. /**
  10013. * @ngdoc service
  10014. * @name $interval
  10015. *
  10016. * @description
  10017. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  10018. * milliseconds.
  10019. *
  10020. * The return value of registering an interval function is a promise. This promise will be
  10021. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  10022. * run indefinitely if `count` is not defined. The value of the notification will be the
  10023. * number of iterations that have run.
  10024. * To cancel an interval, call `$interval.cancel(promise)`.
  10025. *
  10026. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  10027. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  10028. * time.
  10029. *
  10030. * <div class="alert alert-warning">
  10031. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  10032. * with them. In particular they are not automatically destroyed when a controller's scope or a
  10033. * directive's element are destroyed.
  10034. * You should take this into consideration and make sure to always cancel the interval at the
  10035. * appropriate moment. See the example below for more details on how and when to do this.
  10036. * </div>
  10037. *
  10038. * @param {function()} fn A function that should be called repeatedly.
  10039. * @param {number} delay Number of milliseconds between each function call.
  10040. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  10041. * indefinitely.
  10042. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  10043. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  10044. * @param {...*=} Pass additional parameters to the executed function.
  10045. * @returns {promise} A promise which will be notified on each iteration.
  10046. *
  10047. * @example
  10048. * <example module="intervalExample">
  10049. * <file name="index.html">
  10050. * <script>
  10051. * angular.module('intervalExample', [])
  10052. * .controller('ExampleController', ['$scope', '$interval',
  10053. * function($scope, $interval) {
  10054. * $scope.format = 'M/d/yy h:mm:ss a';
  10055. * $scope.blood_1 = 100;
  10056. * $scope.blood_2 = 120;
  10057. *
  10058. * var stop;
  10059. * $scope.fight = function() {
  10060. * // Don't start a new fight if we are already fighting
  10061. * if ( angular.isDefined(stop) ) return;
  10062. *
  10063. * stop = $interval(function() {
  10064. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  10065. * $scope.blood_1 = $scope.blood_1 - 3;
  10066. * $scope.blood_2 = $scope.blood_2 - 4;
  10067. * } else {
  10068. * $scope.stopFight();
  10069. * }
  10070. * }, 100);
  10071. * };
  10072. *
  10073. * $scope.stopFight = function() {
  10074. * if (angular.isDefined(stop)) {
  10075. * $interval.cancel(stop);
  10076. * stop = undefined;
  10077. * }
  10078. * };
  10079. *
  10080. * $scope.resetFight = function() {
  10081. * $scope.blood_1 = 100;
  10082. * $scope.blood_2 = 120;
  10083. * };
  10084. *
  10085. * $scope.$on('$destroy', function() {
  10086. * // Make sure that the interval is destroyed too
  10087. * $scope.stopFight();
  10088. * });
  10089. * }])
  10090. * // Register the 'myCurrentTime' directive factory method.
  10091. * // We inject $interval and dateFilter service since the factory method is DI.
  10092. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  10093. * function($interval, dateFilter) {
  10094. * // return the directive link function. (compile function not needed)
  10095. * return function(scope, element, attrs) {
  10096. * var format, // date format
  10097. * stopTime; // so that we can cancel the time updates
  10098. *
  10099. * // used to update the UI
  10100. * function updateTime() {
  10101. * element.text(dateFilter(new Date(), format));
  10102. * }
  10103. *
  10104. * // watch the expression, and update the UI on change.
  10105. * scope.$watch(attrs.myCurrentTime, function(value) {
  10106. * format = value;
  10107. * updateTime();
  10108. * });
  10109. *
  10110. * stopTime = $interval(updateTime, 1000);
  10111. *
  10112. * // listen on DOM destroy (removal) event, and cancel the next UI update
  10113. * // to prevent updating time after the DOM element was removed.
  10114. * element.on('$destroy', function() {
  10115. * $interval.cancel(stopTime);
  10116. * });
  10117. * }
  10118. * }]);
  10119. * </script>
  10120. *
  10121. * <div>
  10122. * <div ng-controller="ExampleController">
  10123. * <label>Date format: <input ng-model="format"></label> <hr/>
  10124. * Current time is: <span my-current-time="format"></span>
  10125. * <hr/>
  10126. * Blood 1 : <font color='red'>{{blood_1}}</font>
  10127. * Blood 2 : <font color='red'>{{blood_2}}</font>
  10128. * <button type="button" data-ng-click="fight()">Fight</button>
  10129. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  10130. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  10131. * </div>
  10132. * </div>
  10133. *
  10134. * </file>
  10135. * </example>
  10136. */
  10137. function interval(fn, delay, count, invokeApply) {
  10138. var hasParams = arguments.length > 4,
  10139. args = hasParams ? sliceArgs(arguments, 4) : [],
  10140. setInterval = $window.setInterval,
  10141. clearInterval = $window.clearInterval,
  10142. iteration = 0,
  10143. skipApply = (isDefined(invokeApply) && !invokeApply),
  10144. deferred = (skipApply ? $$q : $q).defer(),
  10145. promise = deferred.promise;
  10146. count = isDefined(count) ? count : 0;
  10147. promise.then(null, null, (!hasParams) ? fn : function() {
  10148. fn.apply(null, args);
  10149. });
  10150. promise.$$intervalId = setInterval(function tick() {
  10151. deferred.notify(iteration++);
  10152. if (count > 0 && iteration >= count) {
  10153. deferred.resolve(iteration);
  10154. clearInterval(promise.$$intervalId);
  10155. delete intervals[promise.$$intervalId];
  10156. }
  10157. if (!skipApply) $rootScope.$apply();
  10158. }, delay);
  10159. intervals[promise.$$intervalId] = deferred;
  10160. return promise;
  10161. }
  10162. /**
  10163. * @ngdoc method
  10164. * @name $interval#cancel
  10165. *
  10166. * @description
  10167. * Cancels a task associated with the `promise`.
  10168. *
  10169. * @param {Promise=} promise returned by the `$interval` function.
  10170. * @returns {boolean} Returns `true` if the task was successfully canceled.
  10171. */
  10172. interval.cancel = function(promise) {
  10173. if (promise && promise.$$intervalId in intervals) {
  10174. intervals[promise.$$intervalId].reject('canceled');
  10175. $window.clearInterval(promise.$$intervalId);
  10176. delete intervals[promise.$$intervalId];
  10177. return true;
  10178. }
  10179. return false;
  10180. };
  10181. return interval;
  10182. }];
  10183. }
  10184. /**
  10185. * @ngdoc service
  10186. * @name $locale
  10187. *
  10188. * @description
  10189. * $locale service provides localization rules for various Angular components. As of right now the
  10190. * only public api is:
  10191. *
  10192. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  10193. */
  10194. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  10195. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  10196. var $locationMinErr = minErr('$location');
  10197. /**
  10198. * Encode path using encodeUriSegment, ignoring forward slashes
  10199. *
  10200. * @param {string} path Path to encode
  10201. * @returns {string}
  10202. */
  10203. function encodePath(path) {
  10204. var segments = path.split('/'),
  10205. i = segments.length;
  10206. while (i--) {
  10207. segments[i] = encodeUriSegment(segments[i]);
  10208. }
  10209. return segments.join('/');
  10210. }
  10211. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  10212. var parsedUrl = urlResolve(absoluteUrl);
  10213. locationObj.$$protocol = parsedUrl.protocol;
  10214. locationObj.$$host = parsedUrl.hostname;
  10215. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  10216. }
  10217. function parseAppUrl(relativeUrl, locationObj) {
  10218. var prefixed = (relativeUrl.charAt(0) !== '/');
  10219. if (prefixed) {
  10220. relativeUrl = '/' + relativeUrl;
  10221. }
  10222. var match = urlResolve(relativeUrl);
  10223. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  10224. match.pathname.substring(1) : match.pathname);
  10225. locationObj.$$search = parseKeyValue(match.search);
  10226. locationObj.$$hash = decodeURIComponent(match.hash);
  10227. // make sure path starts with '/';
  10228. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  10229. locationObj.$$path = '/' + locationObj.$$path;
  10230. }
  10231. }
  10232. /**
  10233. *
  10234. * @param {string} begin
  10235. * @param {string} whole
  10236. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  10237. * expected string.
  10238. */
  10239. function beginsWith(begin, whole) {
  10240. if (whole.indexOf(begin) === 0) {
  10241. return whole.substr(begin.length);
  10242. }
  10243. }
  10244. function stripHash(url) {
  10245. var index = url.indexOf('#');
  10246. return index == -1 ? url : url.substr(0, index);
  10247. }
  10248. function trimEmptyHash(url) {
  10249. return url.replace(/(#.+)|#$/, '$1');
  10250. }
  10251. function stripFile(url) {
  10252. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  10253. }
  10254. /* return the server only (scheme://host:port) */
  10255. function serverBase(url) {
  10256. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  10257. }
  10258. /**
  10259. * LocationHtml5Url represents an url
  10260. * This object is exposed as $location service when HTML5 mode is enabled and supported
  10261. *
  10262. * @constructor
  10263. * @param {string} appBase application base URL
  10264. * @param {string} appBaseNoFile application base URL stripped of any filename
  10265. * @param {string} basePrefix url path prefix
  10266. */
  10267. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  10268. this.$$html5 = true;
  10269. basePrefix = basePrefix || '';
  10270. parseAbsoluteUrl(appBase, this);
  10271. /**
  10272. * Parse given html5 (regular) url string into properties
  10273. * @param {string} url HTML5 url
  10274. * @private
  10275. */
  10276. this.$$parse = function(url) {
  10277. var pathUrl = beginsWith(appBaseNoFile, url);
  10278. if (!isString(pathUrl)) {
  10279. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  10280. appBaseNoFile);
  10281. }
  10282. parseAppUrl(pathUrl, this);
  10283. if (!this.$$path) {
  10284. this.$$path = '/';
  10285. }
  10286. this.$$compose();
  10287. };
  10288. /**
  10289. * Compose url and update `absUrl` property
  10290. * @private
  10291. */
  10292. this.$$compose = function() {
  10293. var search = toKeyValue(this.$$search),
  10294. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10295. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10296. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  10297. };
  10298. this.$$parseLinkUrl = function(url, relHref) {
  10299. if (relHref && relHref[0] === '#') {
  10300. // special case for links to hash fragments:
  10301. // keep the old url and only replace the hash fragment
  10302. this.hash(relHref.slice(1));
  10303. return true;
  10304. }
  10305. var appUrl, prevAppUrl;
  10306. var rewrittenUrl;
  10307. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  10308. prevAppUrl = appUrl;
  10309. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  10310. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  10311. } else {
  10312. rewrittenUrl = appBase + prevAppUrl;
  10313. }
  10314. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  10315. rewrittenUrl = appBaseNoFile + appUrl;
  10316. } else if (appBaseNoFile == url + '/') {
  10317. rewrittenUrl = appBaseNoFile;
  10318. }
  10319. if (rewrittenUrl) {
  10320. this.$$parse(rewrittenUrl);
  10321. }
  10322. return !!rewrittenUrl;
  10323. };
  10324. }
  10325. /**
  10326. * LocationHashbangUrl represents url
  10327. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  10328. * It also serves as the base class for html5 mode fallback on legacy browsers.
  10329. *
  10330. * @constructor
  10331. * @param {string} appBase application base URL
  10332. * @param {string} appBaseNoFile application base URL stripped of any filename
  10333. * @param {string} hashPrefix hashbang prefix
  10334. */
  10335. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  10336. parseAbsoluteUrl(appBase, this);
  10337. /**
  10338. * Parse given hashbang url into properties
  10339. * @param {string} url Hashbang url
  10340. * @private
  10341. */
  10342. this.$$parse = function(url) {
  10343. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  10344. var withoutHashUrl;
  10345. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  10346. // The rest of the url starts with a hash so we have
  10347. // got either a hashbang path or a plain hash fragment
  10348. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  10349. if (isUndefined(withoutHashUrl)) {
  10350. // There was no hashbang prefix so we just have a hash fragment
  10351. withoutHashUrl = withoutBaseUrl;
  10352. }
  10353. } else {
  10354. // There was no hashbang path nor hash fragment:
  10355. // If we are in HTML5 mode we use what is left as the path;
  10356. // Otherwise we ignore what is left
  10357. if (this.$$html5) {
  10358. withoutHashUrl = withoutBaseUrl;
  10359. } else {
  10360. withoutHashUrl = '';
  10361. if (isUndefined(withoutBaseUrl)) {
  10362. appBase = url;
  10363. this.replace();
  10364. }
  10365. }
  10366. }
  10367. parseAppUrl(withoutHashUrl, this);
  10368. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  10369. this.$$compose();
  10370. /*
  10371. * In Windows, on an anchor node on documents loaded from
  10372. * the filesystem, the browser will return a pathname
  10373. * prefixed with the drive name ('/C:/path') when a
  10374. * pathname without a drive is set:
  10375. * * a.setAttribute('href', '/foo')
  10376. * * a.pathname === '/C:/foo' //true
  10377. *
  10378. * Inside of Angular, we're always using pathnames that
  10379. * do not include drive names for routing.
  10380. */
  10381. function removeWindowsDriveName(path, url, base) {
  10382. /*
  10383. Matches paths for file protocol on windows,
  10384. such as /C:/foo/bar, and captures only /foo/bar.
  10385. */
  10386. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  10387. var firstPathSegmentMatch;
  10388. //Get the relative path from the input URL.
  10389. if (url.indexOf(base) === 0) {
  10390. url = url.replace(base, '');
  10391. }
  10392. // The input URL intentionally contains a first path segment that ends with a colon.
  10393. if (windowsFilePathExp.exec(url)) {
  10394. return path;
  10395. }
  10396. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  10397. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  10398. }
  10399. };
  10400. /**
  10401. * Compose hashbang url and update `absUrl` property
  10402. * @private
  10403. */
  10404. this.$$compose = function() {
  10405. var search = toKeyValue(this.$$search),
  10406. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10407. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10408. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  10409. };
  10410. this.$$parseLinkUrl = function(url, relHref) {
  10411. if (stripHash(appBase) == stripHash(url)) {
  10412. this.$$parse(url);
  10413. return true;
  10414. }
  10415. return false;
  10416. };
  10417. }
  10418. /**
  10419. * LocationHashbangUrl represents url
  10420. * This object is exposed as $location service when html5 history api is enabled but the browser
  10421. * does not support it.
  10422. *
  10423. * @constructor
  10424. * @param {string} appBase application base URL
  10425. * @param {string} appBaseNoFile application base URL stripped of any filename
  10426. * @param {string} hashPrefix hashbang prefix
  10427. */
  10428. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  10429. this.$$html5 = true;
  10430. LocationHashbangUrl.apply(this, arguments);
  10431. this.$$parseLinkUrl = function(url, relHref) {
  10432. if (relHref && relHref[0] === '#') {
  10433. // special case for links to hash fragments:
  10434. // keep the old url and only replace the hash fragment
  10435. this.hash(relHref.slice(1));
  10436. return true;
  10437. }
  10438. var rewrittenUrl;
  10439. var appUrl;
  10440. if (appBase == stripHash(url)) {
  10441. rewrittenUrl = url;
  10442. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  10443. rewrittenUrl = appBase + hashPrefix + appUrl;
  10444. } else if (appBaseNoFile === url + '/') {
  10445. rewrittenUrl = appBaseNoFile;
  10446. }
  10447. if (rewrittenUrl) {
  10448. this.$$parse(rewrittenUrl);
  10449. }
  10450. return !!rewrittenUrl;
  10451. };
  10452. this.$$compose = function() {
  10453. var search = toKeyValue(this.$$search),
  10454. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10455. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10456. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  10457. this.$$absUrl = appBase + hashPrefix + this.$$url;
  10458. };
  10459. }
  10460. var locationPrototype = {
  10461. /**
  10462. * Are we in html5 mode?
  10463. * @private
  10464. */
  10465. $$html5: false,
  10466. /**
  10467. * Has any change been replacing?
  10468. * @private
  10469. */
  10470. $$replace: false,
  10471. /**
  10472. * @ngdoc method
  10473. * @name $location#absUrl
  10474. *
  10475. * @description
  10476. * This method is getter only.
  10477. *
  10478. * Return full url representation with all segments encoded according to rules specified in
  10479. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  10480. *
  10481. *
  10482. * ```js
  10483. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10484. * var absUrl = $location.absUrl();
  10485. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  10486. * ```
  10487. *
  10488. * @return {string} full url
  10489. */
  10490. absUrl: locationGetter('$$absUrl'),
  10491. /**
  10492. * @ngdoc method
  10493. * @name $location#url
  10494. *
  10495. * @description
  10496. * This method is getter / setter.
  10497. *
  10498. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  10499. *
  10500. * Change path, search and hash, when called with parameter and return `$location`.
  10501. *
  10502. *
  10503. * ```js
  10504. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10505. * var url = $location.url();
  10506. * // => "/some/path?foo=bar&baz=xoxo"
  10507. * ```
  10508. *
  10509. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  10510. * @return {string} url
  10511. */
  10512. url: function(url) {
  10513. if (isUndefined(url)) {
  10514. return this.$$url;
  10515. }
  10516. var match = PATH_MATCH.exec(url);
  10517. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  10518. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  10519. this.hash(match[5] || '');
  10520. return this;
  10521. },
  10522. /**
  10523. * @ngdoc method
  10524. * @name $location#protocol
  10525. *
  10526. * @description
  10527. * This method is getter only.
  10528. *
  10529. * Return protocol of current url.
  10530. *
  10531. *
  10532. * ```js
  10533. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10534. * var protocol = $location.protocol();
  10535. * // => "http"
  10536. * ```
  10537. *
  10538. * @return {string} protocol of current url
  10539. */
  10540. protocol: locationGetter('$$protocol'),
  10541. /**
  10542. * @ngdoc method
  10543. * @name $location#host
  10544. *
  10545. * @description
  10546. * This method is getter only.
  10547. *
  10548. * Return host of current url.
  10549. *
  10550. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  10551. *
  10552. *
  10553. * ```js
  10554. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10555. * var host = $location.host();
  10556. * // => "example.com"
  10557. *
  10558. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  10559. * host = $location.host();
  10560. * // => "example.com"
  10561. * host = location.host;
  10562. * // => "example.com:8080"
  10563. * ```
  10564. *
  10565. * @return {string} host of current url.
  10566. */
  10567. host: locationGetter('$$host'),
  10568. /**
  10569. * @ngdoc method
  10570. * @name $location#port
  10571. *
  10572. * @description
  10573. * This method is getter only.
  10574. *
  10575. * Return port of current url.
  10576. *
  10577. *
  10578. * ```js
  10579. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10580. * var port = $location.port();
  10581. * // => 80
  10582. * ```
  10583. *
  10584. * @return {Number} port
  10585. */
  10586. port: locationGetter('$$port'),
  10587. /**
  10588. * @ngdoc method
  10589. * @name $location#path
  10590. *
  10591. * @description
  10592. * This method is getter / setter.
  10593. *
  10594. * Return path of current url when called without any parameter.
  10595. *
  10596. * Change path when called with parameter and return `$location`.
  10597. *
  10598. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  10599. * if it is missing.
  10600. *
  10601. *
  10602. * ```js
  10603. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10604. * var path = $location.path();
  10605. * // => "/some/path"
  10606. * ```
  10607. *
  10608. * @param {(string|number)=} path New path
  10609. * @return {string} path
  10610. */
  10611. path: locationGetterSetter('$$path', function(path) {
  10612. path = path !== null ? path.toString() : '';
  10613. return path.charAt(0) == '/' ? path : '/' + path;
  10614. }),
  10615. /**
  10616. * @ngdoc method
  10617. * @name $location#search
  10618. *
  10619. * @description
  10620. * This method is getter / setter.
  10621. *
  10622. * Return search part (as object) of current url when called without any parameter.
  10623. *
  10624. * Change search part when called with parameter and return `$location`.
  10625. *
  10626. *
  10627. * ```js
  10628. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10629. * var searchObject = $location.search();
  10630. * // => {foo: 'bar', baz: 'xoxo'}
  10631. *
  10632. * // set foo to 'yipee'
  10633. * $location.search('foo', 'yipee');
  10634. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  10635. * ```
  10636. *
  10637. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  10638. * hash object.
  10639. *
  10640. * When called with a single argument the method acts as a setter, setting the `search` component
  10641. * of `$location` to the specified value.
  10642. *
  10643. * If the argument is a hash object containing an array of values, these values will be encoded
  10644. * as duplicate search parameters in the url.
  10645. *
  10646. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  10647. * will override only a single search property.
  10648. *
  10649. * If `paramValue` is an array, it will override the property of the `search` component of
  10650. * `$location` specified via the first argument.
  10651. *
  10652. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  10653. *
  10654. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  10655. * value nor trailing equal sign.
  10656. *
  10657. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  10658. * one or more arguments returns `$location` object itself.
  10659. */
  10660. search: function(search, paramValue) {
  10661. switch (arguments.length) {
  10662. case 0:
  10663. return this.$$search;
  10664. case 1:
  10665. if (isString(search) || isNumber(search)) {
  10666. search = search.toString();
  10667. this.$$search = parseKeyValue(search);
  10668. } else if (isObject(search)) {
  10669. search = copy(search, {});
  10670. // remove object undefined or null properties
  10671. forEach(search, function(value, key) {
  10672. if (value == null) delete search[key];
  10673. });
  10674. this.$$search = search;
  10675. } else {
  10676. throw $locationMinErr('isrcharg',
  10677. 'The first argument of the `$location#search()` call must be a string or an object.');
  10678. }
  10679. break;
  10680. default:
  10681. if (isUndefined(paramValue) || paramValue === null) {
  10682. delete this.$$search[search];
  10683. } else {
  10684. this.$$search[search] = paramValue;
  10685. }
  10686. }
  10687. this.$$compose();
  10688. return this;
  10689. },
  10690. /**
  10691. * @ngdoc method
  10692. * @name $location#hash
  10693. *
  10694. * @description
  10695. * This method is getter / setter.
  10696. *
  10697. * Return hash fragment when called without any parameter.
  10698. *
  10699. * Change hash fragment when called with parameter and return `$location`.
  10700. *
  10701. *
  10702. * ```js
  10703. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  10704. * var hash = $location.hash();
  10705. * // => "hashValue"
  10706. * ```
  10707. *
  10708. * @param {(string|number)=} hash New hash fragment
  10709. * @return {string} hash
  10710. */
  10711. hash: locationGetterSetter('$$hash', function(hash) {
  10712. return hash !== null ? hash.toString() : '';
  10713. }),
  10714. /**
  10715. * @ngdoc method
  10716. * @name $location#replace
  10717. *
  10718. * @description
  10719. * If called, all changes to $location during current `$digest` will be replacing current history
  10720. * record, instead of adding new one.
  10721. */
  10722. replace: function() {
  10723. this.$$replace = true;
  10724. return this;
  10725. }
  10726. };
  10727. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  10728. Location.prototype = Object.create(locationPrototype);
  10729. /**
  10730. * @ngdoc method
  10731. * @name $location#state
  10732. *
  10733. * @description
  10734. * This method is getter / setter.
  10735. *
  10736. * Return the history state object when called without any parameter.
  10737. *
  10738. * Change the history state object when called with one parameter and return `$location`.
  10739. * The state object is later passed to `pushState` or `replaceState`.
  10740. *
  10741. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  10742. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  10743. * older browsers (like IE9 or Android < 4.0), don't use this method.
  10744. *
  10745. * @param {object=} state State object for pushState or replaceState
  10746. * @return {object} state
  10747. */
  10748. Location.prototype.state = function(state) {
  10749. if (!arguments.length) {
  10750. return this.$$state;
  10751. }
  10752. if (Location !== LocationHtml5Url || !this.$$html5) {
  10753. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10754. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10755. }
  10756. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10757. // but we're changing the $$state reference to $browser.state() during the $digest
  10758. // so the modification window is narrow.
  10759. this.$$state = isUndefined(state) ? null : state;
  10760. return this;
  10761. };
  10762. });
  10763. function locationGetter(property) {
  10764. return function() {
  10765. return this[property];
  10766. };
  10767. }
  10768. function locationGetterSetter(property, preprocess) {
  10769. return function(value) {
  10770. if (isUndefined(value)) {
  10771. return this[property];
  10772. }
  10773. this[property] = preprocess(value);
  10774. this.$$compose();
  10775. return this;
  10776. };
  10777. }
  10778. /**
  10779. * @ngdoc service
  10780. * @name $location
  10781. *
  10782. * @requires $rootElement
  10783. *
  10784. * @description
  10785. * The $location service parses the URL in the browser address bar (based on the
  10786. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10787. * available to your application. Changes to the URL in the address bar are reflected into
  10788. * $location service and changes to $location are reflected into the browser address bar.
  10789. *
  10790. * **The $location service:**
  10791. *
  10792. * - Exposes the current URL in the browser address bar, so you can
  10793. * - Watch and observe the URL.
  10794. * - Change the URL.
  10795. * - Synchronizes the URL with the browser when the user
  10796. * - Changes the address bar.
  10797. * - Clicks the back or forward button (or clicks a History link).
  10798. * - Clicks on a link.
  10799. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10800. *
  10801. * For more information see {@link guide/$location Developer Guide: Using $location}
  10802. */
  10803. /**
  10804. * @ngdoc provider
  10805. * @name $locationProvider
  10806. * @description
  10807. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10808. */
  10809. function $LocationProvider() {
  10810. var hashPrefix = '',
  10811. html5Mode = {
  10812. enabled: false,
  10813. requireBase: true,
  10814. rewriteLinks: true
  10815. };
  10816. /**
  10817. * @ngdoc method
  10818. * @name $locationProvider#hashPrefix
  10819. * @description
  10820. * @param {string=} prefix Prefix for hash part (containing path and search)
  10821. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10822. */
  10823. this.hashPrefix = function(prefix) {
  10824. if (isDefined(prefix)) {
  10825. hashPrefix = prefix;
  10826. return this;
  10827. } else {
  10828. return hashPrefix;
  10829. }
  10830. };
  10831. /**
  10832. * @ngdoc method
  10833. * @name $locationProvider#html5Mode
  10834. * @description
  10835. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10836. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10837. * properties:
  10838. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10839. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10840. * support `pushState`.
  10841. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10842. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10843. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10844. * See the {@link guide/$location $location guide for more information}
  10845. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10846. * enables/disables url rewriting for relative links.
  10847. *
  10848. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10849. */
  10850. this.html5Mode = function(mode) {
  10851. if (isBoolean(mode)) {
  10852. html5Mode.enabled = mode;
  10853. return this;
  10854. } else if (isObject(mode)) {
  10855. if (isBoolean(mode.enabled)) {
  10856. html5Mode.enabled = mode.enabled;
  10857. }
  10858. if (isBoolean(mode.requireBase)) {
  10859. html5Mode.requireBase = mode.requireBase;
  10860. }
  10861. if (isBoolean(mode.rewriteLinks)) {
  10862. html5Mode.rewriteLinks = mode.rewriteLinks;
  10863. }
  10864. return this;
  10865. } else {
  10866. return html5Mode;
  10867. }
  10868. };
  10869. /**
  10870. * @ngdoc event
  10871. * @name $location#$locationChangeStart
  10872. * @eventType broadcast on root scope
  10873. * @description
  10874. * Broadcasted before a URL will change.
  10875. *
  10876. * This change can be prevented by calling
  10877. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10878. * details about event object. Upon successful change
  10879. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10880. *
  10881. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10882. * the browser supports the HTML5 History API.
  10883. *
  10884. * @param {Object} angularEvent Synthetic event object.
  10885. * @param {string} newUrl New URL
  10886. * @param {string=} oldUrl URL that was before it was changed.
  10887. * @param {string=} newState New history state object
  10888. * @param {string=} oldState History state object that was before it was changed.
  10889. */
  10890. /**
  10891. * @ngdoc event
  10892. * @name $location#$locationChangeSuccess
  10893. * @eventType broadcast on root scope
  10894. * @description
  10895. * Broadcasted after a URL was changed.
  10896. *
  10897. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10898. * the browser supports the HTML5 History API.
  10899. *
  10900. * @param {Object} angularEvent Synthetic event object.
  10901. * @param {string} newUrl New URL
  10902. * @param {string=} oldUrl URL that was before it was changed.
  10903. * @param {string=} newState New history state object
  10904. * @param {string=} oldState History state object that was before it was changed.
  10905. */
  10906. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10907. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10908. var $location,
  10909. LocationMode,
  10910. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10911. initialUrl = $browser.url(),
  10912. appBase;
  10913. if (html5Mode.enabled) {
  10914. if (!baseHref && html5Mode.requireBase) {
  10915. throw $locationMinErr('nobase',
  10916. "$location in HTML5 mode requires a <base> tag to be present!");
  10917. }
  10918. appBase = serverBase(initialUrl) + (baseHref || '/');
  10919. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10920. } else {
  10921. appBase = stripHash(initialUrl);
  10922. LocationMode = LocationHashbangUrl;
  10923. }
  10924. var appBaseNoFile = stripFile(appBase);
  10925. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  10926. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10927. $location.$$state = $browser.state();
  10928. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10929. function setBrowserUrlWithFallback(url, replace, state) {
  10930. var oldUrl = $location.url();
  10931. var oldState = $location.$$state;
  10932. try {
  10933. $browser.url(url, replace, state);
  10934. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10935. // state object; this makes possible quick checking if the state changed in the digest
  10936. // loop. Checking deep equality would be too expensive.
  10937. $location.$$state = $browser.state();
  10938. } catch (e) {
  10939. // Restore old values if pushState fails
  10940. $location.url(oldUrl);
  10941. $location.$$state = oldState;
  10942. throw e;
  10943. }
  10944. }
  10945. $rootElement.on('click', function(event) {
  10946. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10947. // currently we open nice url link and redirect then
  10948. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  10949. var elm = jqLite(event.target);
  10950. // traverse the DOM up to find first A tag
  10951. while (nodeName_(elm[0]) !== 'a') {
  10952. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10953. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10954. }
  10955. var absHref = elm.prop('href');
  10956. // get the actual href attribute - see
  10957. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10958. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10959. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10960. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10961. // an animation.
  10962. absHref = urlResolve(absHref.animVal).href;
  10963. }
  10964. // Ignore when url is started with javascript: or mailto:
  10965. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10966. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10967. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10968. // We do a preventDefault for all urls that are part of the angular application,
  10969. // in html5mode and also without, so that we are able to abort navigation without
  10970. // getting double entries in the location history.
  10971. event.preventDefault();
  10972. // update location manually
  10973. if ($location.absUrl() != $browser.url()) {
  10974. $rootScope.$apply();
  10975. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10976. $window.angular['ff-684208-preventDefault'] = true;
  10977. }
  10978. }
  10979. }
  10980. });
  10981. // rewrite hashbang url <> html5 url
  10982. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  10983. $browser.url($location.absUrl(), true);
  10984. }
  10985. var initializing = true;
  10986. // update $location when $browser url changes
  10987. $browser.onUrlChange(function(newUrl, newState) {
  10988. if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
  10989. // If we are navigating outside of the app then force a reload
  10990. $window.location.href = newUrl;
  10991. return;
  10992. }
  10993. $rootScope.$evalAsync(function() {
  10994. var oldUrl = $location.absUrl();
  10995. var oldState = $location.$$state;
  10996. var defaultPrevented;
  10997. $location.$$parse(newUrl);
  10998. $location.$$state = newState;
  10999. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11000. newState, oldState).defaultPrevented;
  11001. // if the location was changed by a `$locationChangeStart` handler then stop
  11002. // processing this location change
  11003. if ($location.absUrl() !== newUrl) return;
  11004. if (defaultPrevented) {
  11005. $location.$$parse(oldUrl);
  11006. $location.$$state = oldState;
  11007. setBrowserUrlWithFallback(oldUrl, false, oldState);
  11008. } else {
  11009. initializing = false;
  11010. afterLocationChange(oldUrl, oldState);
  11011. }
  11012. });
  11013. if (!$rootScope.$$phase) $rootScope.$digest();
  11014. });
  11015. // update browser
  11016. $rootScope.$watch(function $locationWatch() {
  11017. var oldUrl = trimEmptyHash($browser.url());
  11018. var newUrl = trimEmptyHash($location.absUrl());
  11019. var oldState = $browser.state();
  11020. var currentReplace = $location.$$replace;
  11021. var urlOrStateChanged = oldUrl !== newUrl ||
  11022. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  11023. if (initializing || urlOrStateChanged) {
  11024. initializing = false;
  11025. $rootScope.$evalAsync(function() {
  11026. var newUrl = $location.absUrl();
  11027. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11028. $location.$$state, oldState).defaultPrevented;
  11029. // if the location was changed by a `$locationChangeStart` handler then stop
  11030. // processing this location change
  11031. if ($location.absUrl() !== newUrl) return;
  11032. if (defaultPrevented) {
  11033. $location.$$parse(oldUrl);
  11034. $location.$$state = oldState;
  11035. } else {
  11036. if (urlOrStateChanged) {
  11037. setBrowserUrlWithFallback(newUrl, currentReplace,
  11038. oldState === $location.$$state ? null : $location.$$state);
  11039. }
  11040. afterLocationChange(oldUrl, oldState);
  11041. }
  11042. });
  11043. }
  11044. $location.$$replace = false;
  11045. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  11046. // there is a change
  11047. });
  11048. return $location;
  11049. function afterLocationChange(oldUrl, oldState) {
  11050. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  11051. $location.$$state, oldState);
  11052. }
  11053. }];
  11054. }
  11055. /**
  11056. * @ngdoc service
  11057. * @name $log
  11058. * @requires $window
  11059. *
  11060. * @description
  11061. * Simple service for logging. Default implementation safely writes the message
  11062. * into the browser's console (if present).
  11063. *
  11064. * The main purpose of this service is to simplify debugging and troubleshooting.
  11065. *
  11066. * The default is to log `debug` messages. You can use
  11067. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  11068. *
  11069. * @example
  11070. <example module="logExample">
  11071. <file name="script.js">
  11072. angular.module('logExample', [])
  11073. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  11074. $scope.$log = $log;
  11075. $scope.message = 'Hello World!';
  11076. }]);
  11077. </file>
  11078. <file name="index.html">
  11079. <div ng-controller="LogController">
  11080. <p>Reload this page with open console, enter text and hit the log button...</p>
  11081. <label>Message:
  11082. <input type="text" ng-model="message" /></label>
  11083. <button ng-click="$log.log(message)">log</button>
  11084. <button ng-click="$log.warn(message)">warn</button>
  11085. <button ng-click="$log.info(message)">info</button>
  11086. <button ng-click="$log.error(message)">error</button>
  11087. <button ng-click="$log.debug(message)">debug</button>
  11088. </div>
  11089. </file>
  11090. </example>
  11091. */
  11092. /**
  11093. * @ngdoc provider
  11094. * @name $logProvider
  11095. * @description
  11096. * Use the `$logProvider` to configure how the application logs messages
  11097. */
  11098. function $LogProvider() {
  11099. var debug = true,
  11100. self = this;
  11101. /**
  11102. * @ngdoc method
  11103. * @name $logProvider#debugEnabled
  11104. * @description
  11105. * @param {boolean=} flag enable or disable debug level messages
  11106. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11107. */
  11108. this.debugEnabled = function(flag) {
  11109. if (isDefined(flag)) {
  11110. debug = flag;
  11111. return this;
  11112. } else {
  11113. return debug;
  11114. }
  11115. };
  11116. this.$get = ['$window', function($window) {
  11117. return {
  11118. /**
  11119. * @ngdoc method
  11120. * @name $log#log
  11121. *
  11122. * @description
  11123. * Write a log message
  11124. */
  11125. log: consoleLog('log'),
  11126. /**
  11127. * @ngdoc method
  11128. * @name $log#info
  11129. *
  11130. * @description
  11131. * Write an information message
  11132. */
  11133. info: consoleLog('info'),
  11134. /**
  11135. * @ngdoc method
  11136. * @name $log#warn
  11137. *
  11138. * @description
  11139. * Write a warning message
  11140. */
  11141. warn: consoleLog('warn'),
  11142. /**
  11143. * @ngdoc method
  11144. * @name $log#error
  11145. *
  11146. * @description
  11147. * Write an error message
  11148. */
  11149. error: consoleLog('error'),
  11150. /**
  11151. * @ngdoc method
  11152. * @name $log#debug
  11153. *
  11154. * @description
  11155. * Write a debug message
  11156. */
  11157. debug: (function() {
  11158. var fn = consoleLog('debug');
  11159. return function() {
  11160. if (debug) {
  11161. fn.apply(self, arguments);
  11162. }
  11163. };
  11164. }())
  11165. };
  11166. function formatError(arg) {
  11167. if (arg instanceof Error) {
  11168. if (arg.stack) {
  11169. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  11170. ? 'Error: ' + arg.message + '\n' + arg.stack
  11171. : arg.stack;
  11172. } else if (arg.sourceURL) {
  11173. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  11174. }
  11175. }
  11176. return arg;
  11177. }
  11178. function consoleLog(type) {
  11179. var console = $window.console || {},
  11180. logFn = console[type] || console.log || noop,
  11181. hasApply = false;
  11182. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  11183. // The reason behind this is that console.log has type "object" in IE8...
  11184. try {
  11185. hasApply = !!logFn.apply;
  11186. } catch (e) {}
  11187. if (hasApply) {
  11188. return function() {
  11189. var args = [];
  11190. forEach(arguments, function(arg) {
  11191. args.push(formatError(arg));
  11192. });
  11193. return logFn.apply(console, args);
  11194. };
  11195. }
  11196. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  11197. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  11198. return function(arg1, arg2) {
  11199. logFn(arg1, arg2 == null ? '' : arg2);
  11200. };
  11201. }
  11202. }];
  11203. }
  11204. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  11205. * Any commits to this file should be reviewed with security in mind. *
  11206. * Changes to this file can potentially create security vulnerabilities. *
  11207. * An approval from 2 Core members with history of modifying *
  11208. * this file is required. *
  11209. * *
  11210. * Does the change somehow allow for arbitrary javascript to be executed? *
  11211. * Or allows for someone to change the prototype of built-in objects? *
  11212. * Or gives undesired access to variables likes document or window? *
  11213. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  11214. var $parseMinErr = minErr('$parse');
  11215. // Sandboxing Angular Expressions
  11216. // ------------------------------
  11217. // Angular expressions are generally considered safe because these expressions only have direct
  11218. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  11219. // obtaining a reference to native JS functions such as the Function constructor.
  11220. //
  11221. // As an example, consider the following Angular expression:
  11222. //
  11223. // {}.toString.constructor('alert("evil JS code")')
  11224. //
  11225. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  11226. // against the expression language, but not to prevent exploits that were enabled by exposing
  11227. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  11228. // practice and therefore we are not even trying to protect against interaction with an object
  11229. // explicitly exposed in this way.
  11230. //
  11231. // In general, it is not possible to access a Window object from an angular expression unless a
  11232. // window or some DOM object that has a reference to window is published onto a Scope.
  11233. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  11234. // native objects.
  11235. //
  11236. // See https://docs.angularjs.org/guide/security
  11237. function ensureSafeMemberName(name, fullExpression) {
  11238. if (name === "__defineGetter__" || name === "__defineSetter__"
  11239. || name === "__lookupGetter__" || name === "__lookupSetter__"
  11240. || name === "__proto__") {
  11241. throw $parseMinErr('isecfld',
  11242. 'Attempting to access a disallowed field in Angular expressions! '
  11243. + 'Expression: {0}', fullExpression);
  11244. }
  11245. return name;
  11246. }
  11247. function ensureSafeObject(obj, fullExpression) {
  11248. // nifty check if obj is Function that is fast and works across iframes and other contexts
  11249. if (obj) {
  11250. if (obj.constructor === obj) {
  11251. throw $parseMinErr('isecfn',
  11252. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11253. fullExpression);
  11254. } else if (// isWindow(obj)
  11255. obj.window === obj) {
  11256. throw $parseMinErr('isecwindow',
  11257. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  11258. fullExpression);
  11259. } else if (// isElement(obj)
  11260. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  11261. throw $parseMinErr('isecdom',
  11262. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  11263. fullExpression);
  11264. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  11265. obj === Object) {
  11266. throw $parseMinErr('isecobj',
  11267. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  11268. fullExpression);
  11269. }
  11270. }
  11271. return obj;
  11272. }
  11273. var CALL = Function.prototype.call;
  11274. var APPLY = Function.prototype.apply;
  11275. var BIND = Function.prototype.bind;
  11276. function ensureSafeFunction(obj, fullExpression) {
  11277. if (obj) {
  11278. if (obj.constructor === obj) {
  11279. throw $parseMinErr('isecfn',
  11280. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11281. fullExpression);
  11282. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  11283. throw $parseMinErr('isecff',
  11284. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  11285. fullExpression);
  11286. }
  11287. }
  11288. }
  11289. var OPERATORS = createMap();
  11290. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  11291. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  11292. /////////////////////////////////////////
  11293. /**
  11294. * @constructor
  11295. */
  11296. var Lexer = function(options) {
  11297. this.options = options;
  11298. };
  11299. Lexer.prototype = {
  11300. constructor: Lexer,
  11301. lex: function(text) {
  11302. this.text = text;
  11303. this.index = 0;
  11304. this.tokens = [];
  11305. while (this.index < this.text.length) {
  11306. var ch = this.text.charAt(this.index);
  11307. if (ch === '"' || ch === "'") {
  11308. this.readString(ch);
  11309. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  11310. this.readNumber();
  11311. } else if (this.isIdent(ch)) {
  11312. this.readIdent();
  11313. } else if (this.is(ch, '(){}[].,;:?')) {
  11314. this.tokens.push({index: this.index, text: ch});
  11315. this.index++;
  11316. } else if (this.isWhitespace(ch)) {
  11317. this.index++;
  11318. } else {
  11319. var ch2 = ch + this.peek();
  11320. var ch3 = ch2 + this.peek(2);
  11321. var op1 = OPERATORS[ch];
  11322. var op2 = OPERATORS[ch2];
  11323. var op3 = OPERATORS[ch3];
  11324. if (op1 || op2 || op3) {
  11325. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  11326. this.tokens.push({index: this.index, text: token, operator: true});
  11327. this.index += token.length;
  11328. } else {
  11329. this.throwError('Unexpected next character ', this.index, this.index + 1);
  11330. }
  11331. }
  11332. }
  11333. return this.tokens;
  11334. },
  11335. is: function(ch, chars) {
  11336. return chars.indexOf(ch) !== -1;
  11337. },
  11338. peek: function(i) {
  11339. var num = i || 1;
  11340. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  11341. },
  11342. isNumber: function(ch) {
  11343. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  11344. },
  11345. isWhitespace: function(ch) {
  11346. // IE treats non-breaking space as \u00A0
  11347. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  11348. ch === '\n' || ch === '\v' || ch === '\u00A0');
  11349. },
  11350. isIdent: function(ch) {
  11351. return ('a' <= ch && ch <= 'z' ||
  11352. 'A' <= ch && ch <= 'Z' ||
  11353. '_' === ch || ch === '$');
  11354. },
  11355. isExpOperator: function(ch) {
  11356. return (ch === '-' || ch === '+' || this.isNumber(ch));
  11357. },
  11358. throwError: function(error, start, end) {
  11359. end = end || this.index;
  11360. var colStr = (isDefined(start)
  11361. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  11362. : ' ' + end);
  11363. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  11364. error, colStr, this.text);
  11365. },
  11366. readNumber: function() {
  11367. var number = '';
  11368. var start = this.index;
  11369. while (this.index < this.text.length) {
  11370. var ch = lowercase(this.text.charAt(this.index));
  11371. if (ch == '.' || this.isNumber(ch)) {
  11372. number += ch;
  11373. } else {
  11374. var peekCh = this.peek();
  11375. if (ch == 'e' && this.isExpOperator(peekCh)) {
  11376. number += ch;
  11377. } else if (this.isExpOperator(ch) &&
  11378. peekCh && this.isNumber(peekCh) &&
  11379. number.charAt(number.length - 1) == 'e') {
  11380. number += ch;
  11381. } else if (this.isExpOperator(ch) &&
  11382. (!peekCh || !this.isNumber(peekCh)) &&
  11383. number.charAt(number.length - 1) == 'e') {
  11384. this.throwError('Invalid exponent');
  11385. } else {
  11386. break;
  11387. }
  11388. }
  11389. this.index++;
  11390. }
  11391. this.tokens.push({
  11392. index: start,
  11393. text: number,
  11394. constant: true,
  11395. value: Number(number)
  11396. });
  11397. },
  11398. readIdent: function() {
  11399. var start = this.index;
  11400. while (this.index < this.text.length) {
  11401. var ch = this.text.charAt(this.index);
  11402. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  11403. break;
  11404. }
  11405. this.index++;
  11406. }
  11407. this.tokens.push({
  11408. index: start,
  11409. text: this.text.slice(start, this.index),
  11410. identifier: true
  11411. });
  11412. },
  11413. readString: function(quote) {
  11414. var start = this.index;
  11415. this.index++;
  11416. var string = '';
  11417. var rawString = quote;
  11418. var escape = false;
  11419. while (this.index < this.text.length) {
  11420. var ch = this.text.charAt(this.index);
  11421. rawString += ch;
  11422. if (escape) {
  11423. if (ch === 'u') {
  11424. var hex = this.text.substring(this.index + 1, this.index + 5);
  11425. if (!hex.match(/[\da-f]{4}/i)) {
  11426. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  11427. }
  11428. this.index += 4;
  11429. string += String.fromCharCode(parseInt(hex, 16));
  11430. } else {
  11431. var rep = ESCAPE[ch];
  11432. string = string + (rep || ch);
  11433. }
  11434. escape = false;
  11435. } else if (ch === '\\') {
  11436. escape = true;
  11437. } else if (ch === quote) {
  11438. this.index++;
  11439. this.tokens.push({
  11440. index: start,
  11441. text: rawString,
  11442. constant: true,
  11443. value: string
  11444. });
  11445. return;
  11446. } else {
  11447. string += ch;
  11448. }
  11449. this.index++;
  11450. }
  11451. this.throwError('Unterminated quote', start);
  11452. }
  11453. };
  11454. var AST = function(lexer, options) {
  11455. this.lexer = lexer;
  11456. this.options = options;
  11457. };
  11458. AST.Program = 'Program';
  11459. AST.ExpressionStatement = 'ExpressionStatement';
  11460. AST.AssignmentExpression = 'AssignmentExpression';
  11461. AST.ConditionalExpression = 'ConditionalExpression';
  11462. AST.LogicalExpression = 'LogicalExpression';
  11463. AST.BinaryExpression = 'BinaryExpression';
  11464. AST.UnaryExpression = 'UnaryExpression';
  11465. AST.CallExpression = 'CallExpression';
  11466. AST.MemberExpression = 'MemberExpression';
  11467. AST.Identifier = 'Identifier';
  11468. AST.Literal = 'Literal';
  11469. AST.ArrayExpression = 'ArrayExpression';
  11470. AST.Property = 'Property';
  11471. AST.ObjectExpression = 'ObjectExpression';
  11472. AST.ThisExpression = 'ThisExpression';
  11473. // Internal use only
  11474. AST.NGValueParameter = 'NGValueParameter';
  11475. AST.prototype = {
  11476. ast: function(text) {
  11477. this.text = text;
  11478. this.tokens = this.lexer.lex(text);
  11479. var value = this.program();
  11480. if (this.tokens.length !== 0) {
  11481. this.throwError('is an unexpected token', this.tokens[0]);
  11482. }
  11483. return value;
  11484. },
  11485. program: function() {
  11486. var body = [];
  11487. while (true) {
  11488. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  11489. body.push(this.expressionStatement());
  11490. if (!this.expect(';')) {
  11491. return { type: AST.Program, body: body};
  11492. }
  11493. }
  11494. },
  11495. expressionStatement: function() {
  11496. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  11497. },
  11498. filterChain: function() {
  11499. var left = this.expression();
  11500. var token;
  11501. while ((token = this.expect('|'))) {
  11502. left = this.filter(left);
  11503. }
  11504. return left;
  11505. },
  11506. expression: function() {
  11507. return this.assignment();
  11508. },
  11509. assignment: function() {
  11510. var result = this.ternary();
  11511. if (this.expect('=')) {
  11512. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  11513. }
  11514. return result;
  11515. },
  11516. ternary: function() {
  11517. var test = this.logicalOR();
  11518. var alternate;
  11519. var consequent;
  11520. if (this.expect('?')) {
  11521. alternate = this.expression();
  11522. if (this.consume(':')) {
  11523. consequent = this.expression();
  11524. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  11525. }
  11526. }
  11527. return test;
  11528. },
  11529. logicalOR: function() {
  11530. var left = this.logicalAND();
  11531. while (this.expect('||')) {
  11532. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  11533. }
  11534. return left;
  11535. },
  11536. logicalAND: function() {
  11537. var left = this.equality();
  11538. while (this.expect('&&')) {
  11539. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  11540. }
  11541. return left;
  11542. },
  11543. equality: function() {
  11544. var left = this.relational();
  11545. var token;
  11546. while ((token = this.expect('==','!=','===','!=='))) {
  11547. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  11548. }
  11549. return left;
  11550. },
  11551. relational: function() {
  11552. var left = this.additive();
  11553. var token;
  11554. while ((token = this.expect('<', '>', '<=', '>='))) {
  11555. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  11556. }
  11557. return left;
  11558. },
  11559. additive: function() {
  11560. var left = this.multiplicative();
  11561. var token;
  11562. while ((token = this.expect('+','-'))) {
  11563. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  11564. }
  11565. return left;
  11566. },
  11567. multiplicative: function() {
  11568. var left = this.unary();
  11569. var token;
  11570. while ((token = this.expect('*','/','%'))) {
  11571. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  11572. }
  11573. return left;
  11574. },
  11575. unary: function() {
  11576. var token;
  11577. if ((token = this.expect('+', '-', '!'))) {
  11578. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  11579. } else {
  11580. return this.primary();
  11581. }
  11582. },
  11583. primary: function() {
  11584. var primary;
  11585. if (this.expect('(')) {
  11586. primary = this.filterChain();
  11587. this.consume(')');
  11588. } else if (this.expect('[')) {
  11589. primary = this.arrayDeclaration();
  11590. } else if (this.expect('{')) {
  11591. primary = this.object();
  11592. } else if (this.constants.hasOwnProperty(this.peek().text)) {
  11593. primary = copy(this.constants[this.consume().text]);
  11594. } else if (this.peek().identifier) {
  11595. primary = this.identifier();
  11596. } else if (this.peek().constant) {
  11597. primary = this.constant();
  11598. } else {
  11599. this.throwError('not a primary expression', this.peek());
  11600. }
  11601. var next;
  11602. while ((next = this.expect('(', '[', '.'))) {
  11603. if (next.text === '(') {
  11604. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  11605. this.consume(')');
  11606. } else if (next.text === '[') {
  11607. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  11608. this.consume(']');
  11609. } else if (next.text === '.') {
  11610. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  11611. } else {
  11612. this.throwError('IMPOSSIBLE');
  11613. }
  11614. }
  11615. return primary;
  11616. },
  11617. filter: function(baseExpression) {
  11618. var args = [baseExpression];
  11619. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  11620. while (this.expect(':')) {
  11621. args.push(this.expression());
  11622. }
  11623. return result;
  11624. },
  11625. parseArguments: function() {
  11626. var args = [];
  11627. if (this.peekToken().text !== ')') {
  11628. do {
  11629. args.push(this.expression());
  11630. } while (this.expect(','));
  11631. }
  11632. return args;
  11633. },
  11634. identifier: function() {
  11635. var token = this.consume();
  11636. if (!token.identifier) {
  11637. this.throwError('is not a valid identifier', token);
  11638. }
  11639. return { type: AST.Identifier, name: token.text };
  11640. },
  11641. constant: function() {
  11642. // TODO check that it is a constant
  11643. return { type: AST.Literal, value: this.consume().value };
  11644. },
  11645. arrayDeclaration: function() {
  11646. var elements = [];
  11647. if (this.peekToken().text !== ']') {
  11648. do {
  11649. if (this.peek(']')) {
  11650. // Support trailing commas per ES5.1.
  11651. break;
  11652. }
  11653. elements.push(this.expression());
  11654. } while (this.expect(','));
  11655. }
  11656. this.consume(']');
  11657. return { type: AST.ArrayExpression, elements: elements };
  11658. },
  11659. object: function() {
  11660. var properties = [], property;
  11661. if (this.peekToken().text !== '}') {
  11662. do {
  11663. if (this.peek('}')) {
  11664. // Support trailing commas per ES5.1.
  11665. break;
  11666. }
  11667. property = {type: AST.Property, kind: 'init'};
  11668. if (this.peek().constant) {
  11669. property.key = this.constant();
  11670. } else if (this.peek().identifier) {
  11671. property.key = this.identifier();
  11672. } else {
  11673. this.throwError("invalid key", this.peek());
  11674. }
  11675. this.consume(':');
  11676. property.value = this.expression();
  11677. properties.push(property);
  11678. } while (this.expect(','));
  11679. }
  11680. this.consume('}');
  11681. return {type: AST.ObjectExpression, properties: properties };
  11682. },
  11683. throwError: function(msg, token) {
  11684. throw $parseMinErr('syntax',
  11685. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  11686. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  11687. },
  11688. consume: function(e1) {
  11689. if (this.tokens.length === 0) {
  11690. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11691. }
  11692. var token = this.expect(e1);
  11693. if (!token) {
  11694. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  11695. }
  11696. return token;
  11697. },
  11698. peekToken: function() {
  11699. if (this.tokens.length === 0) {
  11700. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11701. }
  11702. return this.tokens[0];
  11703. },
  11704. peek: function(e1, e2, e3, e4) {
  11705. return this.peekAhead(0, e1, e2, e3, e4);
  11706. },
  11707. peekAhead: function(i, e1, e2, e3, e4) {
  11708. if (this.tokens.length > i) {
  11709. var token = this.tokens[i];
  11710. var t = token.text;
  11711. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  11712. (!e1 && !e2 && !e3 && !e4)) {
  11713. return token;
  11714. }
  11715. }
  11716. return false;
  11717. },
  11718. expect: function(e1, e2, e3, e4) {
  11719. var token = this.peek(e1, e2, e3, e4);
  11720. if (token) {
  11721. this.tokens.shift();
  11722. return token;
  11723. }
  11724. return false;
  11725. },
  11726. /* `undefined` is not a constant, it is an identifier,
  11727. * but using it as an identifier is not supported
  11728. */
  11729. constants: {
  11730. 'true': { type: AST.Literal, value: true },
  11731. 'false': { type: AST.Literal, value: false },
  11732. 'null': { type: AST.Literal, value: null },
  11733. 'undefined': {type: AST.Literal, value: undefined },
  11734. 'this': {type: AST.ThisExpression }
  11735. }
  11736. };
  11737. function ifDefined(v, d) {
  11738. return typeof v !== 'undefined' ? v : d;
  11739. }
  11740. function plusFn(l, r) {
  11741. if (typeof l === 'undefined') return r;
  11742. if (typeof r === 'undefined') return l;
  11743. return l + r;
  11744. }
  11745. function isStateless($filter, filterName) {
  11746. var fn = $filter(filterName);
  11747. return !fn.$stateful;
  11748. }
  11749. function findConstantAndWatchExpressions(ast, $filter) {
  11750. var allConstants;
  11751. var argsToWatch;
  11752. switch (ast.type) {
  11753. case AST.Program:
  11754. allConstants = true;
  11755. forEach(ast.body, function(expr) {
  11756. findConstantAndWatchExpressions(expr.expression, $filter);
  11757. allConstants = allConstants && expr.expression.constant;
  11758. });
  11759. ast.constant = allConstants;
  11760. break;
  11761. case AST.Literal:
  11762. ast.constant = true;
  11763. ast.toWatch = [];
  11764. break;
  11765. case AST.UnaryExpression:
  11766. findConstantAndWatchExpressions(ast.argument, $filter);
  11767. ast.constant = ast.argument.constant;
  11768. ast.toWatch = ast.argument.toWatch;
  11769. break;
  11770. case AST.BinaryExpression:
  11771. findConstantAndWatchExpressions(ast.left, $filter);
  11772. findConstantAndWatchExpressions(ast.right, $filter);
  11773. ast.constant = ast.left.constant && ast.right.constant;
  11774. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  11775. break;
  11776. case AST.LogicalExpression:
  11777. findConstantAndWatchExpressions(ast.left, $filter);
  11778. findConstantAndWatchExpressions(ast.right, $filter);
  11779. ast.constant = ast.left.constant && ast.right.constant;
  11780. ast.toWatch = ast.constant ? [] : [ast];
  11781. break;
  11782. case AST.ConditionalExpression:
  11783. findConstantAndWatchExpressions(ast.test, $filter);
  11784. findConstantAndWatchExpressions(ast.alternate, $filter);
  11785. findConstantAndWatchExpressions(ast.consequent, $filter);
  11786. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  11787. ast.toWatch = ast.constant ? [] : [ast];
  11788. break;
  11789. case AST.Identifier:
  11790. ast.constant = false;
  11791. ast.toWatch = [ast];
  11792. break;
  11793. case AST.MemberExpression:
  11794. findConstantAndWatchExpressions(ast.object, $filter);
  11795. if (ast.computed) {
  11796. findConstantAndWatchExpressions(ast.property, $filter);
  11797. }
  11798. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  11799. ast.toWatch = [ast];
  11800. break;
  11801. case AST.CallExpression:
  11802. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  11803. argsToWatch = [];
  11804. forEach(ast.arguments, function(expr) {
  11805. findConstantAndWatchExpressions(expr, $filter);
  11806. allConstants = allConstants && expr.constant;
  11807. if (!expr.constant) {
  11808. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11809. }
  11810. });
  11811. ast.constant = allConstants;
  11812. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  11813. break;
  11814. case AST.AssignmentExpression:
  11815. findConstantAndWatchExpressions(ast.left, $filter);
  11816. findConstantAndWatchExpressions(ast.right, $filter);
  11817. ast.constant = ast.left.constant && ast.right.constant;
  11818. ast.toWatch = [ast];
  11819. break;
  11820. case AST.ArrayExpression:
  11821. allConstants = true;
  11822. argsToWatch = [];
  11823. forEach(ast.elements, function(expr) {
  11824. findConstantAndWatchExpressions(expr, $filter);
  11825. allConstants = allConstants && expr.constant;
  11826. if (!expr.constant) {
  11827. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11828. }
  11829. });
  11830. ast.constant = allConstants;
  11831. ast.toWatch = argsToWatch;
  11832. break;
  11833. case AST.ObjectExpression:
  11834. allConstants = true;
  11835. argsToWatch = [];
  11836. forEach(ast.properties, function(property) {
  11837. findConstantAndWatchExpressions(property.value, $filter);
  11838. allConstants = allConstants && property.value.constant;
  11839. if (!property.value.constant) {
  11840. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  11841. }
  11842. });
  11843. ast.constant = allConstants;
  11844. ast.toWatch = argsToWatch;
  11845. break;
  11846. case AST.ThisExpression:
  11847. ast.constant = false;
  11848. ast.toWatch = [];
  11849. break;
  11850. }
  11851. }
  11852. function getInputs(body) {
  11853. if (body.length != 1) return;
  11854. var lastExpression = body[0].expression;
  11855. var candidate = lastExpression.toWatch;
  11856. if (candidate.length !== 1) return candidate;
  11857. return candidate[0] !== lastExpression ? candidate : undefined;
  11858. }
  11859. function isAssignable(ast) {
  11860. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  11861. }
  11862. function assignableAST(ast) {
  11863. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  11864. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  11865. }
  11866. }
  11867. function isLiteral(ast) {
  11868. return ast.body.length === 0 ||
  11869. ast.body.length === 1 && (
  11870. ast.body[0].expression.type === AST.Literal ||
  11871. ast.body[0].expression.type === AST.ArrayExpression ||
  11872. ast.body[0].expression.type === AST.ObjectExpression);
  11873. }
  11874. function isConstant(ast) {
  11875. return ast.constant;
  11876. }
  11877. function ASTCompiler(astBuilder, $filter) {
  11878. this.astBuilder = astBuilder;
  11879. this.$filter = $filter;
  11880. }
  11881. ASTCompiler.prototype = {
  11882. compile: function(expression, expensiveChecks) {
  11883. var self = this;
  11884. var ast = this.astBuilder.ast(expression);
  11885. this.state = {
  11886. nextId: 0,
  11887. filters: {},
  11888. expensiveChecks: expensiveChecks,
  11889. fn: {vars: [], body: [], own: {}},
  11890. assign: {vars: [], body: [], own: {}},
  11891. inputs: []
  11892. };
  11893. findConstantAndWatchExpressions(ast, self.$filter);
  11894. var extra = '';
  11895. var assignable;
  11896. this.stage = 'assign';
  11897. if ((assignable = assignableAST(ast))) {
  11898. this.state.computing = 'assign';
  11899. var result = this.nextId();
  11900. this.recurse(assignable, result);
  11901. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  11902. }
  11903. var toWatch = getInputs(ast.body);
  11904. self.stage = 'inputs';
  11905. forEach(toWatch, function(watch, key) {
  11906. var fnKey = 'fn' + key;
  11907. self.state[fnKey] = {vars: [], body: [], own: {}};
  11908. self.state.computing = fnKey;
  11909. var intoId = self.nextId();
  11910. self.recurse(watch, intoId);
  11911. self.return_(intoId);
  11912. self.state.inputs.push(fnKey);
  11913. watch.watchId = key;
  11914. });
  11915. this.state.computing = 'fn';
  11916. this.stage = 'main';
  11917. this.recurse(ast);
  11918. var fnString =
  11919. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  11920. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  11921. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  11922. this.filterPrefix() +
  11923. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  11924. extra +
  11925. this.watchFns() +
  11926. 'return fn;';
  11927. /* jshint -W054 */
  11928. var fn = (new Function('$filter',
  11929. 'ensureSafeMemberName',
  11930. 'ensureSafeObject',
  11931. 'ensureSafeFunction',
  11932. 'ifDefined',
  11933. 'plus',
  11934. 'text',
  11935. fnString))(
  11936. this.$filter,
  11937. ensureSafeMemberName,
  11938. ensureSafeObject,
  11939. ensureSafeFunction,
  11940. ifDefined,
  11941. plusFn,
  11942. expression);
  11943. /* jshint +W054 */
  11944. this.state = this.stage = undefined;
  11945. fn.literal = isLiteral(ast);
  11946. fn.constant = isConstant(ast);
  11947. return fn;
  11948. },
  11949. USE: 'use',
  11950. STRICT: 'strict',
  11951. watchFns: function() {
  11952. var result = [];
  11953. var fns = this.state.inputs;
  11954. var self = this;
  11955. forEach(fns, function(name) {
  11956. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  11957. });
  11958. if (fns.length) {
  11959. result.push('fn.inputs=[' + fns.join(',') + '];');
  11960. }
  11961. return result.join('');
  11962. },
  11963. generateFunction: function(name, params) {
  11964. return 'function(' + params + '){' +
  11965. this.varsPrefix(name) +
  11966. this.body(name) +
  11967. '};';
  11968. },
  11969. filterPrefix: function() {
  11970. var parts = [];
  11971. var self = this;
  11972. forEach(this.state.filters, function(id, filter) {
  11973. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  11974. });
  11975. if (parts.length) return 'var ' + parts.join(',') + ';';
  11976. return '';
  11977. },
  11978. varsPrefix: function(section) {
  11979. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  11980. },
  11981. body: function(section) {
  11982. return this.state[section].body.join('');
  11983. },
  11984. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  11985. var left, right, self = this, args, expression;
  11986. recursionFn = recursionFn || noop;
  11987. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  11988. intoId = intoId || this.nextId();
  11989. this.if_('i',
  11990. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  11991. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  11992. );
  11993. return;
  11994. }
  11995. switch (ast.type) {
  11996. case AST.Program:
  11997. forEach(ast.body, function(expression, pos) {
  11998. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  11999. if (pos !== ast.body.length - 1) {
  12000. self.current().body.push(right, ';');
  12001. } else {
  12002. self.return_(right);
  12003. }
  12004. });
  12005. break;
  12006. case AST.Literal:
  12007. expression = this.escape(ast.value);
  12008. this.assign(intoId, expression);
  12009. recursionFn(expression);
  12010. break;
  12011. case AST.UnaryExpression:
  12012. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  12013. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  12014. this.assign(intoId, expression);
  12015. recursionFn(expression);
  12016. break;
  12017. case AST.BinaryExpression:
  12018. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  12019. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  12020. if (ast.operator === '+') {
  12021. expression = this.plus(left, right);
  12022. } else if (ast.operator === '-') {
  12023. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  12024. } else {
  12025. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  12026. }
  12027. this.assign(intoId, expression);
  12028. recursionFn(expression);
  12029. break;
  12030. case AST.LogicalExpression:
  12031. intoId = intoId || this.nextId();
  12032. self.recurse(ast.left, intoId);
  12033. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  12034. recursionFn(intoId);
  12035. break;
  12036. case AST.ConditionalExpression:
  12037. intoId = intoId || this.nextId();
  12038. self.recurse(ast.test, intoId);
  12039. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  12040. recursionFn(intoId);
  12041. break;
  12042. case AST.Identifier:
  12043. intoId = intoId || this.nextId();
  12044. if (nameId) {
  12045. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  12046. nameId.computed = false;
  12047. nameId.name = ast.name;
  12048. }
  12049. ensureSafeMemberName(ast.name);
  12050. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  12051. function() {
  12052. self.if_(self.stage === 'inputs' || 's', function() {
  12053. if (create && create !== 1) {
  12054. self.if_(
  12055. self.not(self.nonComputedMember('s', ast.name)),
  12056. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  12057. }
  12058. self.assign(intoId, self.nonComputedMember('s', ast.name));
  12059. });
  12060. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  12061. );
  12062. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  12063. self.addEnsureSafeObject(intoId);
  12064. }
  12065. recursionFn(intoId);
  12066. break;
  12067. case AST.MemberExpression:
  12068. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  12069. intoId = intoId || this.nextId();
  12070. self.recurse(ast.object, left, undefined, function() {
  12071. self.if_(self.notNull(left), function() {
  12072. if (ast.computed) {
  12073. right = self.nextId();
  12074. self.recurse(ast.property, right);
  12075. self.addEnsureSafeMemberName(right);
  12076. if (create && create !== 1) {
  12077. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  12078. }
  12079. expression = self.ensureSafeObject(self.computedMember(left, right));
  12080. self.assign(intoId, expression);
  12081. if (nameId) {
  12082. nameId.computed = true;
  12083. nameId.name = right;
  12084. }
  12085. } else {
  12086. ensureSafeMemberName(ast.property.name);
  12087. if (create && create !== 1) {
  12088. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  12089. }
  12090. expression = self.nonComputedMember(left, ast.property.name);
  12091. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  12092. expression = self.ensureSafeObject(expression);
  12093. }
  12094. self.assign(intoId, expression);
  12095. if (nameId) {
  12096. nameId.computed = false;
  12097. nameId.name = ast.property.name;
  12098. }
  12099. }
  12100. }, function() {
  12101. self.assign(intoId, 'undefined');
  12102. });
  12103. recursionFn(intoId);
  12104. }, !!create);
  12105. break;
  12106. case AST.CallExpression:
  12107. intoId = intoId || this.nextId();
  12108. if (ast.filter) {
  12109. right = self.filter(ast.callee.name);
  12110. args = [];
  12111. forEach(ast.arguments, function(expr) {
  12112. var argument = self.nextId();
  12113. self.recurse(expr, argument);
  12114. args.push(argument);
  12115. });
  12116. expression = right + '(' + args.join(',') + ')';
  12117. self.assign(intoId, expression);
  12118. recursionFn(intoId);
  12119. } else {
  12120. right = self.nextId();
  12121. left = {};
  12122. args = [];
  12123. self.recurse(ast.callee, right, left, function() {
  12124. self.if_(self.notNull(right), function() {
  12125. self.addEnsureSafeFunction(right);
  12126. forEach(ast.arguments, function(expr) {
  12127. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12128. args.push(self.ensureSafeObject(argument));
  12129. });
  12130. });
  12131. if (left.name) {
  12132. if (!self.state.expensiveChecks) {
  12133. self.addEnsureSafeObject(left.context);
  12134. }
  12135. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  12136. } else {
  12137. expression = right + '(' + args.join(',') + ')';
  12138. }
  12139. expression = self.ensureSafeObject(expression);
  12140. self.assign(intoId, expression);
  12141. }, function() {
  12142. self.assign(intoId, 'undefined');
  12143. });
  12144. recursionFn(intoId);
  12145. });
  12146. }
  12147. break;
  12148. case AST.AssignmentExpression:
  12149. right = this.nextId();
  12150. left = {};
  12151. if (!isAssignable(ast.left)) {
  12152. throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
  12153. }
  12154. this.recurse(ast.left, undefined, left, function() {
  12155. self.if_(self.notNull(left.context), function() {
  12156. self.recurse(ast.right, right);
  12157. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  12158. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  12159. self.assign(intoId, expression);
  12160. recursionFn(intoId || expression);
  12161. });
  12162. }, 1);
  12163. break;
  12164. case AST.ArrayExpression:
  12165. args = [];
  12166. forEach(ast.elements, function(expr) {
  12167. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12168. args.push(argument);
  12169. });
  12170. });
  12171. expression = '[' + args.join(',') + ']';
  12172. this.assign(intoId, expression);
  12173. recursionFn(expression);
  12174. break;
  12175. case AST.ObjectExpression:
  12176. args = [];
  12177. forEach(ast.properties, function(property) {
  12178. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  12179. args.push(self.escape(
  12180. property.key.type === AST.Identifier ? property.key.name :
  12181. ('' + property.key.value)) +
  12182. ':' + expr);
  12183. });
  12184. });
  12185. expression = '{' + args.join(',') + '}';
  12186. this.assign(intoId, expression);
  12187. recursionFn(expression);
  12188. break;
  12189. case AST.ThisExpression:
  12190. this.assign(intoId, 's');
  12191. recursionFn('s');
  12192. break;
  12193. case AST.NGValueParameter:
  12194. this.assign(intoId, 'v');
  12195. recursionFn('v');
  12196. break;
  12197. }
  12198. },
  12199. getHasOwnProperty: function(element, property) {
  12200. var key = element + '.' + property;
  12201. var own = this.current().own;
  12202. if (!own.hasOwnProperty(key)) {
  12203. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  12204. }
  12205. return own[key];
  12206. },
  12207. assign: function(id, value) {
  12208. if (!id) return;
  12209. this.current().body.push(id, '=', value, ';');
  12210. return id;
  12211. },
  12212. filter: function(filterName) {
  12213. if (!this.state.filters.hasOwnProperty(filterName)) {
  12214. this.state.filters[filterName] = this.nextId(true);
  12215. }
  12216. return this.state.filters[filterName];
  12217. },
  12218. ifDefined: function(id, defaultValue) {
  12219. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  12220. },
  12221. plus: function(left, right) {
  12222. return 'plus(' + left + ',' + right + ')';
  12223. },
  12224. return_: function(id) {
  12225. this.current().body.push('return ', id, ';');
  12226. },
  12227. if_: function(test, alternate, consequent) {
  12228. if (test === true) {
  12229. alternate();
  12230. } else {
  12231. var body = this.current().body;
  12232. body.push('if(', test, '){');
  12233. alternate();
  12234. body.push('}');
  12235. if (consequent) {
  12236. body.push('else{');
  12237. consequent();
  12238. body.push('}');
  12239. }
  12240. }
  12241. },
  12242. not: function(expression) {
  12243. return '!(' + expression + ')';
  12244. },
  12245. notNull: function(expression) {
  12246. return expression + '!=null';
  12247. },
  12248. nonComputedMember: function(left, right) {
  12249. return left + '.' + right;
  12250. },
  12251. computedMember: function(left, right) {
  12252. return left + '[' + right + ']';
  12253. },
  12254. member: function(left, right, computed) {
  12255. if (computed) return this.computedMember(left, right);
  12256. return this.nonComputedMember(left, right);
  12257. },
  12258. addEnsureSafeObject: function(item) {
  12259. this.current().body.push(this.ensureSafeObject(item), ';');
  12260. },
  12261. addEnsureSafeMemberName: function(item) {
  12262. this.current().body.push(this.ensureSafeMemberName(item), ';');
  12263. },
  12264. addEnsureSafeFunction: function(item) {
  12265. this.current().body.push(this.ensureSafeFunction(item), ';');
  12266. },
  12267. ensureSafeObject: function(item) {
  12268. return 'ensureSafeObject(' + item + ',text)';
  12269. },
  12270. ensureSafeMemberName: function(item) {
  12271. return 'ensureSafeMemberName(' + item + ',text)';
  12272. },
  12273. ensureSafeFunction: function(item) {
  12274. return 'ensureSafeFunction(' + item + ',text)';
  12275. },
  12276. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12277. var self = this;
  12278. return function() {
  12279. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  12280. };
  12281. },
  12282. lazyAssign: function(id, value) {
  12283. var self = this;
  12284. return function() {
  12285. self.assign(id, value);
  12286. };
  12287. },
  12288. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  12289. stringEscapeFn: function(c) {
  12290. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  12291. },
  12292. escape: function(value) {
  12293. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  12294. if (isNumber(value)) return value.toString();
  12295. if (value === true) return 'true';
  12296. if (value === false) return 'false';
  12297. if (value === null) return 'null';
  12298. if (typeof value === 'undefined') return 'undefined';
  12299. throw $parseMinErr('esc', 'IMPOSSIBLE');
  12300. },
  12301. nextId: function(skip, init) {
  12302. var id = 'v' + (this.state.nextId++);
  12303. if (!skip) {
  12304. this.current().vars.push(id + (init ? '=' + init : ''));
  12305. }
  12306. return id;
  12307. },
  12308. current: function() {
  12309. return this.state[this.state.computing];
  12310. }
  12311. };
  12312. function ASTInterpreter(astBuilder, $filter) {
  12313. this.astBuilder = astBuilder;
  12314. this.$filter = $filter;
  12315. }
  12316. ASTInterpreter.prototype = {
  12317. compile: function(expression, expensiveChecks) {
  12318. var self = this;
  12319. var ast = this.astBuilder.ast(expression);
  12320. this.expression = expression;
  12321. this.expensiveChecks = expensiveChecks;
  12322. findConstantAndWatchExpressions(ast, self.$filter);
  12323. var assignable;
  12324. var assign;
  12325. if ((assignable = assignableAST(ast))) {
  12326. assign = this.recurse(assignable);
  12327. }
  12328. var toWatch = getInputs(ast.body);
  12329. var inputs;
  12330. if (toWatch) {
  12331. inputs = [];
  12332. forEach(toWatch, function(watch, key) {
  12333. var input = self.recurse(watch);
  12334. watch.input = input;
  12335. inputs.push(input);
  12336. watch.watchId = key;
  12337. });
  12338. }
  12339. var expressions = [];
  12340. forEach(ast.body, function(expression) {
  12341. expressions.push(self.recurse(expression.expression));
  12342. });
  12343. var fn = ast.body.length === 0 ? function() {} :
  12344. ast.body.length === 1 ? expressions[0] :
  12345. function(scope, locals) {
  12346. var lastValue;
  12347. forEach(expressions, function(exp) {
  12348. lastValue = exp(scope, locals);
  12349. });
  12350. return lastValue;
  12351. };
  12352. if (assign) {
  12353. fn.assign = function(scope, value, locals) {
  12354. return assign(scope, locals, value);
  12355. };
  12356. }
  12357. if (inputs) {
  12358. fn.inputs = inputs;
  12359. }
  12360. fn.literal = isLiteral(ast);
  12361. fn.constant = isConstant(ast);
  12362. return fn;
  12363. },
  12364. recurse: function(ast, context, create) {
  12365. var left, right, self = this, args, expression;
  12366. if (ast.input) {
  12367. return this.inputs(ast.input, ast.watchId);
  12368. }
  12369. switch (ast.type) {
  12370. case AST.Literal:
  12371. return this.value(ast.value, context);
  12372. case AST.UnaryExpression:
  12373. right = this.recurse(ast.argument);
  12374. return this['unary' + ast.operator](right, context);
  12375. case AST.BinaryExpression:
  12376. left = this.recurse(ast.left);
  12377. right = this.recurse(ast.right);
  12378. return this['binary' + ast.operator](left, right, context);
  12379. case AST.LogicalExpression:
  12380. left = this.recurse(ast.left);
  12381. right = this.recurse(ast.right);
  12382. return this['binary' + ast.operator](left, right, context);
  12383. case AST.ConditionalExpression:
  12384. return this['ternary?:'](
  12385. this.recurse(ast.test),
  12386. this.recurse(ast.alternate),
  12387. this.recurse(ast.consequent),
  12388. context
  12389. );
  12390. case AST.Identifier:
  12391. ensureSafeMemberName(ast.name, self.expression);
  12392. return self.identifier(ast.name,
  12393. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  12394. context, create, self.expression);
  12395. case AST.MemberExpression:
  12396. left = this.recurse(ast.object, false, !!create);
  12397. if (!ast.computed) {
  12398. ensureSafeMemberName(ast.property.name, self.expression);
  12399. right = ast.property.name;
  12400. }
  12401. if (ast.computed) right = this.recurse(ast.property);
  12402. return ast.computed ?
  12403. this.computedMember(left, right, context, create, self.expression) :
  12404. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  12405. case AST.CallExpression:
  12406. args = [];
  12407. forEach(ast.arguments, function(expr) {
  12408. args.push(self.recurse(expr));
  12409. });
  12410. if (ast.filter) right = this.$filter(ast.callee.name);
  12411. if (!ast.filter) right = this.recurse(ast.callee, true);
  12412. return ast.filter ?
  12413. function(scope, locals, assign, inputs) {
  12414. var values = [];
  12415. for (var i = 0; i < args.length; ++i) {
  12416. values.push(args[i](scope, locals, assign, inputs));
  12417. }
  12418. var value = right.apply(undefined, values, inputs);
  12419. return context ? {context: undefined, name: undefined, value: value} : value;
  12420. } :
  12421. function(scope, locals, assign, inputs) {
  12422. var rhs = right(scope, locals, assign, inputs);
  12423. var value;
  12424. if (rhs.value != null) {
  12425. ensureSafeObject(rhs.context, self.expression);
  12426. ensureSafeFunction(rhs.value, self.expression);
  12427. var values = [];
  12428. for (var i = 0; i < args.length; ++i) {
  12429. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  12430. }
  12431. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  12432. }
  12433. return context ? {value: value} : value;
  12434. };
  12435. case AST.AssignmentExpression:
  12436. left = this.recurse(ast.left, true, 1);
  12437. right = this.recurse(ast.right);
  12438. return function(scope, locals, assign, inputs) {
  12439. var lhs = left(scope, locals, assign, inputs);
  12440. var rhs = right(scope, locals, assign, inputs);
  12441. ensureSafeObject(lhs.value, self.expression);
  12442. lhs.context[lhs.name] = rhs;
  12443. return context ? {value: rhs} : rhs;
  12444. };
  12445. case AST.ArrayExpression:
  12446. args = [];
  12447. forEach(ast.elements, function(expr) {
  12448. args.push(self.recurse(expr));
  12449. });
  12450. return function(scope, locals, assign, inputs) {
  12451. var value = [];
  12452. for (var i = 0; i < args.length; ++i) {
  12453. value.push(args[i](scope, locals, assign, inputs));
  12454. }
  12455. return context ? {value: value} : value;
  12456. };
  12457. case AST.ObjectExpression:
  12458. args = [];
  12459. forEach(ast.properties, function(property) {
  12460. args.push({key: property.key.type === AST.Identifier ?
  12461. property.key.name :
  12462. ('' + property.key.value),
  12463. value: self.recurse(property.value)
  12464. });
  12465. });
  12466. return function(scope, locals, assign, inputs) {
  12467. var value = {};
  12468. for (var i = 0; i < args.length; ++i) {
  12469. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  12470. }
  12471. return context ? {value: value} : value;
  12472. };
  12473. case AST.ThisExpression:
  12474. return function(scope) {
  12475. return context ? {value: scope} : scope;
  12476. };
  12477. case AST.NGValueParameter:
  12478. return function(scope, locals, assign, inputs) {
  12479. return context ? {value: assign} : assign;
  12480. };
  12481. }
  12482. },
  12483. 'unary+': function(argument, context) {
  12484. return function(scope, locals, assign, inputs) {
  12485. var arg = argument(scope, locals, assign, inputs);
  12486. if (isDefined(arg)) {
  12487. arg = +arg;
  12488. } else {
  12489. arg = 0;
  12490. }
  12491. return context ? {value: arg} : arg;
  12492. };
  12493. },
  12494. 'unary-': function(argument, context) {
  12495. return function(scope, locals, assign, inputs) {
  12496. var arg = argument(scope, locals, assign, inputs);
  12497. if (isDefined(arg)) {
  12498. arg = -arg;
  12499. } else {
  12500. arg = 0;
  12501. }
  12502. return context ? {value: arg} : arg;
  12503. };
  12504. },
  12505. 'unary!': function(argument, context) {
  12506. return function(scope, locals, assign, inputs) {
  12507. var arg = !argument(scope, locals, assign, inputs);
  12508. return context ? {value: arg} : arg;
  12509. };
  12510. },
  12511. 'binary+': function(left, right, context) {
  12512. return function(scope, locals, assign, inputs) {
  12513. var lhs = left(scope, locals, assign, inputs);
  12514. var rhs = right(scope, locals, assign, inputs);
  12515. var arg = plusFn(lhs, rhs);
  12516. return context ? {value: arg} : arg;
  12517. };
  12518. },
  12519. 'binary-': function(left, right, context) {
  12520. return function(scope, locals, assign, inputs) {
  12521. var lhs = left(scope, locals, assign, inputs);
  12522. var rhs = right(scope, locals, assign, inputs);
  12523. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  12524. return context ? {value: arg} : arg;
  12525. };
  12526. },
  12527. 'binary*': function(left, right, context) {
  12528. return function(scope, locals, assign, inputs) {
  12529. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  12530. return context ? {value: arg} : arg;
  12531. };
  12532. },
  12533. 'binary/': function(left, right, context) {
  12534. return function(scope, locals, assign, inputs) {
  12535. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  12536. return context ? {value: arg} : arg;
  12537. };
  12538. },
  12539. 'binary%': function(left, right, context) {
  12540. return function(scope, locals, assign, inputs) {
  12541. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  12542. return context ? {value: arg} : arg;
  12543. };
  12544. },
  12545. 'binary===': function(left, right, context) {
  12546. return function(scope, locals, assign, inputs) {
  12547. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  12548. return context ? {value: arg} : arg;
  12549. };
  12550. },
  12551. 'binary!==': function(left, right, context) {
  12552. return function(scope, locals, assign, inputs) {
  12553. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  12554. return context ? {value: arg} : arg;
  12555. };
  12556. },
  12557. 'binary==': function(left, right, context) {
  12558. return function(scope, locals, assign, inputs) {
  12559. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  12560. return context ? {value: arg} : arg;
  12561. };
  12562. },
  12563. 'binary!=': function(left, right, context) {
  12564. return function(scope, locals, assign, inputs) {
  12565. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  12566. return context ? {value: arg} : arg;
  12567. };
  12568. },
  12569. 'binary<': function(left, right, context) {
  12570. return function(scope, locals, assign, inputs) {
  12571. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  12572. return context ? {value: arg} : arg;
  12573. };
  12574. },
  12575. 'binary>': function(left, right, context) {
  12576. return function(scope, locals, assign, inputs) {
  12577. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  12578. return context ? {value: arg} : arg;
  12579. };
  12580. },
  12581. 'binary<=': function(left, right, context) {
  12582. return function(scope, locals, assign, inputs) {
  12583. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  12584. return context ? {value: arg} : arg;
  12585. };
  12586. },
  12587. 'binary>=': function(left, right, context) {
  12588. return function(scope, locals, assign, inputs) {
  12589. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  12590. return context ? {value: arg} : arg;
  12591. };
  12592. },
  12593. 'binary&&': function(left, right, context) {
  12594. return function(scope, locals, assign, inputs) {
  12595. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  12596. return context ? {value: arg} : arg;
  12597. };
  12598. },
  12599. 'binary||': function(left, right, context) {
  12600. return function(scope, locals, assign, inputs) {
  12601. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  12602. return context ? {value: arg} : arg;
  12603. };
  12604. },
  12605. 'ternary?:': function(test, alternate, consequent, context) {
  12606. return function(scope, locals, assign, inputs) {
  12607. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  12608. return context ? {value: arg} : arg;
  12609. };
  12610. },
  12611. value: function(value, context) {
  12612. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  12613. },
  12614. identifier: function(name, expensiveChecks, context, create, expression) {
  12615. return function(scope, locals, assign, inputs) {
  12616. var base = locals && (name in locals) ? locals : scope;
  12617. if (create && create !== 1 && base && !(base[name])) {
  12618. base[name] = {};
  12619. }
  12620. var value = base ? base[name] : undefined;
  12621. if (expensiveChecks) {
  12622. ensureSafeObject(value, expression);
  12623. }
  12624. if (context) {
  12625. return {context: base, name: name, value: value};
  12626. } else {
  12627. return value;
  12628. }
  12629. };
  12630. },
  12631. computedMember: function(left, right, context, create, expression) {
  12632. return function(scope, locals, assign, inputs) {
  12633. var lhs = left(scope, locals, assign, inputs);
  12634. var rhs;
  12635. var value;
  12636. if (lhs != null) {
  12637. rhs = right(scope, locals, assign, inputs);
  12638. ensureSafeMemberName(rhs, expression);
  12639. if (create && create !== 1 && lhs && !(lhs[rhs])) {
  12640. lhs[rhs] = {};
  12641. }
  12642. value = lhs[rhs];
  12643. ensureSafeObject(value, expression);
  12644. }
  12645. if (context) {
  12646. return {context: lhs, name: rhs, value: value};
  12647. } else {
  12648. return value;
  12649. }
  12650. };
  12651. },
  12652. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  12653. return function(scope, locals, assign, inputs) {
  12654. var lhs = left(scope, locals, assign, inputs);
  12655. if (create && create !== 1 && lhs && !(lhs[right])) {
  12656. lhs[right] = {};
  12657. }
  12658. var value = lhs != null ? lhs[right] : undefined;
  12659. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  12660. ensureSafeObject(value, expression);
  12661. }
  12662. if (context) {
  12663. return {context: lhs, name: right, value: value};
  12664. } else {
  12665. return value;
  12666. }
  12667. };
  12668. },
  12669. inputs: function(input, watchId) {
  12670. return function(scope, value, locals, inputs) {
  12671. if (inputs) return inputs[watchId];
  12672. return input(scope, value, locals);
  12673. };
  12674. }
  12675. };
  12676. /**
  12677. * @constructor
  12678. */
  12679. var Parser = function(lexer, $filter, options) {
  12680. this.lexer = lexer;
  12681. this.$filter = $filter;
  12682. this.options = options;
  12683. this.ast = new AST(this.lexer);
  12684. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  12685. new ASTCompiler(this.ast, $filter);
  12686. };
  12687. Parser.prototype = {
  12688. constructor: Parser,
  12689. parse: function(text) {
  12690. return this.astCompiler.compile(text, this.options.expensiveChecks);
  12691. }
  12692. };
  12693. var getterFnCacheDefault = createMap();
  12694. var getterFnCacheExpensive = createMap();
  12695. function isPossiblyDangerousMemberName(name) {
  12696. return name == 'constructor';
  12697. }
  12698. var objectValueOf = Object.prototype.valueOf;
  12699. function getValueOf(value) {
  12700. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  12701. }
  12702. ///////////////////////////////////
  12703. /**
  12704. * @ngdoc service
  12705. * @name $parse
  12706. * @kind function
  12707. *
  12708. * @description
  12709. *
  12710. * Converts Angular {@link guide/expression expression} into a function.
  12711. *
  12712. * ```js
  12713. * var getter = $parse('user.name');
  12714. * var setter = getter.assign;
  12715. * var context = {user:{name:'angular'}};
  12716. * var locals = {user:{name:'local'}};
  12717. *
  12718. * expect(getter(context)).toEqual('angular');
  12719. * setter(context, 'newValue');
  12720. * expect(context.user.name).toEqual('newValue');
  12721. * expect(getter(context, locals)).toEqual('local');
  12722. * ```
  12723. *
  12724. *
  12725. * @param {string} expression String expression to compile.
  12726. * @returns {function(context, locals)} a function which represents the compiled expression:
  12727. *
  12728. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12729. * are evaluated against (typically a scope object).
  12730. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12731. * `context`.
  12732. *
  12733. * The returned function also has the following properties:
  12734. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  12735. * literal.
  12736. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  12737. * constant literals.
  12738. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  12739. * set to a function to change its value on the given context.
  12740. *
  12741. */
  12742. /**
  12743. * @ngdoc provider
  12744. * @name $parseProvider
  12745. *
  12746. * @description
  12747. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  12748. * service.
  12749. */
  12750. function $ParseProvider() {
  12751. var cacheDefault = createMap();
  12752. var cacheExpensive = createMap();
  12753. this.$get = ['$filter', function($filter) {
  12754. var noUnsafeEval = csp().noUnsafeEval;
  12755. var $parseOptions = {
  12756. csp: noUnsafeEval,
  12757. expensiveChecks: false
  12758. },
  12759. $parseOptionsExpensive = {
  12760. csp: noUnsafeEval,
  12761. expensiveChecks: true
  12762. };
  12763. return function $parse(exp, interceptorFn, expensiveChecks) {
  12764. var parsedExpression, oneTime, cacheKey;
  12765. switch (typeof exp) {
  12766. case 'string':
  12767. exp = exp.trim();
  12768. cacheKey = exp;
  12769. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  12770. parsedExpression = cache[cacheKey];
  12771. if (!parsedExpression) {
  12772. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  12773. oneTime = true;
  12774. exp = exp.substring(2);
  12775. }
  12776. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  12777. var lexer = new Lexer(parseOptions);
  12778. var parser = new Parser(lexer, $filter, parseOptions);
  12779. parsedExpression = parser.parse(exp);
  12780. if (parsedExpression.constant) {
  12781. parsedExpression.$$watchDelegate = constantWatchDelegate;
  12782. } else if (oneTime) {
  12783. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  12784. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  12785. } else if (parsedExpression.inputs) {
  12786. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  12787. }
  12788. cache[cacheKey] = parsedExpression;
  12789. }
  12790. return addInterceptor(parsedExpression, interceptorFn);
  12791. case 'function':
  12792. return addInterceptor(exp, interceptorFn);
  12793. default:
  12794. return noop;
  12795. }
  12796. };
  12797. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  12798. if (newValue == null || oldValueOfValue == null) { // null/undefined
  12799. return newValue === oldValueOfValue;
  12800. }
  12801. if (typeof newValue === 'object') {
  12802. // attempt to convert the value to a primitive type
  12803. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  12804. // be cheaply dirty-checked
  12805. newValue = getValueOf(newValue);
  12806. if (typeof newValue === 'object') {
  12807. // objects/arrays are not supported - deep-watching them would be too expensive
  12808. return false;
  12809. }
  12810. // fall-through to the primitive equality check
  12811. }
  12812. //Primitive or NaN
  12813. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  12814. }
  12815. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  12816. var inputExpressions = parsedExpression.inputs;
  12817. var lastResult;
  12818. if (inputExpressions.length === 1) {
  12819. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12820. inputExpressions = inputExpressions[0];
  12821. return scope.$watch(function expressionInputWatch(scope) {
  12822. var newInputValue = inputExpressions(scope);
  12823. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  12824. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  12825. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  12826. }
  12827. return lastResult;
  12828. }, listener, objectEquality, prettyPrintExpression);
  12829. }
  12830. var oldInputValueOfValues = [];
  12831. var oldInputValues = [];
  12832. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12833. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12834. oldInputValues[i] = null;
  12835. }
  12836. return scope.$watch(function expressionInputsWatch(scope) {
  12837. var changed = false;
  12838. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12839. var newInputValue = inputExpressions[i](scope);
  12840. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  12841. oldInputValues[i] = newInputValue;
  12842. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  12843. }
  12844. }
  12845. if (changed) {
  12846. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  12847. }
  12848. return lastResult;
  12849. }, listener, objectEquality, prettyPrintExpression);
  12850. }
  12851. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12852. var unwatch, lastValue;
  12853. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12854. return parsedExpression(scope);
  12855. }, function oneTimeListener(value, old, scope) {
  12856. lastValue = value;
  12857. if (isFunction(listener)) {
  12858. listener.apply(this, arguments);
  12859. }
  12860. if (isDefined(value)) {
  12861. scope.$$postDigest(function() {
  12862. if (isDefined(lastValue)) {
  12863. unwatch();
  12864. }
  12865. });
  12866. }
  12867. }, objectEquality);
  12868. }
  12869. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12870. var unwatch, lastValue;
  12871. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12872. return parsedExpression(scope);
  12873. }, function oneTimeListener(value, old, scope) {
  12874. lastValue = value;
  12875. if (isFunction(listener)) {
  12876. listener.call(this, value, old, scope);
  12877. }
  12878. if (isAllDefined(value)) {
  12879. scope.$$postDigest(function() {
  12880. if (isAllDefined(lastValue)) unwatch();
  12881. });
  12882. }
  12883. }, objectEquality);
  12884. function isAllDefined(value) {
  12885. var allDefined = true;
  12886. forEach(value, function(val) {
  12887. if (!isDefined(val)) allDefined = false;
  12888. });
  12889. return allDefined;
  12890. }
  12891. }
  12892. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12893. var unwatch;
  12894. return unwatch = scope.$watch(function constantWatch(scope) {
  12895. return parsedExpression(scope);
  12896. }, function constantListener(value, old, scope) {
  12897. if (isFunction(listener)) {
  12898. listener.apply(this, arguments);
  12899. }
  12900. unwatch();
  12901. }, objectEquality);
  12902. }
  12903. function addInterceptor(parsedExpression, interceptorFn) {
  12904. if (!interceptorFn) return parsedExpression;
  12905. var watchDelegate = parsedExpression.$$watchDelegate;
  12906. var regularWatch =
  12907. watchDelegate !== oneTimeLiteralWatchDelegate &&
  12908. watchDelegate !== oneTimeWatchDelegate;
  12909. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  12910. var value = parsedExpression(scope, locals, assign, inputs);
  12911. return interceptorFn(value, scope, locals);
  12912. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  12913. var value = parsedExpression(scope, locals, assign, inputs);
  12914. var result = interceptorFn(value, scope, locals);
  12915. // we only return the interceptor's result if the
  12916. // initial value is defined (for bind-once)
  12917. return isDefined(value) ? result : value;
  12918. };
  12919. // Propagate $$watchDelegates other then inputsWatchDelegate
  12920. if (parsedExpression.$$watchDelegate &&
  12921. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  12922. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  12923. } else if (!interceptorFn.$stateful) {
  12924. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  12925. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  12926. fn.$$watchDelegate = inputsWatchDelegate;
  12927. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  12928. }
  12929. return fn;
  12930. }
  12931. }];
  12932. }
  12933. /**
  12934. * @ngdoc service
  12935. * @name $q
  12936. * @requires $rootScope
  12937. *
  12938. * @description
  12939. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  12940. * when they are done processing.
  12941. *
  12942. * This is an implementation of promises/deferred objects inspired by
  12943. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  12944. *
  12945. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  12946. * implementations, and the other which resembles ES6 promises to some degree.
  12947. *
  12948. * # $q constructor
  12949. *
  12950. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  12951. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  12952. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  12953. *
  12954. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  12955. * available yet.
  12956. *
  12957. * It can be used like so:
  12958. *
  12959. * ```js
  12960. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  12961. * // are available in the current lexical scope (they could have been injected or passed in).
  12962. *
  12963. * function asyncGreet(name) {
  12964. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  12965. * return $q(function(resolve, reject) {
  12966. * setTimeout(function() {
  12967. * if (okToGreet(name)) {
  12968. * resolve('Hello, ' + name + '!');
  12969. * } else {
  12970. * reject('Greeting ' + name + ' is not allowed.');
  12971. * }
  12972. * }, 1000);
  12973. * });
  12974. * }
  12975. *
  12976. * var promise = asyncGreet('Robin Hood');
  12977. * promise.then(function(greeting) {
  12978. * alert('Success: ' + greeting);
  12979. * }, function(reason) {
  12980. * alert('Failed: ' + reason);
  12981. * });
  12982. * ```
  12983. *
  12984. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  12985. *
  12986. * However, the more traditional CommonJS-style usage is still available, and documented below.
  12987. *
  12988. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  12989. * interface for interacting with an object that represents the result of an action that is
  12990. * performed asynchronously, and may or may not be finished at any given point in time.
  12991. *
  12992. * From the perspective of dealing with error handling, deferred and promise APIs are to
  12993. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  12994. *
  12995. * ```js
  12996. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  12997. * // are available in the current lexical scope (they could have been injected or passed in).
  12998. *
  12999. * function asyncGreet(name) {
  13000. * var deferred = $q.defer();
  13001. *
  13002. * setTimeout(function() {
  13003. * deferred.notify('About to greet ' + name + '.');
  13004. *
  13005. * if (okToGreet(name)) {
  13006. * deferred.resolve('Hello, ' + name + '!');
  13007. * } else {
  13008. * deferred.reject('Greeting ' + name + ' is not allowed.');
  13009. * }
  13010. * }, 1000);
  13011. *
  13012. * return deferred.promise;
  13013. * }
  13014. *
  13015. * var promise = asyncGreet('Robin Hood');
  13016. * promise.then(function(greeting) {
  13017. * alert('Success: ' + greeting);
  13018. * }, function(reason) {
  13019. * alert('Failed: ' + reason);
  13020. * }, function(update) {
  13021. * alert('Got notification: ' + update);
  13022. * });
  13023. * ```
  13024. *
  13025. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  13026. * comes in the way of guarantees that promise and deferred APIs make, see
  13027. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  13028. *
  13029. * Additionally the promise api allows for composition that is very hard to do with the
  13030. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  13031. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  13032. * section on serial or parallel joining of promises.
  13033. *
  13034. * # The Deferred API
  13035. *
  13036. * A new instance of deferred is constructed by calling `$q.defer()`.
  13037. *
  13038. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  13039. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  13040. * of the task.
  13041. *
  13042. * **Methods**
  13043. *
  13044. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  13045. * constructed via `$q.reject`, the promise will be rejected instead.
  13046. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  13047. * resolving it with a rejection constructed via `$q.reject`.
  13048. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  13049. * multiple times before the promise is either resolved or rejected.
  13050. *
  13051. * **Properties**
  13052. *
  13053. * - promise – `{Promise}` – promise object associated with this deferred.
  13054. *
  13055. *
  13056. * # The Promise API
  13057. *
  13058. * A new promise instance is created when a deferred instance is created and can be retrieved by
  13059. * calling `deferred.promise`.
  13060. *
  13061. * The purpose of the promise object is to allow for interested parties to get access to the result
  13062. * of the deferred task when it completes.
  13063. *
  13064. * **Methods**
  13065. *
  13066. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  13067. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  13068. * as soon as the result is available. The callbacks are called with a single argument: the result
  13069. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  13070. * provide a progress indication, before the promise is resolved or rejected.
  13071. *
  13072. * This method *returns a new promise* which is resolved or rejected via the return value of the
  13073. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  13074. * with the value which is resolved in that promise using
  13075. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  13076. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  13077. * resolved or rejected from the notifyCallback method.
  13078. *
  13079. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  13080. *
  13081. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  13082. * but to do so without modifying the final value. This is useful to release resources or do some
  13083. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  13084. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  13085. * more information.
  13086. *
  13087. * # Chaining promises
  13088. *
  13089. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  13090. * possible to create a chain of promises:
  13091. *
  13092. * ```js
  13093. * promiseB = promiseA.then(function(result) {
  13094. * return result + 1;
  13095. * });
  13096. *
  13097. * // promiseB will be resolved immediately after promiseA is resolved and its value
  13098. * // will be the result of promiseA incremented by 1
  13099. * ```
  13100. *
  13101. * It is possible to create chains of any length and since a promise can be resolved with another
  13102. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  13103. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  13104. * $http's response interceptors.
  13105. *
  13106. *
  13107. * # Differences between Kris Kowal's Q and $q
  13108. *
  13109. * There are two main differences:
  13110. *
  13111. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  13112. * mechanism in angular, which means faster propagation of resolution or rejection into your
  13113. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  13114. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  13115. * all the important functionality needed for common async tasks.
  13116. *
  13117. * # Testing
  13118. *
  13119. * ```js
  13120. * it('should simulate promise', inject(function($q, $rootScope) {
  13121. * var deferred = $q.defer();
  13122. * var promise = deferred.promise;
  13123. * var resolvedValue;
  13124. *
  13125. * promise.then(function(value) { resolvedValue = value; });
  13126. * expect(resolvedValue).toBeUndefined();
  13127. *
  13128. * // Simulate resolving of promise
  13129. * deferred.resolve(123);
  13130. * // Note that the 'then' function does not get called synchronously.
  13131. * // This is because we want the promise API to always be async, whether or not
  13132. * // it got called synchronously or asynchronously.
  13133. * expect(resolvedValue).toBeUndefined();
  13134. *
  13135. * // Propagate promise resolution to 'then' functions using $apply().
  13136. * $rootScope.$apply();
  13137. * expect(resolvedValue).toEqual(123);
  13138. * }));
  13139. * ```
  13140. *
  13141. * @param {function(function, function)} resolver Function which is responsible for resolving or
  13142. * rejecting the newly created promise. The first parameter is a function which resolves the
  13143. * promise, the second parameter is a function which rejects the promise.
  13144. *
  13145. * @returns {Promise} The newly created promise.
  13146. */
  13147. function $QProvider() {
  13148. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  13149. return qFactory(function(callback) {
  13150. $rootScope.$evalAsync(callback);
  13151. }, $exceptionHandler);
  13152. }];
  13153. }
  13154. function $$QProvider() {
  13155. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  13156. return qFactory(function(callback) {
  13157. $browser.defer(callback);
  13158. }, $exceptionHandler);
  13159. }];
  13160. }
  13161. /**
  13162. * Constructs a promise manager.
  13163. *
  13164. * @param {function(function)} nextTick Function for executing functions in the next turn.
  13165. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  13166. * debugging purposes.
  13167. * @returns {object} Promise manager.
  13168. */
  13169. function qFactory(nextTick, exceptionHandler) {
  13170. var $qMinErr = minErr('$q', TypeError);
  13171. function callOnce(self, resolveFn, rejectFn) {
  13172. var called = false;
  13173. function wrap(fn) {
  13174. return function(value) {
  13175. if (called) return;
  13176. called = true;
  13177. fn.call(self, value);
  13178. };
  13179. }
  13180. return [wrap(resolveFn), wrap(rejectFn)];
  13181. }
  13182. /**
  13183. * @ngdoc method
  13184. * @name ng.$q#defer
  13185. * @kind function
  13186. *
  13187. * @description
  13188. * Creates a `Deferred` object which represents a task which will finish in the future.
  13189. *
  13190. * @returns {Deferred} Returns a new instance of deferred.
  13191. */
  13192. var defer = function() {
  13193. return new Deferred();
  13194. };
  13195. function Promise() {
  13196. this.$$state = { status: 0 };
  13197. }
  13198. extend(Promise.prototype, {
  13199. then: function(onFulfilled, onRejected, progressBack) {
  13200. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  13201. return this;
  13202. }
  13203. var result = new Deferred();
  13204. this.$$state.pending = this.$$state.pending || [];
  13205. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  13206. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  13207. return result.promise;
  13208. },
  13209. "catch": function(callback) {
  13210. return this.then(null, callback);
  13211. },
  13212. "finally": function(callback, progressBack) {
  13213. return this.then(function(value) {
  13214. return handleCallback(value, true, callback);
  13215. }, function(error) {
  13216. return handleCallback(error, false, callback);
  13217. }, progressBack);
  13218. }
  13219. });
  13220. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  13221. function simpleBind(context, fn) {
  13222. return function(value) {
  13223. fn.call(context, value);
  13224. };
  13225. }
  13226. function processQueue(state) {
  13227. var fn, deferred, pending;
  13228. pending = state.pending;
  13229. state.processScheduled = false;
  13230. state.pending = undefined;
  13231. for (var i = 0, ii = pending.length; i < ii; ++i) {
  13232. deferred = pending[i][0];
  13233. fn = pending[i][state.status];
  13234. try {
  13235. if (isFunction(fn)) {
  13236. deferred.resolve(fn(state.value));
  13237. } else if (state.status === 1) {
  13238. deferred.resolve(state.value);
  13239. } else {
  13240. deferred.reject(state.value);
  13241. }
  13242. } catch (e) {
  13243. deferred.reject(e);
  13244. exceptionHandler(e);
  13245. }
  13246. }
  13247. }
  13248. function scheduleProcessQueue(state) {
  13249. if (state.processScheduled || !state.pending) return;
  13250. state.processScheduled = true;
  13251. nextTick(function() { processQueue(state); });
  13252. }
  13253. function Deferred() {
  13254. this.promise = new Promise();
  13255. //Necessary to support unbound execution :/
  13256. this.resolve = simpleBind(this, this.resolve);
  13257. this.reject = simpleBind(this, this.reject);
  13258. this.notify = simpleBind(this, this.notify);
  13259. }
  13260. extend(Deferred.prototype, {
  13261. resolve: function(val) {
  13262. if (this.promise.$$state.status) return;
  13263. if (val === this.promise) {
  13264. this.$$reject($qMinErr(
  13265. 'qcycle',
  13266. "Expected promise to be resolved with value other than itself '{0}'",
  13267. val));
  13268. } else {
  13269. this.$$resolve(val);
  13270. }
  13271. },
  13272. $$resolve: function(val) {
  13273. var then, fns;
  13274. fns = callOnce(this, this.$$resolve, this.$$reject);
  13275. try {
  13276. if ((isObject(val) || isFunction(val))) then = val && val.then;
  13277. if (isFunction(then)) {
  13278. this.promise.$$state.status = -1;
  13279. then.call(val, fns[0], fns[1], this.notify);
  13280. } else {
  13281. this.promise.$$state.value = val;
  13282. this.promise.$$state.status = 1;
  13283. scheduleProcessQueue(this.promise.$$state);
  13284. }
  13285. } catch (e) {
  13286. fns[1](e);
  13287. exceptionHandler(e);
  13288. }
  13289. },
  13290. reject: function(reason) {
  13291. if (this.promise.$$state.status) return;
  13292. this.$$reject(reason);
  13293. },
  13294. $$reject: function(reason) {
  13295. this.promise.$$state.value = reason;
  13296. this.promise.$$state.status = 2;
  13297. scheduleProcessQueue(this.promise.$$state);
  13298. },
  13299. notify: function(progress) {
  13300. var callbacks = this.promise.$$state.pending;
  13301. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  13302. nextTick(function() {
  13303. var callback, result;
  13304. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  13305. result = callbacks[i][0];
  13306. callback = callbacks[i][3];
  13307. try {
  13308. result.notify(isFunction(callback) ? callback(progress) : progress);
  13309. } catch (e) {
  13310. exceptionHandler(e);
  13311. }
  13312. }
  13313. });
  13314. }
  13315. }
  13316. });
  13317. /**
  13318. * @ngdoc method
  13319. * @name $q#reject
  13320. * @kind function
  13321. *
  13322. * @description
  13323. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  13324. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  13325. * a promise chain, you don't need to worry about it.
  13326. *
  13327. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  13328. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  13329. * a promise error callback and you want to forward the error to the promise derived from the
  13330. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  13331. * `reject`.
  13332. *
  13333. * ```js
  13334. * promiseB = promiseA.then(function(result) {
  13335. * // success: do something and resolve promiseB
  13336. * // with the old or a new result
  13337. * return result;
  13338. * }, function(reason) {
  13339. * // error: handle the error if possible and
  13340. * // resolve promiseB with newPromiseOrValue,
  13341. * // otherwise forward the rejection to promiseB
  13342. * if (canHandle(reason)) {
  13343. * // handle the error and recover
  13344. * return newPromiseOrValue;
  13345. * }
  13346. * return $q.reject(reason);
  13347. * });
  13348. * ```
  13349. *
  13350. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  13351. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  13352. */
  13353. var reject = function(reason) {
  13354. var result = new Deferred();
  13355. result.reject(reason);
  13356. return result.promise;
  13357. };
  13358. var makePromise = function makePromise(value, resolved) {
  13359. var result = new Deferred();
  13360. if (resolved) {
  13361. result.resolve(value);
  13362. } else {
  13363. result.reject(value);
  13364. }
  13365. return result.promise;
  13366. };
  13367. var handleCallback = function handleCallback(value, isResolved, callback) {
  13368. var callbackOutput = null;
  13369. try {
  13370. if (isFunction(callback)) callbackOutput = callback();
  13371. } catch (e) {
  13372. return makePromise(e, false);
  13373. }
  13374. if (isPromiseLike(callbackOutput)) {
  13375. return callbackOutput.then(function() {
  13376. return makePromise(value, isResolved);
  13377. }, function(error) {
  13378. return makePromise(error, false);
  13379. });
  13380. } else {
  13381. return makePromise(value, isResolved);
  13382. }
  13383. };
  13384. /**
  13385. * @ngdoc method
  13386. * @name $q#when
  13387. * @kind function
  13388. *
  13389. * @description
  13390. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  13391. * This is useful when you are dealing with an object that might or might not be a promise, or if
  13392. * the promise comes from a source that can't be trusted.
  13393. *
  13394. * @param {*} value Value or a promise
  13395. * @param {Function=} successCallback
  13396. * @param {Function=} errorCallback
  13397. * @param {Function=} progressCallback
  13398. * @returns {Promise} Returns a promise of the passed value or promise
  13399. */
  13400. var when = function(value, callback, errback, progressBack) {
  13401. var result = new Deferred();
  13402. result.resolve(value);
  13403. return result.promise.then(callback, errback, progressBack);
  13404. };
  13405. /**
  13406. * @ngdoc method
  13407. * @name $q#resolve
  13408. * @kind function
  13409. *
  13410. * @description
  13411. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  13412. *
  13413. * @param {*} value Value or a promise
  13414. * @param {Function=} successCallback
  13415. * @param {Function=} errorCallback
  13416. * @param {Function=} progressCallback
  13417. * @returns {Promise} Returns a promise of the passed value or promise
  13418. */
  13419. var resolve = when;
  13420. /**
  13421. * @ngdoc method
  13422. * @name $q#all
  13423. * @kind function
  13424. *
  13425. * @description
  13426. * Combines multiple promises into a single promise that is resolved when all of the input
  13427. * promises are resolved.
  13428. *
  13429. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  13430. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  13431. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  13432. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  13433. * with the same rejection value.
  13434. */
  13435. function all(promises) {
  13436. var deferred = new Deferred(),
  13437. counter = 0,
  13438. results = isArray(promises) ? [] : {};
  13439. forEach(promises, function(promise, key) {
  13440. counter++;
  13441. when(promise).then(function(value) {
  13442. if (results.hasOwnProperty(key)) return;
  13443. results[key] = value;
  13444. if (!(--counter)) deferred.resolve(results);
  13445. }, function(reason) {
  13446. if (results.hasOwnProperty(key)) return;
  13447. deferred.reject(reason);
  13448. });
  13449. });
  13450. if (counter === 0) {
  13451. deferred.resolve(results);
  13452. }
  13453. return deferred.promise;
  13454. }
  13455. var $Q = function Q(resolver) {
  13456. if (!isFunction(resolver)) {
  13457. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  13458. }
  13459. if (!(this instanceof Q)) {
  13460. // More useful when $Q is the Promise itself.
  13461. return new Q(resolver);
  13462. }
  13463. var deferred = new Deferred();
  13464. function resolveFn(value) {
  13465. deferred.resolve(value);
  13466. }
  13467. function rejectFn(reason) {
  13468. deferred.reject(reason);
  13469. }
  13470. resolver(resolveFn, rejectFn);
  13471. return deferred.promise;
  13472. };
  13473. $Q.defer = defer;
  13474. $Q.reject = reject;
  13475. $Q.when = when;
  13476. $Q.resolve = resolve;
  13477. $Q.all = all;
  13478. return $Q;
  13479. }
  13480. function $$RAFProvider() { //rAF
  13481. this.$get = ['$window', '$timeout', function($window, $timeout) {
  13482. var requestAnimationFrame = $window.requestAnimationFrame ||
  13483. $window.webkitRequestAnimationFrame;
  13484. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  13485. $window.webkitCancelAnimationFrame ||
  13486. $window.webkitCancelRequestAnimationFrame;
  13487. var rafSupported = !!requestAnimationFrame;
  13488. var rafFn = rafSupported
  13489. ? function(fn) {
  13490. var id = requestAnimationFrame(fn);
  13491. return function() {
  13492. cancelAnimationFrame(id);
  13493. };
  13494. }
  13495. : function(fn) {
  13496. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  13497. return function() {
  13498. $timeout.cancel(timer);
  13499. };
  13500. };
  13501. queueFn.supported = rafSupported;
  13502. var cancelLastRAF;
  13503. var taskCount = 0;
  13504. var taskQueue = [];
  13505. return queueFn;
  13506. function flush() {
  13507. for (var i = 0; i < taskQueue.length; i++) {
  13508. var task = taskQueue[i];
  13509. if (task) {
  13510. taskQueue[i] = null;
  13511. task();
  13512. }
  13513. }
  13514. taskCount = taskQueue.length = 0;
  13515. }
  13516. function queueFn(asyncFn) {
  13517. var index = taskQueue.length;
  13518. taskCount++;
  13519. taskQueue.push(asyncFn);
  13520. if (index === 0) {
  13521. cancelLastRAF = rafFn(flush);
  13522. }
  13523. return function cancelQueueFn() {
  13524. if (index >= 0) {
  13525. taskQueue[index] = null;
  13526. index = null;
  13527. if (--taskCount === 0 && cancelLastRAF) {
  13528. cancelLastRAF();
  13529. cancelLastRAF = null;
  13530. taskQueue.length = 0;
  13531. }
  13532. }
  13533. };
  13534. }
  13535. }];
  13536. }
  13537. /**
  13538. * DESIGN NOTES
  13539. *
  13540. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  13541. *
  13542. * The typical use of scope is to watch the expressions, which most of the time return the same
  13543. * value as last time so we optimize the operation.
  13544. *
  13545. * Closures construction is expensive in terms of speed as well as memory:
  13546. * - No closures, instead use prototypical inheritance for API
  13547. * - Internal state needs to be stored on scope directly, which means that private state is
  13548. * exposed as $$____ properties
  13549. *
  13550. * Loop operations are optimized by using while(count--) { ... }
  13551. * - this means that in order to keep the same order of execution as addition we have to add
  13552. * items to the array at the beginning (unshift) instead of at the end (push)
  13553. *
  13554. * Child scopes are created and removed often
  13555. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  13556. *
  13557. * There are few watches then a lot of observers. This is why you don't want the observer to be
  13558. * implemented in the same way as watch. Watch requires return of initialization function which
  13559. * are expensive to construct.
  13560. */
  13561. /**
  13562. * @ngdoc provider
  13563. * @name $rootScopeProvider
  13564. * @description
  13565. *
  13566. * Provider for the $rootScope service.
  13567. */
  13568. /**
  13569. * @ngdoc method
  13570. * @name $rootScopeProvider#digestTtl
  13571. * @description
  13572. *
  13573. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  13574. * assuming that the model is unstable.
  13575. *
  13576. * The current default is 10 iterations.
  13577. *
  13578. * In complex applications it's possible that the dependencies between `$watch`s will result in
  13579. * several digest iterations. However if an application needs more than the default 10 digest
  13580. * iterations for its model to stabilize then you should investigate what is causing the model to
  13581. * continuously change during the digest.
  13582. *
  13583. * Increasing the TTL could have performance implications, so you should not change it without
  13584. * proper justification.
  13585. *
  13586. * @param {number} limit The number of digest iterations.
  13587. */
  13588. /**
  13589. * @ngdoc service
  13590. * @name $rootScope
  13591. * @description
  13592. *
  13593. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  13594. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  13595. * between the model and the view, via a mechanism for watching the model for changes.
  13596. * They also provide an event emission/broadcast and subscription facility. See the
  13597. * {@link guide/scope developer guide on scopes}.
  13598. */
  13599. function $RootScopeProvider() {
  13600. var TTL = 10;
  13601. var $rootScopeMinErr = minErr('$rootScope');
  13602. var lastDirtyWatch = null;
  13603. var applyAsyncId = null;
  13604. this.digestTtl = function(value) {
  13605. if (arguments.length) {
  13606. TTL = value;
  13607. }
  13608. return TTL;
  13609. };
  13610. function createChildScopeClass(parent) {
  13611. function ChildScope() {
  13612. this.$$watchers = this.$$nextSibling =
  13613. this.$$childHead = this.$$childTail = null;
  13614. this.$$listeners = {};
  13615. this.$$listenerCount = {};
  13616. this.$$watchersCount = 0;
  13617. this.$id = nextUid();
  13618. this.$$ChildScope = null;
  13619. }
  13620. ChildScope.prototype = parent;
  13621. return ChildScope;
  13622. }
  13623. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  13624. function($injector, $exceptionHandler, $parse, $browser) {
  13625. function destroyChildScope($event) {
  13626. $event.currentScope.$$destroyed = true;
  13627. }
  13628. /**
  13629. * @ngdoc type
  13630. * @name $rootScope.Scope
  13631. *
  13632. * @description
  13633. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  13634. * {@link auto.$injector $injector}. Child scopes are created using the
  13635. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  13636. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  13637. * an in-depth introduction and usage examples.
  13638. *
  13639. *
  13640. * # Inheritance
  13641. * A scope can inherit from a parent scope, as in this example:
  13642. * ```js
  13643. var parent = $rootScope;
  13644. var child = parent.$new();
  13645. parent.salutation = "Hello";
  13646. expect(child.salutation).toEqual('Hello');
  13647. child.salutation = "Welcome";
  13648. expect(child.salutation).toEqual('Welcome');
  13649. expect(parent.salutation).toEqual('Hello');
  13650. * ```
  13651. *
  13652. * When interacting with `Scope` in tests, additional helper methods are available on the
  13653. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  13654. * details.
  13655. *
  13656. *
  13657. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  13658. * provided for the current scope. Defaults to {@link ng}.
  13659. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  13660. * append/override services provided by `providers`. This is handy
  13661. * when unit-testing and having the need to override a default
  13662. * service.
  13663. * @returns {Object} Newly created scope.
  13664. *
  13665. */
  13666. function Scope() {
  13667. this.$id = nextUid();
  13668. this.$$phase = this.$parent = this.$$watchers =
  13669. this.$$nextSibling = this.$$prevSibling =
  13670. this.$$childHead = this.$$childTail = null;
  13671. this.$root = this;
  13672. this.$$destroyed = false;
  13673. this.$$listeners = {};
  13674. this.$$listenerCount = {};
  13675. this.$$watchersCount = 0;
  13676. this.$$isolateBindings = null;
  13677. }
  13678. /**
  13679. * @ngdoc property
  13680. * @name $rootScope.Scope#$id
  13681. *
  13682. * @description
  13683. * Unique scope ID (monotonically increasing) useful for debugging.
  13684. */
  13685. /**
  13686. * @ngdoc property
  13687. * @name $rootScope.Scope#$parent
  13688. *
  13689. * @description
  13690. * Reference to the parent scope.
  13691. */
  13692. /**
  13693. * @ngdoc property
  13694. * @name $rootScope.Scope#$root
  13695. *
  13696. * @description
  13697. * Reference to the root scope.
  13698. */
  13699. Scope.prototype = {
  13700. constructor: Scope,
  13701. /**
  13702. * @ngdoc method
  13703. * @name $rootScope.Scope#$new
  13704. * @kind function
  13705. *
  13706. * @description
  13707. * Creates a new child {@link ng.$rootScope.Scope scope}.
  13708. *
  13709. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  13710. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  13711. *
  13712. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  13713. * desired for the scope and its child scopes to be permanently detached from the parent and
  13714. * thus stop participating in model change detection and listener notification by invoking.
  13715. *
  13716. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  13717. * parent scope. The scope is isolated, as it can not see parent scope properties.
  13718. * When creating widgets, it is useful for the widget to not accidentally read parent
  13719. * state.
  13720. *
  13721. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  13722. * of the newly created scope. Defaults to `this` scope if not provided.
  13723. * This is used when creating a transclude scope to correctly place it
  13724. * in the scope hierarchy while maintaining the correct prototypical
  13725. * inheritance.
  13726. *
  13727. * @returns {Object} The newly created child scope.
  13728. *
  13729. */
  13730. $new: function(isolate, parent) {
  13731. var child;
  13732. parent = parent || this;
  13733. if (isolate) {
  13734. child = new Scope();
  13735. child.$root = this.$root;
  13736. } else {
  13737. // Only create a child scope class if somebody asks for one,
  13738. // but cache it to allow the VM to optimize lookups.
  13739. if (!this.$$ChildScope) {
  13740. this.$$ChildScope = createChildScopeClass(this);
  13741. }
  13742. child = new this.$$ChildScope();
  13743. }
  13744. child.$parent = parent;
  13745. child.$$prevSibling = parent.$$childTail;
  13746. if (parent.$$childHead) {
  13747. parent.$$childTail.$$nextSibling = child;
  13748. parent.$$childTail = child;
  13749. } else {
  13750. parent.$$childHead = parent.$$childTail = child;
  13751. }
  13752. // When the new scope is not isolated or we inherit from `this`, and
  13753. // the parent scope is destroyed, the property `$$destroyed` is inherited
  13754. // prototypically. In all other cases, this property needs to be set
  13755. // when the parent scope is destroyed.
  13756. // The listener needs to be added after the parent is set
  13757. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  13758. return child;
  13759. },
  13760. /**
  13761. * @ngdoc method
  13762. * @name $rootScope.Scope#$watch
  13763. * @kind function
  13764. *
  13765. * @description
  13766. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  13767. *
  13768. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  13769. * $digest()} and should return the value that will be watched. (Since
  13770. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  13771. * `watchExpression` can execute multiple times per
  13772. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  13773. * - The `listener` is called only when the value from the current `watchExpression` and the
  13774. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  13775. * see below). Inequality is determined according to reference inequality,
  13776. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  13777. * via the `!==` Javascript operator, unless `objectEquality == true`
  13778. * (see next point)
  13779. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  13780. * according to the {@link angular.equals} function. To save the value of the object for
  13781. * later comparison, the {@link angular.copy} function is used. This therefore means that
  13782. * watching complex objects will have adverse memory and performance implications.
  13783. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  13784. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  13785. * iteration limit is 10 to prevent an infinite loop deadlock.
  13786. *
  13787. *
  13788. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  13789. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  13790. * multiple calls to your `watchExpression` because it will execute multiple times in a
  13791. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  13792. *
  13793. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  13794. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  13795. * watcher. In rare cases, this is undesirable because the listener is called when the result
  13796. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  13797. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  13798. * listener was called due to initialization.
  13799. *
  13800. *
  13801. *
  13802. * # Example
  13803. * ```js
  13804. // let's assume that scope was dependency injected as the $rootScope
  13805. var scope = $rootScope;
  13806. scope.name = 'misko';
  13807. scope.counter = 0;
  13808. expect(scope.counter).toEqual(0);
  13809. scope.$watch('name', function(newValue, oldValue) {
  13810. scope.counter = scope.counter + 1;
  13811. });
  13812. expect(scope.counter).toEqual(0);
  13813. scope.$digest();
  13814. // the listener is always called during the first $digest loop after it was registered
  13815. expect(scope.counter).toEqual(1);
  13816. scope.$digest();
  13817. // but now it will not be called unless the value changes
  13818. expect(scope.counter).toEqual(1);
  13819. scope.name = 'adam';
  13820. scope.$digest();
  13821. expect(scope.counter).toEqual(2);
  13822. // Using a function as a watchExpression
  13823. var food;
  13824. scope.foodCounter = 0;
  13825. expect(scope.foodCounter).toEqual(0);
  13826. scope.$watch(
  13827. // This function returns the value being watched. It is called for each turn of the $digest loop
  13828. function() { return food; },
  13829. // This is the change listener, called when the value returned from the above function changes
  13830. function(newValue, oldValue) {
  13831. if ( newValue !== oldValue ) {
  13832. // Only increment the counter if the value changed
  13833. scope.foodCounter = scope.foodCounter + 1;
  13834. }
  13835. }
  13836. );
  13837. // No digest has been run so the counter will be zero
  13838. expect(scope.foodCounter).toEqual(0);
  13839. // Run the digest but since food has not changed count will still be zero
  13840. scope.$digest();
  13841. expect(scope.foodCounter).toEqual(0);
  13842. // Update food and run digest. Now the counter will increment
  13843. food = 'cheeseburger';
  13844. scope.$digest();
  13845. expect(scope.foodCounter).toEqual(1);
  13846. * ```
  13847. *
  13848. *
  13849. *
  13850. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  13851. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  13852. * a call to the `listener`.
  13853. *
  13854. * - `string`: Evaluated as {@link guide/expression expression}
  13855. * - `function(scope)`: called with current `scope` as a parameter.
  13856. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  13857. * of `watchExpression` changes.
  13858. *
  13859. * - `newVal` contains the current value of the `watchExpression`
  13860. * - `oldVal` contains the previous value of the `watchExpression`
  13861. * - `scope` refers to the current scope
  13862. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  13863. * comparing for reference equality.
  13864. * @returns {function()} Returns a deregistration function for this listener.
  13865. */
  13866. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  13867. var get = $parse(watchExp);
  13868. if (get.$$watchDelegate) {
  13869. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  13870. }
  13871. var scope = this,
  13872. array = scope.$$watchers,
  13873. watcher = {
  13874. fn: listener,
  13875. last: initWatchVal,
  13876. get: get,
  13877. exp: prettyPrintExpression || watchExp,
  13878. eq: !!objectEquality
  13879. };
  13880. lastDirtyWatch = null;
  13881. if (!isFunction(listener)) {
  13882. watcher.fn = noop;
  13883. }
  13884. if (!array) {
  13885. array = scope.$$watchers = [];
  13886. }
  13887. // we use unshift since we use a while loop in $digest for speed.
  13888. // the while loop reads in reverse order.
  13889. array.unshift(watcher);
  13890. incrementWatchersCount(this, 1);
  13891. return function deregisterWatch() {
  13892. if (arrayRemove(array, watcher) >= 0) {
  13893. incrementWatchersCount(scope, -1);
  13894. }
  13895. lastDirtyWatch = null;
  13896. };
  13897. },
  13898. /**
  13899. * @ngdoc method
  13900. * @name $rootScope.Scope#$watchGroup
  13901. * @kind function
  13902. *
  13903. * @description
  13904. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  13905. * If any one expression in the collection changes the `listener` is executed.
  13906. *
  13907. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  13908. * call to $digest() to see if any items changes.
  13909. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  13910. *
  13911. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  13912. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  13913. *
  13914. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  13915. * expression in `watchExpressions` changes
  13916. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  13917. * those of `watchExpression`
  13918. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  13919. * those of `watchExpression`
  13920. * The `scope` refers to the current scope.
  13921. * @returns {function()} Returns a de-registration function for all listeners.
  13922. */
  13923. $watchGroup: function(watchExpressions, listener) {
  13924. var oldValues = new Array(watchExpressions.length);
  13925. var newValues = new Array(watchExpressions.length);
  13926. var deregisterFns = [];
  13927. var self = this;
  13928. var changeReactionScheduled = false;
  13929. var firstRun = true;
  13930. if (!watchExpressions.length) {
  13931. // No expressions means we call the listener ASAP
  13932. var shouldCall = true;
  13933. self.$evalAsync(function() {
  13934. if (shouldCall) listener(newValues, newValues, self);
  13935. });
  13936. return function deregisterWatchGroup() {
  13937. shouldCall = false;
  13938. };
  13939. }
  13940. if (watchExpressions.length === 1) {
  13941. // Special case size of one
  13942. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  13943. newValues[0] = value;
  13944. oldValues[0] = oldValue;
  13945. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  13946. });
  13947. }
  13948. forEach(watchExpressions, function(expr, i) {
  13949. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  13950. newValues[i] = value;
  13951. oldValues[i] = oldValue;
  13952. if (!changeReactionScheduled) {
  13953. changeReactionScheduled = true;
  13954. self.$evalAsync(watchGroupAction);
  13955. }
  13956. });
  13957. deregisterFns.push(unwatchFn);
  13958. });
  13959. function watchGroupAction() {
  13960. changeReactionScheduled = false;
  13961. if (firstRun) {
  13962. firstRun = false;
  13963. listener(newValues, newValues, self);
  13964. } else {
  13965. listener(newValues, oldValues, self);
  13966. }
  13967. }
  13968. return function deregisterWatchGroup() {
  13969. while (deregisterFns.length) {
  13970. deregisterFns.shift()();
  13971. }
  13972. };
  13973. },
  13974. /**
  13975. * @ngdoc method
  13976. * @name $rootScope.Scope#$watchCollection
  13977. * @kind function
  13978. *
  13979. * @description
  13980. * Shallow watches the properties of an object and fires whenever any of the properties change
  13981. * (for arrays, this implies watching the array items; for object maps, this implies watching
  13982. * the properties). If a change is detected, the `listener` callback is fired.
  13983. *
  13984. * - The `obj` collection is observed via standard $watch operation and is examined on every
  13985. * call to $digest() to see if any items have been added, removed, or moved.
  13986. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  13987. * adding, removing, and moving items belonging to an object or array.
  13988. *
  13989. *
  13990. * # Example
  13991. * ```js
  13992. $scope.names = ['igor', 'matias', 'misko', 'james'];
  13993. $scope.dataCount = 4;
  13994. $scope.$watchCollection('names', function(newNames, oldNames) {
  13995. $scope.dataCount = newNames.length;
  13996. });
  13997. expect($scope.dataCount).toEqual(4);
  13998. $scope.$digest();
  13999. //still at 4 ... no changes
  14000. expect($scope.dataCount).toEqual(4);
  14001. $scope.names.pop();
  14002. $scope.$digest();
  14003. //now there's been a change
  14004. expect($scope.dataCount).toEqual(3);
  14005. * ```
  14006. *
  14007. *
  14008. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  14009. * expression value should evaluate to an object or an array which is observed on each
  14010. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  14011. * collection will trigger a call to the `listener`.
  14012. *
  14013. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  14014. * when a change is detected.
  14015. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  14016. * - The `oldCollection` object is a copy of the former collection data.
  14017. * Due to performance considerations, the`oldCollection` value is computed only if the
  14018. * `listener` function declares two or more arguments.
  14019. * - The `scope` argument refers to the current scope.
  14020. *
  14021. * @returns {function()} Returns a de-registration function for this listener. When the
  14022. * de-registration function is executed, the internal watch operation is terminated.
  14023. */
  14024. $watchCollection: function(obj, listener) {
  14025. $watchCollectionInterceptor.$stateful = true;
  14026. var self = this;
  14027. // the current value, updated on each dirty-check run
  14028. var newValue;
  14029. // a shallow copy of the newValue from the last dirty-check run,
  14030. // updated to match newValue during dirty-check run
  14031. var oldValue;
  14032. // a shallow copy of the newValue from when the last change happened
  14033. var veryOldValue;
  14034. // only track veryOldValue if the listener is asking for it
  14035. var trackVeryOldValue = (listener.length > 1);
  14036. var changeDetected = 0;
  14037. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  14038. var internalArray = [];
  14039. var internalObject = {};
  14040. var initRun = true;
  14041. var oldLength = 0;
  14042. function $watchCollectionInterceptor(_value) {
  14043. newValue = _value;
  14044. var newLength, key, bothNaN, newItem, oldItem;
  14045. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  14046. if (isUndefined(newValue)) return;
  14047. if (!isObject(newValue)) { // if primitive
  14048. if (oldValue !== newValue) {
  14049. oldValue = newValue;
  14050. changeDetected++;
  14051. }
  14052. } else if (isArrayLike(newValue)) {
  14053. if (oldValue !== internalArray) {
  14054. // we are transitioning from something which was not an array into array.
  14055. oldValue = internalArray;
  14056. oldLength = oldValue.length = 0;
  14057. changeDetected++;
  14058. }
  14059. newLength = newValue.length;
  14060. if (oldLength !== newLength) {
  14061. // if lengths do not match we need to trigger change notification
  14062. changeDetected++;
  14063. oldValue.length = oldLength = newLength;
  14064. }
  14065. // copy the items to oldValue and look for changes.
  14066. for (var i = 0; i < newLength; i++) {
  14067. oldItem = oldValue[i];
  14068. newItem = newValue[i];
  14069. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14070. if (!bothNaN && (oldItem !== newItem)) {
  14071. changeDetected++;
  14072. oldValue[i] = newItem;
  14073. }
  14074. }
  14075. } else {
  14076. if (oldValue !== internalObject) {
  14077. // we are transitioning from something which was not an object into object.
  14078. oldValue = internalObject = {};
  14079. oldLength = 0;
  14080. changeDetected++;
  14081. }
  14082. // copy the items to oldValue and look for changes.
  14083. newLength = 0;
  14084. for (key in newValue) {
  14085. if (newValue.hasOwnProperty(key)) {
  14086. newLength++;
  14087. newItem = newValue[key];
  14088. oldItem = oldValue[key];
  14089. if (key in oldValue) {
  14090. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14091. if (!bothNaN && (oldItem !== newItem)) {
  14092. changeDetected++;
  14093. oldValue[key] = newItem;
  14094. }
  14095. } else {
  14096. oldLength++;
  14097. oldValue[key] = newItem;
  14098. changeDetected++;
  14099. }
  14100. }
  14101. }
  14102. if (oldLength > newLength) {
  14103. // we used to have more keys, need to find them and destroy them.
  14104. changeDetected++;
  14105. for (key in oldValue) {
  14106. if (!newValue.hasOwnProperty(key)) {
  14107. oldLength--;
  14108. delete oldValue[key];
  14109. }
  14110. }
  14111. }
  14112. }
  14113. return changeDetected;
  14114. }
  14115. function $watchCollectionAction() {
  14116. if (initRun) {
  14117. initRun = false;
  14118. listener(newValue, newValue, self);
  14119. } else {
  14120. listener(newValue, veryOldValue, self);
  14121. }
  14122. // make a copy for the next time a collection is changed
  14123. if (trackVeryOldValue) {
  14124. if (!isObject(newValue)) {
  14125. //primitive
  14126. veryOldValue = newValue;
  14127. } else if (isArrayLike(newValue)) {
  14128. veryOldValue = new Array(newValue.length);
  14129. for (var i = 0; i < newValue.length; i++) {
  14130. veryOldValue[i] = newValue[i];
  14131. }
  14132. } else { // if object
  14133. veryOldValue = {};
  14134. for (var key in newValue) {
  14135. if (hasOwnProperty.call(newValue, key)) {
  14136. veryOldValue[key] = newValue[key];
  14137. }
  14138. }
  14139. }
  14140. }
  14141. }
  14142. return this.$watch(changeDetector, $watchCollectionAction);
  14143. },
  14144. /**
  14145. * @ngdoc method
  14146. * @name $rootScope.Scope#$digest
  14147. * @kind function
  14148. *
  14149. * @description
  14150. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  14151. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  14152. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  14153. * until no more listeners are firing. This means that it is possible to get into an infinite
  14154. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  14155. * iterations exceeds 10.
  14156. *
  14157. * Usually, you don't call `$digest()` directly in
  14158. * {@link ng.directive:ngController controllers} or in
  14159. * {@link ng.$compileProvider#directive directives}.
  14160. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  14161. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  14162. *
  14163. * If you want to be notified whenever `$digest()` is called,
  14164. * you can register a `watchExpression` function with
  14165. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  14166. *
  14167. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  14168. *
  14169. * # Example
  14170. * ```js
  14171. var scope = ...;
  14172. scope.name = 'misko';
  14173. scope.counter = 0;
  14174. expect(scope.counter).toEqual(0);
  14175. scope.$watch('name', function(newValue, oldValue) {
  14176. scope.counter = scope.counter + 1;
  14177. });
  14178. expect(scope.counter).toEqual(0);
  14179. scope.$digest();
  14180. // the listener is always called during the first $digest loop after it was registered
  14181. expect(scope.counter).toEqual(1);
  14182. scope.$digest();
  14183. // but now it will not be called unless the value changes
  14184. expect(scope.counter).toEqual(1);
  14185. scope.name = 'adam';
  14186. scope.$digest();
  14187. expect(scope.counter).toEqual(2);
  14188. * ```
  14189. *
  14190. */
  14191. $digest: function() {
  14192. var watch, value, last,
  14193. watchers,
  14194. length,
  14195. dirty, ttl = TTL,
  14196. next, current, target = this,
  14197. watchLog = [],
  14198. logIdx, logMsg, asyncTask;
  14199. beginPhase('$digest');
  14200. // Check for changes to browser url that happened in sync before the call to $digest
  14201. $browser.$$checkUrlChange();
  14202. if (this === $rootScope && applyAsyncId !== null) {
  14203. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  14204. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  14205. $browser.defer.cancel(applyAsyncId);
  14206. flushApplyAsync();
  14207. }
  14208. lastDirtyWatch = null;
  14209. do { // "while dirty" loop
  14210. dirty = false;
  14211. current = target;
  14212. while (asyncQueue.length) {
  14213. try {
  14214. asyncTask = asyncQueue.shift();
  14215. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  14216. } catch (e) {
  14217. $exceptionHandler(e);
  14218. }
  14219. lastDirtyWatch = null;
  14220. }
  14221. traverseScopesLoop:
  14222. do { // "traverse the scopes" loop
  14223. if ((watchers = current.$$watchers)) {
  14224. // process our watches
  14225. length = watchers.length;
  14226. while (length--) {
  14227. try {
  14228. watch = watchers[length];
  14229. // Most common watches are on primitives, in which case we can short
  14230. // circuit it with === operator, only when === fails do we use .equals
  14231. if (watch) {
  14232. if ((value = watch.get(current)) !== (last = watch.last) &&
  14233. !(watch.eq
  14234. ? equals(value, last)
  14235. : (typeof value === 'number' && typeof last === 'number'
  14236. && isNaN(value) && isNaN(last)))) {
  14237. dirty = true;
  14238. lastDirtyWatch = watch;
  14239. watch.last = watch.eq ? copy(value, null) : value;
  14240. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  14241. if (ttl < 5) {
  14242. logIdx = 4 - ttl;
  14243. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  14244. watchLog[logIdx].push({
  14245. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  14246. newVal: value,
  14247. oldVal: last
  14248. });
  14249. }
  14250. } else if (watch === lastDirtyWatch) {
  14251. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  14252. // have already been tested.
  14253. dirty = false;
  14254. break traverseScopesLoop;
  14255. }
  14256. }
  14257. } catch (e) {
  14258. $exceptionHandler(e);
  14259. }
  14260. }
  14261. }
  14262. // Insanity Warning: scope depth-first traversal
  14263. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14264. // this piece should be kept in sync with the traversal in $broadcast
  14265. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  14266. (current !== target && current.$$nextSibling)))) {
  14267. while (current !== target && !(next = current.$$nextSibling)) {
  14268. current = current.$parent;
  14269. }
  14270. }
  14271. } while ((current = next));
  14272. // `break traverseScopesLoop;` takes us to here
  14273. if ((dirty || asyncQueue.length) && !(ttl--)) {
  14274. clearPhase();
  14275. throw $rootScopeMinErr('infdig',
  14276. '{0} $digest() iterations reached. Aborting!\n' +
  14277. 'Watchers fired in the last 5 iterations: {1}',
  14278. TTL, watchLog);
  14279. }
  14280. } while (dirty || asyncQueue.length);
  14281. clearPhase();
  14282. while (postDigestQueue.length) {
  14283. try {
  14284. postDigestQueue.shift()();
  14285. } catch (e) {
  14286. $exceptionHandler(e);
  14287. }
  14288. }
  14289. },
  14290. /**
  14291. * @ngdoc event
  14292. * @name $rootScope.Scope#$destroy
  14293. * @eventType broadcast on scope being destroyed
  14294. *
  14295. * @description
  14296. * Broadcasted when a scope and its children are being destroyed.
  14297. *
  14298. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14299. * clean up DOM bindings before an element is removed from the DOM.
  14300. */
  14301. /**
  14302. * @ngdoc method
  14303. * @name $rootScope.Scope#$destroy
  14304. * @kind function
  14305. *
  14306. * @description
  14307. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  14308. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  14309. * propagate to the current scope and its children. Removal also implies that the current
  14310. * scope is eligible for garbage collection.
  14311. *
  14312. * The `$destroy()` is usually used by directives such as
  14313. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  14314. * unrolling of the loop.
  14315. *
  14316. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  14317. * Application code can register a `$destroy` event handler that will give it a chance to
  14318. * perform any necessary cleanup.
  14319. *
  14320. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14321. * clean up DOM bindings before an element is removed from the DOM.
  14322. */
  14323. $destroy: function() {
  14324. // We can't destroy a scope that has been already destroyed.
  14325. if (this.$$destroyed) return;
  14326. var parent = this.$parent;
  14327. this.$broadcast('$destroy');
  14328. this.$$destroyed = true;
  14329. if (this === $rootScope) {
  14330. //Remove handlers attached to window when $rootScope is removed
  14331. $browser.$$applicationDestroyed();
  14332. }
  14333. incrementWatchersCount(this, -this.$$watchersCount);
  14334. for (var eventName in this.$$listenerCount) {
  14335. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  14336. }
  14337. // sever all the references to parent scopes (after this cleanup, the current scope should
  14338. // not be retained by any of our references and should be eligible for garbage collection)
  14339. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  14340. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  14341. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  14342. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  14343. // Disable listeners, watchers and apply/digest methods
  14344. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  14345. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  14346. this.$$listeners = {};
  14347. // All of the code below is bogus code that works around V8's memory leak via optimized code
  14348. // and inline caches.
  14349. //
  14350. // see:
  14351. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  14352. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  14353. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  14354. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  14355. this.$$childTail = this.$root = this.$$watchers = null;
  14356. },
  14357. /**
  14358. * @ngdoc method
  14359. * @name $rootScope.Scope#$eval
  14360. * @kind function
  14361. *
  14362. * @description
  14363. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  14364. * the expression are propagated (uncaught). This is useful when evaluating Angular
  14365. * expressions.
  14366. *
  14367. * # Example
  14368. * ```js
  14369. var scope = ng.$rootScope.Scope();
  14370. scope.a = 1;
  14371. scope.b = 2;
  14372. expect(scope.$eval('a+b')).toEqual(3);
  14373. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  14374. * ```
  14375. *
  14376. * @param {(string|function())=} expression An angular expression to be executed.
  14377. *
  14378. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14379. * - `function(scope)`: execute the function with the current `scope` parameter.
  14380. *
  14381. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14382. * @returns {*} The result of evaluating the expression.
  14383. */
  14384. $eval: function(expr, locals) {
  14385. return $parse(expr)(this, locals);
  14386. },
  14387. /**
  14388. * @ngdoc method
  14389. * @name $rootScope.Scope#$evalAsync
  14390. * @kind function
  14391. *
  14392. * @description
  14393. * Executes the expression on the current scope at a later point in time.
  14394. *
  14395. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  14396. * that:
  14397. *
  14398. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  14399. * rendering).
  14400. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  14401. * `expression` execution.
  14402. *
  14403. * Any exceptions from the execution of the expression are forwarded to the
  14404. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14405. *
  14406. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  14407. * will be scheduled. However, it is encouraged to always call code that changes the model
  14408. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  14409. *
  14410. * @param {(string|function())=} expression An angular expression to be executed.
  14411. *
  14412. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14413. * - `function(scope)`: execute the function with the current `scope` parameter.
  14414. *
  14415. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14416. */
  14417. $evalAsync: function(expr, locals) {
  14418. // if we are outside of an $digest loop and this is the first time we are scheduling async
  14419. // task also schedule async auto-flush
  14420. if (!$rootScope.$$phase && !asyncQueue.length) {
  14421. $browser.defer(function() {
  14422. if (asyncQueue.length) {
  14423. $rootScope.$digest();
  14424. }
  14425. });
  14426. }
  14427. asyncQueue.push({scope: this, expression: expr, locals: locals});
  14428. },
  14429. $$postDigest: function(fn) {
  14430. postDigestQueue.push(fn);
  14431. },
  14432. /**
  14433. * @ngdoc method
  14434. * @name $rootScope.Scope#$apply
  14435. * @kind function
  14436. *
  14437. * @description
  14438. * `$apply()` is used to execute an expression in angular from outside of the angular
  14439. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  14440. * Because we are calling into the angular framework we need to perform proper scope life
  14441. * cycle of {@link ng.$exceptionHandler exception handling},
  14442. * {@link ng.$rootScope.Scope#$digest executing watches}.
  14443. *
  14444. * ## Life cycle
  14445. *
  14446. * # Pseudo-Code of `$apply()`
  14447. * ```js
  14448. function $apply(expr) {
  14449. try {
  14450. return $eval(expr);
  14451. } catch (e) {
  14452. $exceptionHandler(e);
  14453. } finally {
  14454. $root.$digest();
  14455. }
  14456. }
  14457. * ```
  14458. *
  14459. *
  14460. * Scope's `$apply()` method transitions through the following stages:
  14461. *
  14462. * 1. The {@link guide/expression expression} is executed using the
  14463. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  14464. * 2. Any exceptions from the execution of the expression are forwarded to the
  14465. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14466. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  14467. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  14468. *
  14469. *
  14470. * @param {(string|function())=} exp An angular expression to be executed.
  14471. *
  14472. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14473. * - `function(scope)`: execute the function with current `scope` parameter.
  14474. *
  14475. * @returns {*} The result of evaluating the expression.
  14476. */
  14477. $apply: function(expr) {
  14478. try {
  14479. beginPhase('$apply');
  14480. try {
  14481. return this.$eval(expr);
  14482. } finally {
  14483. clearPhase();
  14484. }
  14485. } catch (e) {
  14486. $exceptionHandler(e);
  14487. } finally {
  14488. try {
  14489. $rootScope.$digest();
  14490. } catch (e) {
  14491. $exceptionHandler(e);
  14492. throw e;
  14493. }
  14494. }
  14495. },
  14496. /**
  14497. * @ngdoc method
  14498. * @name $rootScope.Scope#$applyAsync
  14499. * @kind function
  14500. *
  14501. * @description
  14502. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  14503. * varies across browsers, but is typically around ~10 milliseconds.
  14504. *
  14505. * This can be used to queue up multiple expressions which need to be evaluated in the same
  14506. * digest.
  14507. *
  14508. * @param {(string|function())=} exp An angular expression to be executed.
  14509. *
  14510. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14511. * - `function(scope)`: execute the function with current `scope` parameter.
  14512. */
  14513. $applyAsync: function(expr) {
  14514. var scope = this;
  14515. expr && applyAsyncQueue.push($applyAsyncExpression);
  14516. scheduleApplyAsync();
  14517. function $applyAsyncExpression() {
  14518. scope.$eval(expr);
  14519. }
  14520. },
  14521. /**
  14522. * @ngdoc method
  14523. * @name $rootScope.Scope#$on
  14524. * @kind function
  14525. *
  14526. * @description
  14527. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  14528. * discussion of event life cycle.
  14529. *
  14530. * The event listener function format is: `function(event, args...)`. The `event` object
  14531. * passed into the listener has the following attributes:
  14532. *
  14533. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  14534. * `$broadcast`-ed.
  14535. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  14536. * event propagates through the scope hierarchy, this property is set to null.
  14537. * - `name` - `{string}`: name of the event.
  14538. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  14539. * further event propagation (available only for events that were `$emit`-ed).
  14540. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  14541. * to true.
  14542. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  14543. *
  14544. * @param {string} name Event name to listen on.
  14545. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  14546. * @returns {function()} Returns a deregistration function for this listener.
  14547. */
  14548. $on: function(name, listener) {
  14549. var namedListeners = this.$$listeners[name];
  14550. if (!namedListeners) {
  14551. this.$$listeners[name] = namedListeners = [];
  14552. }
  14553. namedListeners.push(listener);
  14554. var current = this;
  14555. do {
  14556. if (!current.$$listenerCount[name]) {
  14557. current.$$listenerCount[name] = 0;
  14558. }
  14559. current.$$listenerCount[name]++;
  14560. } while ((current = current.$parent));
  14561. var self = this;
  14562. return function() {
  14563. var indexOfListener = namedListeners.indexOf(listener);
  14564. if (indexOfListener !== -1) {
  14565. namedListeners[indexOfListener] = null;
  14566. decrementListenerCount(self, 1, name);
  14567. }
  14568. };
  14569. },
  14570. /**
  14571. * @ngdoc method
  14572. * @name $rootScope.Scope#$emit
  14573. * @kind function
  14574. *
  14575. * @description
  14576. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  14577. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14578. *
  14579. * The event life cycle starts at the scope on which `$emit` was called. All
  14580. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14581. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  14582. * registered listeners along the way. The event will stop propagating if one of the listeners
  14583. * cancels it.
  14584. *
  14585. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14586. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14587. *
  14588. * @param {string} name Event name to emit.
  14589. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14590. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  14591. */
  14592. $emit: function(name, args) {
  14593. var empty = [],
  14594. namedListeners,
  14595. scope = this,
  14596. stopPropagation = false,
  14597. event = {
  14598. name: name,
  14599. targetScope: scope,
  14600. stopPropagation: function() {stopPropagation = true;},
  14601. preventDefault: function() {
  14602. event.defaultPrevented = true;
  14603. },
  14604. defaultPrevented: false
  14605. },
  14606. listenerArgs = concat([event], arguments, 1),
  14607. i, length;
  14608. do {
  14609. namedListeners = scope.$$listeners[name] || empty;
  14610. event.currentScope = scope;
  14611. for (i = 0, length = namedListeners.length; i < length; i++) {
  14612. // if listeners were deregistered, defragment the array
  14613. if (!namedListeners[i]) {
  14614. namedListeners.splice(i, 1);
  14615. i--;
  14616. length--;
  14617. continue;
  14618. }
  14619. try {
  14620. //allow all listeners attached to the current scope to run
  14621. namedListeners[i].apply(null, listenerArgs);
  14622. } catch (e) {
  14623. $exceptionHandler(e);
  14624. }
  14625. }
  14626. //if any listener on the current scope stops propagation, prevent bubbling
  14627. if (stopPropagation) {
  14628. event.currentScope = null;
  14629. return event;
  14630. }
  14631. //traverse upwards
  14632. scope = scope.$parent;
  14633. } while (scope);
  14634. event.currentScope = null;
  14635. return event;
  14636. },
  14637. /**
  14638. * @ngdoc method
  14639. * @name $rootScope.Scope#$broadcast
  14640. * @kind function
  14641. *
  14642. * @description
  14643. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  14644. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14645. *
  14646. * The event life cycle starts at the scope on which `$broadcast` was called. All
  14647. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14648. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  14649. * scope and calls all registered listeners along the way. The event cannot be canceled.
  14650. *
  14651. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14652. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14653. *
  14654. * @param {string} name Event name to broadcast.
  14655. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14656. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  14657. */
  14658. $broadcast: function(name, args) {
  14659. var target = this,
  14660. current = target,
  14661. next = target,
  14662. event = {
  14663. name: name,
  14664. targetScope: target,
  14665. preventDefault: function() {
  14666. event.defaultPrevented = true;
  14667. },
  14668. defaultPrevented: false
  14669. };
  14670. if (!target.$$listenerCount[name]) return event;
  14671. var listenerArgs = concat([event], arguments, 1),
  14672. listeners, i, length;
  14673. //down while you can, then up and next sibling or up and next sibling until back at root
  14674. while ((current = next)) {
  14675. event.currentScope = current;
  14676. listeners = current.$$listeners[name] || [];
  14677. for (i = 0, length = listeners.length; i < length; i++) {
  14678. // if listeners were deregistered, defragment the array
  14679. if (!listeners[i]) {
  14680. listeners.splice(i, 1);
  14681. i--;
  14682. length--;
  14683. continue;
  14684. }
  14685. try {
  14686. listeners[i].apply(null, listenerArgs);
  14687. } catch (e) {
  14688. $exceptionHandler(e);
  14689. }
  14690. }
  14691. // Insanity Warning: scope depth-first traversal
  14692. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14693. // this piece should be kept in sync with the traversal in $digest
  14694. // (though it differs due to having the extra check for $$listenerCount)
  14695. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  14696. (current !== target && current.$$nextSibling)))) {
  14697. while (current !== target && !(next = current.$$nextSibling)) {
  14698. current = current.$parent;
  14699. }
  14700. }
  14701. }
  14702. event.currentScope = null;
  14703. return event;
  14704. }
  14705. };
  14706. var $rootScope = new Scope();
  14707. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  14708. var asyncQueue = $rootScope.$$asyncQueue = [];
  14709. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  14710. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  14711. return $rootScope;
  14712. function beginPhase(phase) {
  14713. if ($rootScope.$$phase) {
  14714. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  14715. }
  14716. $rootScope.$$phase = phase;
  14717. }
  14718. function clearPhase() {
  14719. $rootScope.$$phase = null;
  14720. }
  14721. function incrementWatchersCount(current, count) {
  14722. do {
  14723. current.$$watchersCount += count;
  14724. } while ((current = current.$parent));
  14725. }
  14726. function decrementListenerCount(current, count, name) {
  14727. do {
  14728. current.$$listenerCount[name] -= count;
  14729. if (current.$$listenerCount[name] === 0) {
  14730. delete current.$$listenerCount[name];
  14731. }
  14732. } while ((current = current.$parent));
  14733. }
  14734. /**
  14735. * function used as an initial value for watchers.
  14736. * because it's unique we can easily tell it apart from other values
  14737. */
  14738. function initWatchVal() {}
  14739. function flushApplyAsync() {
  14740. while (applyAsyncQueue.length) {
  14741. try {
  14742. applyAsyncQueue.shift()();
  14743. } catch (e) {
  14744. $exceptionHandler(e);
  14745. }
  14746. }
  14747. applyAsyncId = null;
  14748. }
  14749. function scheduleApplyAsync() {
  14750. if (applyAsyncId === null) {
  14751. applyAsyncId = $browser.defer(function() {
  14752. $rootScope.$apply(flushApplyAsync);
  14753. });
  14754. }
  14755. }
  14756. }];
  14757. }
  14758. /**
  14759. * @description
  14760. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  14761. */
  14762. function $$SanitizeUriProvider() {
  14763. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  14764. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  14765. /**
  14766. * @description
  14767. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14768. * urls during a[href] sanitization.
  14769. *
  14770. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14771. *
  14772. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  14773. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  14774. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14775. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14776. *
  14777. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14778. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14779. * chaining otherwise.
  14780. */
  14781. this.aHrefSanitizationWhitelist = function(regexp) {
  14782. if (isDefined(regexp)) {
  14783. aHrefSanitizationWhitelist = regexp;
  14784. return this;
  14785. }
  14786. return aHrefSanitizationWhitelist;
  14787. };
  14788. /**
  14789. * @description
  14790. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14791. * urls during img[src] sanitization.
  14792. *
  14793. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14794. *
  14795. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  14796. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  14797. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14798. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14799. *
  14800. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14801. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14802. * chaining otherwise.
  14803. */
  14804. this.imgSrcSanitizationWhitelist = function(regexp) {
  14805. if (isDefined(regexp)) {
  14806. imgSrcSanitizationWhitelist = regexp;
  14807. return this;
  14808. }
  14809. return imgSrcSanitizationWhitelist;
  14810. };
  14811. this.$get = function() {
  14812. return function sanitizeUri(uri, isImage) {
  14813. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  14814. var normalizedVal;
  14815. normalizedVal = urlResolve(uri).href;
  14816. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  14817. return 'unsafe:' + normalizedVal;
  14818. }
  14819. return uri;
  14820. };
  14821. };
  14822. }
  14823. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  14824. * Any commits to this file should be reviewed with security in mind. *
  14825. * Changes to this file can potentially create security vulnerabilities. *
  14826. * An approval from 2 Core members with history of modifying *
  14827. * this file is required. *
  14828. * *
  14829. * Does the change somehow allow for arbitrary javascript to be executed? *
  14830. * Or allows for someone to change the prototype of built-in objects? *
  14831. * Or gives undesired access to variables likes document or window? *
  14832. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  14833. var $sceMinErr = minErr('$sce');
  14834. var SCE_CONTEXTS = {
  14835. HTML: 'html',
  14836. CSS: 'css',
  14837. URL: 'url',
  14838. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  14839. // url. (e.g. ng-include, script src, templateUrl)
  14840. RESOURCE_URL: 'resourceUrl',
  14841. JS: 'js'
  14842. };
  14843. // Helper functions follow.
  14844. function adjustMatcher(matcher) {
  14845. if (matcher === 'self') {
  14846. return matcher;
  14847. } else if (isString(matcher)) {
  14848. // Strings match exactly except for 2 wildcards - '*' and '**'.
  14849. // '*' matches any character except those from the set ':/.?&'.
  14850. // '**' matches any character (like .* in a RegExp).
  14851. // More than 2 *'s raises an error as it's ill defined.
  14852. if (matcher.indexOf('***') > -1) {
  14853. throw $sceMinErr('iwcard',
  14854. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  14855. }
  14856. matcher = escapeForRegexp(matcher).
  14857. replace('\\*\\*', '.*').
  14858. replace('\\*', '[^:/.?&;]*');
  14859. return new RegExp('^' + matcher + '$');
  14860. } else if (isRegExp(matcher)) {
  14861. // The only other type of matcher allowed is a Regexp.
  14862. // Match entire URL / disallow partial matches.
  14863. // Flags are reset (i.e. no global, ignoreCase or multiline)
  14864. return new RegExp('^' + matcher.source + '$');
  14865. } else {
  14866. throw $sceMinErr('imatcher',
  14867. 'Matchers may only be "self", string patterns or RegExp objects');
  14868. }
  14869. }
  14870. function adjustMatchers(matchers) {
  14871. var adjustedMatchers = [];
  14872. if (isDefined(matchers)) {
  14873. forEach(matchers, function(matcher) {
  14874. adjustedMatchers.push(adjustMatcher(matcher));
  14875. });
  14876. }
  14877. return adjustedMatchers;
  14878. }
  14879. /**
  14880. * @ngdoc service
  14881. * @name $sceDelegate
  14882. * @kind function
  14883. *
  14884. * @description
  14885. *
  14886. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  14887. * Contextual Escaping (SCE)} services to AngularJS.
  14888. *
  14889. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  14890. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  14891. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  14892. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  14893. * work because `$sce` delegates to `$sceDelegate` for these operations.
  14894. *
  14895. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  14896. *
  14897. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  14898. * can override it completely to change the behavior of `$sce`, the common case would
  14899. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  14900. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  14901. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  14902. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  14903. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14904. */
  14905. /**
  14906. * @ngdoc provider
  14907. * @name $sceDelegateProvider
  14908. * @description
  14909. *
  14910. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  14911. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  14912. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  14913. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  14914. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14915. *
  14916. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  14917. * Strict Contextual Escaping (SCE)}.
  14918. *
  14919. * **Example**: Consider the following case. <a name="example"></a>
  14920. *
  14921. * - your app is hosted at url `http://myapp.example.com/`
  14922. * - but some of your templates are hosted on other domains you control such as
  14923. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  14924. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  14925. *
  14926. * Here is what a secure configuration for this scenario might look like:
  14927. *
  14928. * ```
  14929. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  14930. * $sceDelegateProvider.resourceUrlWhitelist([
  14931. * // Allow same origin resource loads.
  14932. * 'self',
  14933. * // Allow loading from our assets domain. Notice the difference between * and **.
  14934. * 'http://srv*.assets.example.com/**'
  14935. * ]);
  14936. *
  14937. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  14938. * $sceDelegateProvider.resourceUrlBlacklist([
  14939. * 'http://myapp.example.com/clickThru**'
  14940. * ]);
  14941. * });
  14942. * ```
  14943. */
  14944. function $SceDelegateProvider() {
  14945. this.SCE_CONTEXTS = SCE_CONTEXTS;
  14946. // Resource URLs can also be trusted by policy.
  14947. var resourceUrlWhitelist = ['self'],
  14948. resourceUrlBlacklist = [];
  14949. /**
  14950. * @ngdoc method
  14951. * @name $sceDelegateProvider#resourceUrlWhitelist
  14952. * @kind function
  14953. *
  14954. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  14955. * provided. This must be an array or null. A snapshot of this array is used so further
  14956. * changes to the array are ignored.
  14957. *
  14958. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14959. * allowed in this array.
  14960. *
  14961. * Note: **an empty whitelist array will block all URLs**!
  14962. *
  14963. * @return {Array} the currently set whitelist array.
  14964. *
  14965. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  14966. * same origin resource requests.
  14967. *
  14968. * @description
  14969. * Sets/Gets the whitelist of trusted resource URLs.
  14970. */
  14971. this.resourceUrlWhitelist = function(value) {
  14972. if (arguments.length) {
  14973. resourceUrlWhitelist = adjustMatchers(value);
  14974. }
  14975. return resourceUrlWhitelist;
  14976. };
  14977. /**
  14978. * @ngdoc method
  14979. * @name $sceDelegateProvider#resourceUrlBlacklist
  14980. * @kind function
  14981. *
  14982. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  14983. * provided. This must be an array or null. A snapshot of this array is used so further
  14984. * changes to the array are ignored.
  14985. *
  14986. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14987. * allowed in this array.
  14988. *
  14989. * The typical usage for the blacklist is to **block
  14990. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  14991. * these would otherwise be trusted but actually return content from the redirected domain.
  14992. *
  14993. * Finally, **the blacklist overrides the whitelist** and has the final say.
  14994. *
  14995. * @return {Array} the currently set blacklist array.
  14996. *
  14997. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  14998. * is no blacklist.)
  14999. *
  15000. * @description
  15001. * Sets/Gets the blacklist of trusted resource URLs.
  15002. */
  15003. this.resourceUrlBlacklist = function(value) {
  15004. if (arguments.length) {
  15005. resourceUrlBlacklist = adjustMatchers(value);
  15006. }
  15007. return resourceUrlBlacklist;
  15008. };
  15009. this.$get = ['$injector', function($injector) {
  15010. var htmlSanitizer = function htmlSanitizer(html) {
  15011. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15012. };
  15013. if ($injector.has('$sanitize')) {
  15014. htmlSanitizer = $injector.get('$sanitize');
  15015. }
  15016. function matchUrl(matcher, parsedUrl) {
  15017. if (matcher === 'self') {
  15018. return urlIsSameOrigin(parsedUrl);
  15019. } else {
  15020. // definitely a regex. See adjustMatchers()
  15021. return !!matcher.exec(parsedUrl.href);
  15022. }
  15023. }
  15024. function isResourceUrlAllowedByPolicy(url) {
  15025. var parsedUrl = urlResolve(url.toString());
  15026. var i, n, allowed = false;
  15027. // Ensure that at least one item from the whitelist allows this url.
  15028. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  15029. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  15030. allowed = true;
  15031. break;
  15032. }
  15033. }
  15034. if (allowed) {
  15035. // Ensure that no item from the blacklist blocked this url.
  15036. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  15037. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  15038. allowed = false;
  15039. break;
  15040. }
  15041. }
  15042. }
  15043. return allowed;
  15044. }
  15045. function generateHolderType(Base) {
  15046. var holderType = function TrustedValueHolderType(trustedValue) {
  15047. this.$$unwrapTrustedValue = function() {
  15048. return trustedValue;
  15049. };
  15050. };
  15051. if (Base) {
  15052. holderType.prototype = new Base();
  15053. }
  15054. holderType.prototype.valueOf = function sceValueOf() {
  15055. return this.$$unwrapTrustedValue();
  15056. };
  15057. holderType.prototype.toString = function sceToString() {
  15058. return this.$$unwrapTrustedValue().toString();
  15059. };
  15060. return holderType;
  15061. }
  15062. var trustedValueHolderBase = generateHolderType(),
  15063. byType = {};
  15064. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  15065. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  15066. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  15067. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  15068. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  15069. /**
  15070. * @ngdoc method
  15071. * @name $sceDelegate#trustAs
  15072. *
  15073. * @description
  15074. * Returns an object that is trusted by angular for use in specified strict
  15075. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  15076. * attribute interpolation, any dom event binding attribute interpolation
  15077. * such as for onclick, etc.) that uses the provided value.
  15078. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  15079. *
  15080. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15081. * resourceUrl, html, js and css.
  15082. * @param {*} value The value that that should be considered trusted/safe.
  15083. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15084. * where Angular expects a $sce.trustAs() return value.
  15085. */
  15086. function trustAs(type, trustedValue) {
  15087. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15088. if (!Constructor) {
  15089. throw $sceMinErr('icontext',
  15090. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  15091. type, trustedValue);
  15092. }
  15093. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  15094. return trustedValue;
  15095. }
  15096. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  15097. // mutable objects, we ensure here that the value passed in is actually a string.
  15098. if (typeof trustedValue !== 'string') {
  15099. throw $sceMinErr('itype',
  15100. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  15101. type);
  15102. }
  15103. return new Constructor(trustedValue);
  15104. }
  15105. /**
  15106. * @ngdoc method
  15107. * @name $sceDelegate#valueOf
  15108. *
  15109. * @description
  15110. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  15111. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  15112. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  15113. *
  15114. * If the passed parameter is not a value that had been returned by {@link
  15115. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  15116. *
  15117. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  15118. * call or anything else.
  15119. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  15120. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  15121. * `value` unchanged.
  15122. */
  15123. function valueOf(maybeTrusted) {
  15124. if (maybeTrusted instanceof trustedValueHolderBase) {
  15125. return maybeTrusted.$$unwrapTrustedValue();
  15126. } else {
  15127. return maybeTrusted;
  15128. }
  15129. }
  15130. /**
  15131. * @ngdoc method
  15132. * @name $sceDelegate#getTrusted
  15133. *
  15134. * @description
  15135. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  15136. * returns the originally supplied value if the queried context type is a supertype of the
  15137. * created type. If this condition isn't satisfied, throws an exception.
  15138. *
  15139. * @param {string} type The kind of context in which this value is to be used.
  15140. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  15141. * `$sceDelegate.trustAs`} call.
  15142. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  15143. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  15144. */
  15145. function getTrusted(type, maybeTrusted) {
  15146. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  15147. return maybeTrusted;
  15148. }
  15149. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15150. if (constructor && maybeTrusted instanceof constructor) {
  15151. return maybeTrusted.$$unwrapTrustedValue();
  15152. }
  15153. // If we get here, then we may only take one of two actions.
  15154. // 1. sanitize the value for the requested type, or
  15155. // 2. throw an exception.
  15156. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  15157. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  15158. return maybeTrusted;
  15159. } else {
  15160. throw $sceMinErr('insecurl',
  15161. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  15162. maybeTrusted.toString());
  15163. }
  15164. } else if (type === SCE_CONTEXTS.HTML) {
  15165. return htmlSanitizer(maybeTrusted);
  15166. }
  15167. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15168. }
  15169. return { trustAs: trustAs,
  15170. getTrusted: getTrusted,
  15171. valueOf: valueOf };
  15172. }];
  15173. }
  15174. /**
  15175. * @ngdoc provider
  15176. * @name $sceProvider
  15177. * @description
  15178. *
  15179. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  15180. * - enable/disable Strict Contextual Escaping (SCE) in a module
  15181. * - override the default implementation with a custom delegate
  15182. *
  15183. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  15184. */
  15185. /* jshint maxlen: false*/
  15186. /**
  15187. * @ngdoc service
  15188. * @name $sce
  15189. * @kind function
  15190. *
  15191. * @description
  15192. *
  15193. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  15194. *
  15195. * # Strict Contextual Escaping
  15196. *
  15197. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  15198. * contexts to result in a value that is marked as safe to use for that context. One example of
  15199. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  15200. * to these contexts as privileged or SCE contexts.
  15201. *
  15202. * As of version 1.2, Angular ships with SCE enabled by default.
  15203. *
  15204. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  15205. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  15206. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  15207. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  15208. * to the top of your HTML document.
  15209. *
  15210. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  15211. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  15212. *
  15213. * Here's an example of a binding in a privileged context:
  15214. *
  15215. * ```
  15216. * <input ng-model="userHtml" aria-label="User input">
  15217. * <div ng-bind-html="userHtml"></div>
  15218. * ```
  15219. *
  15220. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  15221. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  15222. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  15223. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  15224. * security vulnerabilities.)
  15225. *
  15226. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  15227. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  15228. *
  15229. * How would you ensure that every place that used these types of bindings was bound to a value that
  15230. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  15231. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  15232. * properties/fields and forgot to update the binding to the sanitized value?
  15233. *
  15234. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  15235. * determine that something explicitly says it's safe to use a value for binding in that
  15236. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  15237. * for those values that you can easily tell are safe - because they were received from your server,
  15238. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  15239. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  15240. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  15241. *
  15242. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  15243. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  15244. * obtain values that will be accepted by SCE / privileged contexts.
  15245. *
  15246. *
  15247. * ## How does it work?
  15248. *
  15249. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  15250. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  15251. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  15252. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  15253. *
  15254. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  15255. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  15256. * simplified):
  15257. *
  15258. * ```
  15259. * var ngBindHtmlDirective = ['$sce', function($sce) {
  15260. * return function(scope, element, attr) {
  15261. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  15262. * element.html(value || '');
  15263. * });
  15264. * };
  15265. * }];
  15266. * ```
  15267. *
  15268. * ## Impact on loading templates
  15269. *
  15270. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  15271. * `templateUrl`'s specified by {@link guide/directive directives}.
  15272. *
  15273. * By default, Angular only loads templates from the same domain and protocol as the application
  15274. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  15275. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  15276. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  15277. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  15278. *
  15279. * *Please note*:
  15280. * The browser's
  15281. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  15282. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  15283. * policy apply in addition to this and may further restrict whether the template is successfully
  15284. * loaded. This means that without the right CORS policy, loading templates from a different domain
  15285. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  15286. * browsers.
  15287. *
  15288. * ## This feels like too much overhead
  15289. *
  15290. * It's important to remember that SCE only applies to interpolation expressions.
  15291. *
  15292. * If your expressions are constant literals, they're automatically trusted and you don't need to
  15293. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  15294. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  15295. *
  15296. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  15297. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  15298. *
  15299. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  15300. * templates in `ng-include` from your application's domain without having to even know about SCE.
  15301. * It blocks loading templates from other domains or loading templates over http from an https
  15302. * served document. You can change these by setting your own custom {@link
  15303. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  15304. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  15305. *
  15306. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  15307. * application that's secure and can be audited to verify that with much more ease than bolting
  15308. * security onto an application later.
  15309. *
  15310. * <a name="contexts"></a>
  15311. * ## What trusted context types are supported?
  15312. *
  15313. * | Context | Notes |
  15314. * |---------------------|----------------|
  15315. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
  15316. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  15317. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
  15318. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  15319. * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
  15320. *
  15321. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  15322. *
  15323. * Each element in these arrays must be one of the following:
  15324. *
  15325. * - **'self'**
  15326. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  15327. * domain** as the application document using the **same protocol**.
  15328. * - **String** (except the special value `'self'`)
  15329. * - The string is matched against the full *normalized / absolute URL* of the resource
  15330. * being tested (substring matches are not good enough.)
  15331. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  15332. * match themselves.
  15333. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  15334. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  15335. * in a whitelist.
  15336. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  15337. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  15338. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  15339. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  15340. * http://foo.example.com/templates/**).
  15341. * - **RegExp** (*see caveat below*)
  15342. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  15343. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  15344. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  15345. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  15346. * small number of cases. A `.` character in the regex used when matching the scheme or a
  15347. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  15348. * is highly recommended to use the string patterns and only fall back to regular expressions
  15349. * as a last resort.
  15350. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  15351. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  15352. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  15353. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  15354. * - If you are generating your JavaScript from some other templating engine (not
  15355. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  15356. * remember to escape your regular expression (and be aware that you might need more than
  15357. * one level of escaping depending on your templating engine and the way you interpolated
  15358. * the value.) Do make use of your platform's escaping mechanism as it might be good
  15359. * enough before coding your own. E.g. Ruby has
  15360. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  15361. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  15362. * Javascript lacks a similar built in function for escaping. Take a look at Google
  15363. * Closure library's [goog.string.regExpEscape(s)](
  15364. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  15365. *
  15366. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  15367. *
  15368. * ## Show me an example using SCE.
  15369. *
  15370. * <example module="mySceApp" deps="angular-sanitize.js">
  15371. * <file name="index.html">
  15372. * <div ng-controller="AppController as myCtrl">
  15373. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  15374. * <b>User comments</b><br>
  15375. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  15376. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  15377. * exploit.
  15378. * <div class="well">
  15379. * <div ng-repeat="userComment in myCtrl.userComments">
  15380. * <b>{{userComment.name}}</b>:
  15381. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  15382. * <br>
  15383. * </div>
  15384. * </div>
  15385. * </div>
  15386. * </file>
  15387. *
  15388. * <file name="script.js">
  15389. * angular.module('mySceApp', ['ngSanitize'])
  15390. * .controller('AppController', ['$http', '$templateCache', '$sce',
  15391. * function($http, $templateCache, $sce) {
  15392. * var self = this;
  15393. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  15394. * self.userComments = userComments;
  15395. * });
  15396. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  15397. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15398. * 'sanitization.&quot;">Hover over this text.</span>');
  15399. * }]);
  15400. * </file>
  15401. *
  15402. * <file name="test_data.json">
  15403. * [
  15404. * { "name": "Alice",
  15405. * "htmlComment":
  15406. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  15407. * },
  15408. * { "name": "Bob",
  15409. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  15410. * }
  15411. * ]
  15412. * </file>
  15413. *
  15414. * <file name="protractor.js" type="protractor">
  15415. * describe('SCE doc demo', function() {
  15416. * it('should sanitize untrusted values', function() {
  15417. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  15418. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  15419. * });
  15420. *
  15421. * it('should NOT sanitize explicitly trusted values', function() {
  15422. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  15423. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15424. * 'sanitization.&quot;">Hover over this text.</span>');
  15425. * });
  15426. * });
  15427. * </file>
  15428. * </example>
  15429. *
  15430. *
  15431. *
  15432. * ## Can I disable SCE completely?
  15433. *
  15434. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  15435. * for little coding overhead. It will be much harder to take an SCE disabled application and
  15436. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  15437. * for cases where you have a lot of existing code that was written before SCE was introduced and
  15438. * you're migrating them a module at a time.
  15439. *
  15440. * That said, here's how you can completely disable SCE:
  15441. *
  15442. * ```
  15443. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  15444. * // Completely disable SCE. For demonstration purposes only!
  15445. * // Do not use in new projects.
  15446. * $sceProvider.enabled(false);
  15447. * });
  15448. * ```
  15449. *
  15450. */
  15451. /* jshint maxlen: 100 */
  15452. function $SceProvider() {
  15453. var enabled = true;
  15454. /**
  15455. * @ngdoc method
  15456. * @name $sceProvider#enabled
  15457. * @kind function
  15458. *
  15459. * @param {boolean=} value If provided, then enables/disables SCE.
  15460. * @return {boolean} true if SCE is enabled, false otherwise.
  15461. *
  15462. * @description
  15463. * Enables/disables SCE and returns the current value.
  15464. */
  15465. this.enabled = function(value) {
  15466. if (arguments.length) {
  15467. enabled = !!value;
  15468. }
  15469. return enabled;
  15470. };
  15471. /* Design notes on the default implementation for SCE.
  15472. *
  15473. * The API contract for the SCE delegate
  15474. * -------------------------------------
  15475. * The SCE delegate object must provide the following 3 methods:
  15476. *
  15477. * - trustAs(contextEnum, value)
  15478. * This method is used to tell the SCE service that the provided value is OK to use in the
  15479. * contexts specified by contextEnum. It must return an object that will be accepted by
  15480. * getTrusted() for a compatible contextEnum and return this value.
  15481. *
  15482. * - valueOf(value)
  15483. * For values that were not produced by trustAs(), return them as is. For values that were
  15484. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  15485. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  15486. * such a value.
  15487. *
  15488. * - getTrusted(contextEnum, value)
  15489. * This function should return the a value that is safe to use in the context specified by
  15490. * contextEnum or throw and exception otherwise.
  15491. *
  15492. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  15493. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  15494. * instance, an implementation could maintain a registry of all trusted objects by context. In
  15495. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  15496. * return the same object passed in if it was found in the registry under a compatible context or
  15497. * throw an exception otherwise. An implementation might only wrap values some of the time based
  15498. * on some criteria. getTrusted() might return a value and not throw an exception for special
  15499. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  15500. *
  15501. *
  15502. * A note on the inheritance model for SCE contexts
  15503. * ------------------------------------------------
  15504. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  15505. * is purely an implementation details.
  15506. *
  15507. * The contract is simply this:
  15508. *
  15509. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  15510. * will also succeed.
  15511. *
  15512. * Inheritance happens to capture this in a natural way. In some future, we
  15513. * may not use inheritance anymore. That is OK because no code outside of
  15514. * sce.js and sceSpecs.js would need to be aware of this detail.
  15515. */
  15516. this.$get = ['$parse', '$sceDelegate', function(
  15517. $parse, $sceDelegate) {
  15518. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  15519. // the "expression(javascript expression)" syntax which is insecure.
  15520. if (enabled && msie < 8) {
  15521. throw $sceMinErr('iequirks',
  15522. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  15523. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  15524. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  15525. }
  15526. var sce = shallowCopy(SCE_CONTEXTS);
  15527. /**
  15528. * @ngdoc method
  15529. * @name $sce#isEnabled
  15530. * @kind function
  15531. *
  15532. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  15533. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  15534. *
  15535. * @description
  15536. * Returns a boolean indicating if SCE is enabled.
  15537. */
  15538. sce.isEnabled = function() {
  15539. return enabled;
  15540. };
  15541. sce.trustAs = $sceDelegate.trustAs;
  15542. sce.getTrusted = $sceDelegate.getTrusted;
  15543. sce.valueOf = $sceDelegate.valueOf;
  15544. if (!enabled) {
  15545. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  15546. sce.valueOf = identity;
  15547. }
  15548. /**
  15549. * @ngdoc method
  15550. * @name $sce#parseAs
  15551. *
  15552. * @description
  15553. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  15554. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  15555. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  15556. * *result*)}
  15557. *
  15558. * @param {string} type The kind of SCE context in which this result will be used.
  15559. * @param {string} expression String expression to compile.
  15560. * @returns {function(context, locals)} a function which represents the compiled expression:
  15561. *
  15562. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15563. * are evaluated against (typically a scope object).
  15564. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15565. * `context`.
  15566. */
  15567. sce.parseAs = function sceParseAs(type, expr) {
  15568. var parsed = $parse(expr);
  15569. if (parsed.literal && parsed.constant) {
  15570. return parsed;
  15571. } else {
  15572. return $parse(expr, function(value) {
  15573. return sce.getTrusted(type, value);
  15574. });
  15575. }
  15576. };
  15577. /**
  15578. * @ngdoc method
  15579. * @name $sce#trustAs
  15580. *
  15581. * @description
  15582. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  15583. * returns an object that is trusted by angular for use in specified strict contextual
  15584. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  15585. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  15586. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  15587. * escaping.
  15588. *
  15589. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15590. * resourceUrl, html, js and css.
  15591. * @param {*} value The value that that should be considered trusted/safe.
  15592. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15593. * where Angular expects a $sce.trustAs() return value.
  15594. */
  15595. /**
  15596. * @ngdoc method
  15597. * @name $sce#trustAsHtml
  15598. *
  15599. * @description
  15600. * Shorthand method. `$sce.trustAsHtml(value)` →
  15601. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  15602. *
  15603. * @param {*} value The value to trustAs.
  15604. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  15605. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  15606. * only accept expressions that are either literal constants or are the
  15607. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15608. */
  15609. /**
  15610. * @ngdoc method
  15611. * @name $sce#trustAsUrl
  15612. *
  15613. * @description
  15614. * Shorthand method. `$sce.trustAsUrl(value)` →
  15615. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  15616. *
  15617. * @param {*} value The value to trustAs.
  15618. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  15619. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  15620. * only accept expressions that are either literal constants or are the
  15621. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15622. */
  15623. /**
  15624. * @ngdoc method
  15625. * @name $sce#trustAsResourceUrl
  15626. *
  15627. * @description
  15628. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  15629. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  15630. *
  15631. * @param {*} value The value to trustAs.
  15632. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  15633. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  15634. * only accept expressions that are either literal constants or are the return
  15635. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15636. */
  15637. /**
  15638. * @ngdoc method
  15639. * @name $sce#trustAsJs
  15640. *
  15641. * @description
  15642. * Shorthand method. `$sce.trustAsJs(value)` →
  15643. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  15644. *
  15645. * @param {*} value The value to trustAs.
  15646. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  15647. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  15648. * only accept expressions that are either literal constants or are the
  15649. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15650. */
  15651. /**
  15652. * @ngdoc method
  15653. * @name $sce#getTrusted
  15654. *
  15655. * @description
  15656. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  15657. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  15658. * originally supplied value if the queried context type is a supertype of the created type.
  15659. * If this condition isn't satisfied, throws an exception.
  15660. *
  15661. * @param {string} type The kind of context in which this value is to be used.
  15662. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  15663. * call.
  15664. * @returns {*} The value the was originally provided to
  15665. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  15666. * Otherwise, throws an exception.
  15667. */
  15668. /**
  15669. * @ngdoc method
  15670. * @name $sce#getTrustedHtml
  15671. *
  15672. * @description
  15673. * Shorthand method. `$sce.getTrustedHtml(value)` →
  15674. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  15675. *
  15676. * @param {*} value The value to pass to `$sce.getTrusted`.
  15677. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  15678. */
  15679. /**
  15680. * @ngdoc method
  15681. * @name $sce#getTrustedCss
  15682. *
  15683. * @description
  15684. * Shorthand method. `$sce.getTrustedCss(value)` →
  15685. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  15686. *
  15687. * @param {*} value The value to pass to `$sce.getTrusted`.
  15688. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  15689. */
  15690. /**
  15691. * @ngdoc method
  15692. * @name $sce#getTrustedUrl
  15693. *
  15694. * @description
  15695. * Shorthand method. `$sce.getTrustedUrl(value)` →
  15696. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  15697. *
  15698. * @param {*} value The value to pass to `$sce.getTrusted`.
  15699. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  15700. */
  15701. /**
  15702. * @ngdoc method
  15703. * @name $sce#getTrustedResourceUrl
  15704. *
  15705. * @description
  15706. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  15707. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  15708. *
  15709. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  15710. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  15711. */
  15712. /**
  15713. * @ngdoc method
  15714. * @name $sce#getTrustedJs
  15715. *
  15716. * @description
  15717. * Shorthand method. `$sce.getTrustedJs(value)` →
  15718. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  15719. *
  15720. * @param {*} value The value to pass to `$sce.getTrusted`.
  15721. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  15722. */
  15723. /**
  15724. * @ngdoc method
  15725. * @name $sce#parseAsHtml
  15726. *
  15727. * @description
  15728. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  15729. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  15730. *
  15731. * @param {string} expression String expression to compile.
  15732. * @returns {function(context, locals)} a function which represents the compiled expression:
  15733. *
  15734. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15735. * are evaluated against (typically a scope object).
  15736. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15737. * `context`.
  15738. */
  15739. /**
  15740. * @ngdoc method
  15741. * @name $sce#parseAsCss
  15742. *
  15743. * @description
  15744. * Shorthand method. `$sce.parseAsCss(value)` →
  15745. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  15746. *
  15747. * @param {string} expression String expression to compile.
  15748. * @returns {function(context, locals)} a function which represents the compiled expression:
  15749. *
  15750. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15751. * are evaluated against (typically a scope object).
  15752. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15753. * `context`.
  15754. */
  15755. /**
  15756. * @ngdoc method
  15757. * @name $sce#parseAsUrl
  15758. *
  15759. * @description
  15760. * Shorthand method. `$sce.parseAsUrl(value)` →
  15761. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  15762. *
  15763. * @param {string} expression String expression to compile.
  15764. * @returns {function(context, locals)} a function which represents the compiled expression:
  15765. *
  15766. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15767. * are evaluated against (typically a scope object).
  15768. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15769. * `context`.
  15770. */
  15771. /**
  15772. * @ngdoc method
  15773. * @name $sce#parseAsResourceUrl
  15774. *
  15775. * @description
  15776. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  15777. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  15778. *
  15779. * @param {string} expression String expression to compile.
  15780. * @returns {function(context, locals)} a function which represents the compiled expression:
  15781. *
  15782. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15783. * are evaluated against (typically a scope object).
  15784. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15785. * `context`.
  15786. */
  15787. /**
  15788. * @ngdoc method
  15789. * @name $sce#parseAsJs
  15790. *
  15791. * @description
  15792. * Shorthand method. `$sce.parseAsJs(value)` →
  15793. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  15794. *
  15795. * @param {string} expression String expression to compile.
  15796. * @returns {function(context, locals)} a function which represents the compiled expression:
  15797. *
  15798. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15799. * are evaluated against (typically a scope object).
  15800. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15801. * `context`.
  15802. */
  15803. // Shorthand delegations.
  15804. var parse = sce.parseAs,
  15805. getTrusted = sce.getTrusted,
  15806. trustAs = sce.trustAs;
  15807. forEach(SCE_CONTEXTS, function(enumValue, name) {
  15808. var lName = lowercase(name);
  15809. sce[camelCase("parse_as_" + lName)] = function(expr) {
  15810. return parse(enumValue, expr);
  15811. };
  15812. sce[camelCase("get_trusted_" + lName)] = function(value) {
  15813. return getTrusted(enumValue, value);
  15814. };
  15815. sce[camelCase("trust_as_" + lName)] = function(value) {
  15816. return trustAs(enumValue, value);
  15817. };
  15818. });
  15819. return sce;
  15820. }];
  15821. }
  15822. /**
  15823. * !!! This is an undocumented "private" service !!!
  15824. *
  15825. * @name $sniffer
  15826. * @requires $window
  15827. * @requires $document
  15828. *
  15829. * @property {boolean} history Does the browser support html5 history api ?
  15830. * @property {boolean} transitions Does the browser support CSS transition events ?
  15831. * @property {boolean} animations Does the browser support CSS animation events ?
  15832. *
  15833. * @description
  15834. * This is very simple implementation of testing browser's features.
  15835. */
  15836. function $SnifferProvider() {
  15837. this.$get = ['$window', '$document', function($window, $document) {
  15838. var eventSupport = {},
  15839. android =
  15840. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  15841. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  15842. document = $document[0] || {},
  15843. vendorPrefix,
  15844. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  15845. bodyStyle = document.body && document.body.style,
  15846. transitions = false,
  15847. animations = false,
  15848. match;
  15849. if (bodyStyle) {
  15850. for (var prop in bodyStyle) {
  15851. if (match = vendorRegex.exec(prop)) {
  15852. vendorPrefix = match[0];
  15853. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  15854. break;
  15855. }
  15856. }
  15857. if (!vendorPrefix) {
  15858. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  15859. }
  15860. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  15861. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  15862. if (android && (!transitions || !animations)) {
  15863. transitions = isString(bodyStyle.webkitTransition);
  15864. animations = isString(bodyStyle.webkitAnimation);
  15865. }
  15866. }
  15867. return {
  15868. // Android has history.pushState, but it does not update location correctly
  15869. // so let's not use the history API at all.
  15870. // http://code.google.com/p/android/issues/detail?id=17471
  15871. // https://github.com/angular/angular.js/issues/904
  15872. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  15873. // so let's not use the history API also
  15874. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  15875. // jshint -W018
  15876. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  15877. // jshint +W018
  15878. hasEvent: function(event) {
  15879. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  15880. // it. In particular the event is not fired when backspace or delete key are pressed or
  15881. // when cut operation is performed.
  15882. // IE10+ implements 'input' event but it erroneously fires under various situations,
  15883. // e.g. when placeholder changes, or a form is focused.
  15884. if (event === 'input' && msie <= 11) return false;
  15885. if (isUndefined(eventSupport[event])) {
  15886. var divElm = document.createElement('div');
  15887. eventSupport[event] = 'on' + event in divElm;
  15888. }
  15889. return eventSupport[event];
  15890. },
  15891. csp: csp(),
  15892. vendorPrefix: vendorPrefix,
  15893. transitions: transitions,
  15894. animations: animations,
  15895. android: android
  15896. };
  15897. }];
  15898. }
  15899. var $compileMinErr = minErr('$compile');
  15900. /**
  15901. * @ngdoc service
  15902. * @name $templateRequest
  15903. *
  15904. * @description
  15905. * The `$templateRequest` service runs security checks then downloads the provided template using
  15906. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  15907. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  15908. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  15909. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  15910. * when `tpl` is of type string and `$templateCache` has the matching entry.
  15911. *
  15912. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  15913. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  15914. *
  15915. * @return {Promise} a promise for the HTTP response data of the given URL.
  15916. *
  15917. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  15918. */
  15919. function $TemplateRequestProvider() {
  15920. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  15921. function handleRequestFn(tpl, ignoreRequestError) {
  15922. handleRequestFn.totalPendingRequests++;
  15923. // We consider the template cache holds only trusted templates, so
  15924. // there's no need to go through whitelisting again for keys that already
  15925. // are included in there. This also makes Angular accept any script
  15926. // directive, no matter its name. However, we still need to unwrap trusted
  15927. // types.
  15928. if (!isString(tpl) || !$templateCache.get(tpl)) {
  15929. tpl = $sce.getTrustedResourceUrl(tpl);
  15930. }
  15931. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  15932. if (isArray(transformResponse)) {
  15933. transformResponse = transformResponse.filter(function(transformer) {
  15934. return transformer !== defaultHttpResponseTransform;
  15935. });
  15936. } else if (transformResponse === defaultHttpResponseTransform) {
  15937. transformResponse = null;
  15938. }
  15939. var httpOptions = {
  15940. cache: $templateCache,
  15941. transformResponse: transformResponse
  15942. };
  15943. return $http.get(tpl, httpOptions)
  15944. ['finally'](function() {
  15945. handleRequestFn.totalPendingRequests--;
  15946. })
  15947. .then(function(response) {
  15948. $templateCache.put(tpl, response.data);
  15949. return response.data;
  15950. }, handleError);
  15951. function handleError(resp) {
  15952. if (!ignoreRequestError) {
  15953. throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  15954. tpl, resp.status, resp.statusText);
  15955. }
  15956. return $q.reject(resp);
  15957. }
  15958. }
  15959. handleRequestFn.totalPendingRequests = 0;
  15960. return handleRequestFn;
  15961. }];
  15962. }
  15963. function $$TestabilityProvider() {
  15964. this.$get = ['$rootScope', '$browser', '$location',
  15965. function($rootScope, $browser, $location) {
  15966. /**
  15967. * @name $testability
  15968. *
  15969. * @description
  15970. * The private $$testability service provides a collection of methods for use when debugging
  15971. * or by automated test and debugging tools.
  15972. */
  15973. var testability = {};
  15974. /**
  15975. * @name $$testability#findBindings
  15976. *
  15977. * @description
  15978. * Returns an array of elements that are bound (via ng-bind or {{}})
  15979. * to expressions matching the input.
  15980. *
  15981. * @param {Element} element The element root to search from.
  15982. * @param {string} expression The binding expression to match.
  15983. * @param {boolean} opt_exactMatch If true, only returns exact matches
  15984. * for the expression. Filters and whitespace are ignored.
  15985. */
  15986. testability.findBindings = function(element, expression, opt_exactMatch) {
  15987. var bindings = element.getElementsByClassName('ng-binding');
  15988. var matches = [];
  15989. forEach(bindings, function(binding) {
  15990. var dataBinding = angular.element(binding).data('$binding');
  15991. if (dataBinding) {
  15992. forEach(dataBinding, function(bindingName) {
  15993. if (opt_exactMatch) {
  15994. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  15995. if (matcher.test(bindingName)) {
  15996. matches.push(binding);
  15997. }
  15998. } else {
  15999. if (bindingName.indexOf(expression) != -1) {
  16000. matches.push(binding);
  16001. }
  16002. }
  16003. });
  16004. }
  16005. });
  16006. return matches;
  16007. };
  16008. /**
  16009. * @name $$testability#findModels
  16010. *
  16011. * @description
  16012. * Returns an array of elements that are two-way found via ng-model to
  16013. * expressions matching the input.
  16014. *
  16015. * @param {Element} element The element root to search from.
  16016. * @param {string} expression The model expression to match.
  16017. * @param {boolean} opt_exactMatch If true, only returns exact matches
  16018. * for the expression.
  16019. */
  16020. testability.findModels = function(element, expression, opt_exactMatch) {
  16021. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  16022. for (var p = 0; p < prefixes.length; ++p) {
  16023. var attributeEquals = opt_exactMatch ? '=' : '*=';
  16024. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  16025. var elements = element.querySelectorAll(selector);
  16026. if (elements.length) {
  16027. return elements;
  16028. }
  16029. }
  16030. };
  16031. /**
  16032. * @name $$testability#getLocation
  16033. *
  16034. * @description
  16035. * Shortcut for getting the location in a browser agnostic way. Returns
  16036. * the path, search, and hash. (e.g. /path?a=b#hash)
  16037. */
  16038. testability.getLocation = function() {
  16039. return $location.url();
  16040. };
  16041. /**
  16042. * @name $$testability#setLocation
  16043. *
  16044. * @description
  16045. * Shortcut for navigating to a location without doing a full page reload.
  16046. *
  16047. * @param {string} url The location url (path, search and hash,
  16048. * e.g. /path?a=b#hash) to go to.
  16049. */
  16050. testability.setLocation = function(url) {
  16051. if (url !== $location.url()) {
  16052. $location.url(url);
  16053. $rootScope.$digest();
  16054. }
  16055. };
  16056. /**
  16057. * @name $$testability#whenStable
  16058. *
  16059. * @description
  16060. * Calls the callback when $timeout and $http requests are completed.
  16061. *
  16062. * @param {function} callback
  16063. */
  16064. testability.whenStable = function(callback) {
  16065. $browser.notifyWhenNoOutstandingRequests(callback);
  16066. };
  16067. return testability;
  16068. }];
  16069. }
  16070. function $TimeoutProvider() {
  16071. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  16072. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  16073. var deferreds = {};
  16074. /**
  16075. * @ngdoc service
  16076. * @name $timeout
  16077. *
  16078. * @description
  16079. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  16080. * block and delegates any exceptions to
  16081. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16082. *
  16083. * The return value of calling `$timeout` is a promise, which will be resolved when
  16084. * the delay has passed and the timeout function, if provided, is executed.
  16085. *
  16086. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  16087. *
  16088. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  16089. * synchronously flush the queue of deferred functions.
  16090. *
  16091. * If you only want a promise that will be resolved after some specified delay
  16092. * then you can call `$timeout` without the `fn` function.
  16093. *
  16094. * @param {function()=} fn A function, whose execution should be delayed.
  16095. * @param {number=} [delay=0] Delay in milliseconds.
  16096. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  16097. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  16098. * @param {...*=} Pass additional parameters to the executed function.
  16099. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  16100. * promise will be resolved with is the return value of the `fn` function.
  16101. *
  16102. */
  16103. function timeout(fn, delay, invokeApply) {
  16104. if (!isFunction(fn)) {
  16105. invokeApply = delay;
  16106. delay = fn;
  16107. fn = noop;
  16108. }
  16109. var args = sliceArgs(arguments, 3),
  16110. skipApply = (isDefined(invokeApply) && !invokeApply),
  16111. deferred = (skipApply ? $$q : $q).defer(),
  16112. promise = deferred.promise,
  16113. timeoutId;
  16114. timeoutId = $browser.defer(function() {
  16115. try {
  16116. deferred.resolve(fn.apply(null, args));
  16117. } catch (e) {
  16118. deferred.reject(e);
  16119. $exceptionHandler(e);
  16120. }
  16121. finally {
  16122. delete deferreds[promise.$$timeoutId];
  16123. }
  16124. if (!skipApply) $rootScope.$apply();
  16125. }, delay);
  16126. promise.$$timeoutId = timeoutId;
  16127. deferreds[timeoutId] = deferred;
  16128. return promise;
  16129. }
  16130. /**
  16131. * @ngdoc method
  16132. * @name $timeout#cancel
  16133. *
  16134. * @description
  16135. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  16136. * resolved with a rejection.
  16137. *
  16138. * @param {Promise=} promise Promise returned by the `$timeout` function.
  16139. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  16140. * canceled.
  16141. */
  16142. timeout.cancel = function(promise) {
  16143. if (promise && promise.$$timeoutId in deferreds) {
  16144. deferreds[promise.$$timeoutId].reject('canceled');
  16145. delete deferreds[promise.$$timeoutId];
  16146. return $browser.defer.cancel(promise.$$timeoutId);
  16147. }
  16148. return false;
  16149. };
  16150. return timeout;
  16151. }];
  16152. }
  16153. // NOTE: The usage of window and document instead of $window and $document here is
  16154. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  16155. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  16156. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  16157. // doesn't know about mocked locations and resolves URLs to the real document - which is
  16158. // exactly the behavior needed here. There is little value is mocking these out for this
  16159. // service.
  16160. var urlParsingNode = document.createElement("a");
  16161. var originUrl = urlResolve(window.location.href);
  16162. /**
  16163. *
  16164. * Implementation Notes for non-IE browsers
  16165. * ----------------------------------------
  16166. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  16167. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  16168. * URL will be resolved into an absolute URL in the context of the application document.
  16169. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  16170. * properties are all populated to reflect the normalized URL. This approach has wide
  16171. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  16172. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16173. *
  16174. * Implementation Notes for IE
  16175. * ---------------------------
  16176. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  16177. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  16178. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  16179. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  16180. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  16181. * properties such as protocol, hostname, port, etc.
  16182. *
  16183. * References:
  16184. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  16185. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16186. * http://url.spec.whatwg.org/#urlutils
  16187. * https://github.com/angular/angular.js/pull/2902
  16188. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  16189. *
  16190. * @kind function
  16191. * @param {string} url The URL to be parsed.
  16192. * @description Normalizes and parses a URL.
  16193. * @returns {object} Returns the normalized URL as a dictionary.
  16194. *
  16195. * | member name | Description |
  16196. * |---------------|----------------|
  16197. * | href | A normalized version of the provided URL if it was not an absolute URL |
  16198. * | protocol | The protocol including the trailing colon |
  16199. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  16200. * | search | The search params, minus the question mark |
  16201. * | hash | The hash string, minus the hash symbol
  16202. * | hostname | The hostname
  16203. * | port | The port, without ":"
  16204. * | pathname | The pathname, beginning with "/"
  16205. *
  16206. */
  16207. function urlResolve(url) {
  16208. var href = url;
  16209. if (msie) {
  16210. // Normalize before parse. Refer Implementation Notes on why this is
  16211. // done in two steps on IE.
  16212. urlParsingNode.setAttribute("href", href);
  16213. href = urlParsingNode.href;
  16214. }
  16215. urlParsingNode.setAttribute('href', href);
  16216. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  16217. return {
  16218. href: urlParsingNode.href,
  16219. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  16220. host: urlParsingNode.host,
  16221. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  16222. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  16223. hostname: urlParsingNode.hostname,
  16224. port: urlParsingNode.port,
  16225. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  16226. ? urlParsingNode.pathname
  16227. : '/' + urlParsingNode.pathname
  16228. };
  16229. }
  16230. /**
  16231. * Parse a request URL and determine whether this is a same-origin request as the application document.
  16232. *
  16233. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  16234. * or a parsed URL object.
  16235. * @returns {boolean} Whether the request is for the same origin as the application document.
  16236. */
  16237. function urlIsSameOrigin(requestUrl) {
  16238. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  16239. return (parsed.protocol === originUrl.protocol &&
  16240. parsed.host === originUrl.host);
  16241. }
  16242. /**
  16243. * @ngdoc service
  16244. * @name $window
  16245. *
  16246. * @description
  16247. * A reference to the browser's `window` object. While `window`
  16248. * is globally available in JavaScript, it causes testability problems, because
  16249. * it is a global variable. In angular we always refer to it through the
  16250. * `$window` service, so it may be overridden, removed or mocked for testing.
  16251. *
  16252. * Expressions, like the one defined for the `ngClick` directive in the example
  16253. * below, are evaluated with respect to the current scope. Therefore, there is
  16254. * no risk of inadvertently coding in a dependency on a global value in such an
  16255. * expression.
  16256. *
  16257. * @example
  16258. <example module="windowExample">
  16259. <file name="index.html">
  16260. <script>
  16261. angular.module('windowExample', [])
  16262. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  16263. $scope.greeting = 'Hello, World!';
  16264. $scope.doGreeting = function(greeting) {
  16265. $window.alert(greeting);
  16266. };
  16267. }]);
  16268. </script>
  16269. <div ng-controller="ExampleController">
  16270. <input type="text" ng-model="greeting" aria-label="greeting" />
  16271. <button ng-click="doGreeting(greeting)">ALERT</button>
  16272. </div>
  16273. </file>
  16274. <file name="protractor.js" type="protractor">
  16275. it('should display the greeting in the input box', function() {
  16276. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  16277. // If we click the button it will block the test runner
  16278. // element(':button').click();
  16279. });
  16280. </file>
  16281. </example>
  16282. */
  16283. function $WindowProvider() {
  16284. this.$get = valueFn(window);
  16285. }
  16286. /**
  16287. * @name $$cookieReader
  16288. * @requires $document
  16289. *
  16290. * @description
  16291. * This is a private service for reading cookies used by $http and ngCookies
  16292. *
  16293. * @return {Object} a key/value map of the current cookies
  16294. */
  16295. function $$CookieReader($document) {
  16296. var rawDocument = $document[0] || {};
  16297. var lastCookies = {};
  16298. var lastCookieString = '';
  16299. function safeDecodeURIComponent(str) {
  16300. try {
  16301. return decodeURIComponent(str);
  16302. } catch (e) {
  16303. return str;
  16304. }
  16305. }
  16306. return function() {
  16307. var cookieArray, cookie, i, index, name;
  16308. var currentCookieString = rawDocument.cookie || '';
  16309. if (currentCookieString !== lastCookieString) {
  16310. lastCookieString = currentCookieString;
  16311. cookieArray = lastCookieString.split('; ');
  16312. lastCookies = {};
  16313. for (i = 0; i < cookieArray.length; i++) {
  16314. cookie = cookieArray[i];
  16315. index = cookie.indexOf('=');
  16316. if (index > 0) { //ignore nameless cookies
  16317. name = safeDecodeURIComponent(cookie.substring(0, index));
  16318. // the first value that is seen for a cookie is the most
  16319. // specific one. values for the same cookie name that
  16320. // follow are for less specific paths.
  16321. if (lastCookies[name] === undefined) {
  16322. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  16323. }
  16324. }
  16325. }
  16326. }
  16327. return lastCookies;
  16328. };
  16329. }
  16330. $$CookieReader.$inject = ['$document'];
  16331. function $$CookieReaderProvider() {
  16332. this.$get = $$CookieReader;
  16333. }
  16334. /* global currencyFilter: true,
  16335. dateFilter: true,
  16336. filterFilter: true,
  16337. jsonFilter: true,
  16338. limitToFilter: true,
  16339. lowercaseFilter: true,
  16340. numberFilter: true,
  16341. orderByFilter: true,
  16342. uppercaseFilter: true,
  16343. */
  16344. /**
  16345. * @ngdoc provider
  16346. * @name $filterProvider
  16347. * @description
  16348. *
  16349. * Filters are just functions which transform input to an output. However filters need to be
  16350. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  16351. * annotated with dependencies and is responsible for creating a filter function.
  16352. *
  16353. * <div class="alert alert-warning">
  16354. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16355. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16356. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16357. * (`myapp_subsection_filterx`).
  16358. * </div>
  16359. *
  16360. * ```js
  16361. * // Filter registration
  16362. * function MyModule($provide, $filterProvider) {
  16363. * // create a service to demonstrate injection (not always needed)
  16364. * $provide.value('greet', function(name){
  16365. * return 'Hello ' + name + '!';
  16366. * });
  16367. *
  16368. * // register a filter factory which uses the
  16369. * // greet service to demonstrate DI.
  16370. * $filterProvider.register('greet', function(greet){
  16371. * // return the filter function which uses the greet service
  16372. * // to generate salutation
  16373. * return function(text) {
  16374. * // filters need to be forgiving so check input validity
  16375. * return text && greet(text) || text;
  16376. * };
  16377. * });
  16378. * }
  16379. * ```
  16380. *
  16381. * The filter function is registered with the `$injector` under the filter name suffix with
  16382. * `Filter`.
  16383. *
  16384. * ```js
  16385. * it('should be the same instance', inject(
  16386. * function($filterProvider) {
  16387. * $filterProvider.register('reverse', function(){
  16388. * return ...;
  16389. * });
  16390. * },
  16391. * function($filter, reverseFilter) {
  16392. * expect($filter('reverse')).toBe(reverseFilter);
  16393. * });
  16394. * ```
  16395. *
  16396. *
  16397. * For more information about how angular filters work, and how to create your own filters, see
  16398. * {@link guide/filter Filters} in the Angular Developer Guide.
  16399. */
  16400. /**
  16401. * @ngdoc service
  16402. * @name $filter
  16403. * @kind function
  16404. * @description
  16405. * Filters are used for formatting data displayed to the user.
  16406. *
  16407. * The general syntax in templates is as follows:
  16408. *
  16409. * {{ expression [| filter_name[:parameter_value] ... ] }}
  16410. *
  16411. * @param {String} name Name of the filter function to retrieve
  16412. * @return {Function} the filter function
  16413. * @example
  16414. <example name="$filter" module="filterExample">
  16415. <file name="index.html">
  16416. <div ng-controller="MainCtrl">
  16417. <h3>{{ originalText }}</h3>
  16418. <h3>{{ filteredText }}</h3>
  16419. </div>
  16420. </file>
  16421. <file name="script.js">
  16422. angular.module('filterExample', [])
  16423. .controller('MainCtrl', function($scope, $filter) {
  16424. $scope.originalText = 'hello';
  16425. $scope.filteredText = $filter('uppercase')($scope.originalText);
  16426. });
  16427. </file>
  16428. </example>
  16429. */
  16430. $FilterProvider.$inject = ['$provide'];
  16431. function $FilterProvider($provide) {
  16432. var suffix = 'Filter';
  16433. /**
  16434. * @ngdoc method
  16435. * @name $filterProvider#register
  16436. * @param {string|Object} name Name of the filter function, or an object map of filters where
  16437. * the keys are the filter names and the values are the filter factories.
  16438. *
  16439. * <div class="alert alert-warning">
  16440. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16441. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16442. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16443. * (`myapp_subsection_filterx`).
  16444. * </div>
  16445. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  16446. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  16447. * of the registered filter instances.
  16448. */
  16449. function register(name, factory) {
  16450. if (isObject(name)) {
  16451. var filters = {};
  16452. forEach(name, function(filter, key) {
  16453. filters[key] = register(key, filter);
  16454. });
  16455. return filters;
  16456. } else {
  16457. return $provide.factory(name + suffix, factory);
  16458. }
  16459. }
  16460. this.register = register;
  16461. this.$get = ['$injector', function($injector) {
  16462. return function(name) {
  16463. return $injector.get(name + suffix);
  16464. };
  16465. }];
  16466. ////////////////////////////////////////
  16467. /* global
  16468. currencyFilter: false,
  16469. dateFilter: false,
  16470. filterFilter: false,
  16471. jsonFilter: false,
  16472. limitToFilter: false,
  16473. lowercaseFilter: false,
  16474. numberFilter: false,
  16475. orderByFilter: false,
  16476. uppercaseFilter: false,
  16477. */
  16478. register('currency', currencyFilter);
  16479. register('date', dateFilter);
  16480. register('filter', filterFilter);
  16481. register('json', jsonFilter);
  16482. register('limitTo', limitToFilter);
  16483. register('lowercase', lowercaseFilter);
  16484. register('number', numberFilter);
  16485. register('orderBy', orderByFilter);
  16486. register('uppercase', uppercaseFilter);
  16487. }
  16488. /**
  16489. * @ngdoc filter
  16490. * @name filter
  16491. * @kind function
  16492. *
  16493. * @description
  16494. * Selects a subset of items from `array` and returns it as a new array.
  16495. *
  16496. * @param {Array} array The source array.
  16497. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  16498. * `array`.
  16499. *
  16500. * Can be one of:
  16501. *
  16502. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  16503. * objects with string properties in `array` that match this string will be returned. This also
  16504. * applies to nested object properties.
  16505. * The predicate can be negated by prefixing the string with `!`.
  16506. *
  16507. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  16508. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  16509. * which have property `name` containing "M" and property `phone` containing "1". A special
  16510. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  16511. * property of the object or its nested object properties. That's equivalent to the simple
  16512. * substring match with a `string` as described above. The predicate can be negated by prefixing
  16513. * the string with `!`.
  16514. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  16515. * not containing "M".
  16516. *
  16517. * Note that a named property will match properties on the same level only, while the special
  16518. * `$` property will match properties on the same level or deeper. E.g. an array item like
  16519. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  16520. * **will** be matched by `{$: 'John'}`.
  16521. *
  16522. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  16523. * The function is called for each element of the array, with the element, its index, and
  16524. * the entire array itself as arguments.
  16525. *
  16526. * The final result is an array of those elements that the predicate returned true for.
  16527. *
  16528. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  16529. * determining if the expected value (from the filter expression) and actual value (from
  16530. * the object in the array) should be considered a match.
  16531. *
  16532. * Can be one of:
  16533. *
  16534. * - `function(actual, expected)`:
  16535. * The function will be given the object value and the predicate value to compare and
  16536. * should return true if both values should be considered equal.
  16537. *
  16538. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  16539. * This is essentially strict comparison of expected and actual.
  16540. *
  16541. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  16542. * insensitive way.
  16543. *
  16544. * Primitive values are converted to strings. Objects are not compared against primitives,
  16545. * unless they have a custom `toString` method (e.g. `Date` objects).
  16546. *
  16547. * @example
  16548. <example>
  16549. <file name="index.html">
  16550. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  16551. {name:'Mary', phone:'800-BIG-MARY'},
  16552. {name:'Mike', phone:'555-4321'},
  16553. {name:'Adam', phone:'555-5678'},
  16554. {name:'Julie', phone:'555-8765'},
  16555. {name:'Juliette', phone:'555-5678'}]"></div>
  16556. <label>Search: <input ng-model="searchText"></label>
  16557. <table id="searchTextResults">
  16558. <tr><th>Name</th><th>Phone</th></tr>
  16559. <tr ng-repeat="friend in friends | filter:searchText">
  16560. <td>{{friend.name}}</td>
  16561. <td>{{friend.phone}}</td>
  16562. </tr>
  16563. </table>
  16564. <hr>
  16565. <label>Any: <input ng-model="search.$"></label> <br>
  16566. <label>Name only <input ng-model="search.name"></label><br>
  16567. <label>Phone only <input ng-model="search.phone"></label><br>
  16568. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  16569. <table id="searchObjResults">
  16570. <tr><th>Name</th><th>Phone</th></tr>
  16571. <tr ng-repeat="friendObj in friends | filter:search:strict">
  16572. <td>{{friendObj.name}}</td>
  16573. <td>{{friendObj.phone}}</td>
  16574. </tr>
  16575. </table>
  16576. </file>
  16577. <file name="protractor.js" type="protractor">
  16578. var expectFriendNames = function(expectedNames, key) {
  16579. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  16580. arr.forEach(function(wd, i) {
  16581. expect(wd.getText()).toMatch(expectedNames[i]);
  16582. });
  16583. });
  16584. };
  16585. it('should search across all fields when filtering with a string', function() {
  16586. var searchText = element(by.model('searchText'));
  16587. searchText.clear();
  16588. searchText.sendKeys('m');
  16589. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  16590. searchText.clear();
  16591. searchText.sendKeys('76');
  16592. expectFriendNames(['John', 'Julie'], 'friend');
  16593. });
  16594. it('should search in specific fields when filtering with a predicate object', function() {
  16595. var searchAny = element(by.model('search.$'));
  16596. searchAny.clear();
  16597. searchAny.sendKeys('i');
  16598. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  16599. });
  16600. it('should use a equal comparison when comparator is true', function() {
  16601. var searchName = element(by.model('search.name'));
  16602. var strict = element(by.model('strict'));
  16603. searchName.clear();
  16604. searchName.sendKeys('Julie');
  16605. strict.click();
  16606. expectFriendNames(['Julie'], 'friendObj');
  16607. });
  16608. </file>
  16609. </example>
  16610. */
  16611. function filterFilter() {
  16612. return function(array, expression, comparator) {
  16613. if (!isArrayLike(array)) {
  16614. if (array == null) {
  16615. return array;
  16616. } else {
  16617. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  16618. }
  16619. }
  16620. var expressionType = getTypeForFilter(expression);
  16621. var predicateFn;
  16622. var matchAgainstAnyProp;
  16623. switch (expressionType) {
  16624. case 'function':
  16625. predicateFn = expression;
  16626. break;
  16627. case 'boolean':
  16628. case 'null':
  16629. case 'number':
  16630. case 'string':
  16631. matchAgainstAnyProp = true;
  16632. //jshint -W086
  16633. case 'object':
  16634. //jshint +W086
  16635. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  16636. break;
  16637. default:
  16638. return array;
  16639. }
  16640. return Array.prototype.filter.call(array, predicateFn);
  16641. };
  16642. }
  16643. // Helper functions for `filterFilter`
  16644. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  16645. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  16646. var predicateFn;
  16647. if (comparator === true) {
  16648. comparator = equals;
  16649. } else if (!isFunction(comparator)) {
  16650. comparator = function(actual, expected) {
  16651. if (isUndefined(actual)) {
  16652. // No substring matching against `undefined`
  16653. return false;
  16654. }
  16655. if ((actual === null) || (expected === null)) {
  16656. // No substring matching against `null`; only match against `null`
  16657. return actual === expected;
  16658. }
  16659. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  16660. // Should not compare primitives against objects, unless they have custom `toString` method
  16661. return false;
  16662. }
  16663. actual = lowercase('' + actual);
  16664. expected = lowercase('' + expected);
  16665. return actual.indexOf(expected) !== -1;
  16666. };
  16667. }
  16668. predicateFn = function(item) {
  16669. if (shouldMatchPrimitives && !isObject(item)) {
  16670. return deepCompare(item, expression.$, comparator, false);
  16671. }
  16672. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  16673. };
  16674. return predicateFn;
  16675. }
  16676. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  16677. var actualType = getTypeForFilter(actual);
  16678. var expectedType = getTypeForFilter(expected);
  16679. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  16680. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  16681. } else if (isArray(actual)) {
  16682. // In case `actual` is an array, consider it a match
  16683. // if ANY of it's items matches `expected`
  16684. return actual.some(function(item) {
  16685. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  16686. });
  16687. }
  16688. switch (actualType) {
  16689. case 'object':
  16690. var key;
  16691. if (matchAgainstAnyProp) {
  16692. for (key in actual) {
  16693. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  16694. return true;
  16695. }
  16696. }
  16697. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  16698. } else if (expectedType === 'object') {
  16699. for (key in expected) {
  16700. var expectedVal = expected[key];
  16701. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  16702. continue;
  16703. }
  16704. var matchAnyProperty = key === '$';
  16705. var actualVal = matchAnyProperty ? actual : actual[key];
  16706. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  16707. return false;
  16708. }
  16709. }
  16710. return true;
  16711. } else {
  16712. return comparator(actual, expected);
  16713. }
  16714. break;
  16715. case 'function':
  16716. return false;
  16717. default:
  16718. return comparator(actual, expected);
  16719. }
  16720. }
  16721. // Used for easily differentiating between `null` and actual `object`
  16722. function getTypeForFilter(val) {
  16723. return (val === null) ? 'null' : typeof val;
  16724. }
  16725. /**
  16726. * @ngdoc filter
  16727. * @name currency
  16728. * @kind function
  16729. *
  16730. * @description
  16731. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  16732. * symbol for current locale is used.
  16733. *
  16734. * @param {number} amount Input to filter.
  16735. * @param {string=} symbol Currency symbol or identifier to be displayed.
  16736. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  16737. * @returns {string} Formatted number.
  16738. *
  16739. *
  16740. * @example
  16741. <example module="currencyExample">
  16742. <file name="index.html">
  16743. <script>
  16744. angular.module('currencyExample', [])
  16745. .controller('ExampleController', ['$scope', function($scope) {
  16746. $scope.amount = 1234.56;
  16747. }]);
  16748. </script>
  16749. <div ng-controller="ExampleController">
  16750. <input type="number" ng-model="amount" aria-label="amount"> <br>
  16751. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  16752. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  16753. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  16754. </div>
  16755. </file>
  16756. <file name="protractor.js" type="protractor">
  16757. it('should init with 1234.56', function() {
  16758. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  16759. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  16760. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  16761. });
  16762. it('should update', function() {
  16763. if (browser.params.browser == 'safari') {
  16764. // Safari does not understand the minus key. See
  16765. // https://github.com/angular/protractor/issues/481
  16766. return;
  16767. }
  16768. element(by.model('amount')).clear();
  16769. element(by.model('amount')).sendKeys('-1234');
  16770. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  16771. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  16772. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  16773. });
  16774. </file>
  16775. </example>
  16776. */
  16777. currencyFilter.$inject = ['$locale'];
  16778. function currencyFilter($locale) {
  16779. var formats = $locale.NUMBER_FORMATS;
  16780. return function(amount, currencySymbol, fractionSize) {
  16781. if (isUndefined(currencySymbol)) {
  16782. currencySymbol = formats.CURRENCY_SYM;
  16783. }
  16784. if (isUndefined(fractionSize)) {
  16785. fractionSize = formats.PATTERNS[1].maxFrac;
  16786. }
  16787. // if null or undefined pass it through
  16788. return (amount == null)
  16789. ? amount
  16790. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  16791. replace(/\u00A4/g, currencySymbol);
  16792. };
  16793. }
  16794. /**
  16795. * @ngdoc filter
  16796. * @name number
  16797. * @kind function
  16798. *
  16799. * @description
  16800. * Formats a number as text.
  16801. *
  16802. * If the input is null or undefined, it will just be returned.
  16803. * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
  16804. * If the input is not a number an empty string is returned.
  16805. *
  16806. *
  16807. * @param {number|string} number Number to format.
  16808. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  16809. * If this is not provided then the fraction size is computed from the current locale's number
  16810. * formatting pattern. In the case of the default locale, it will be 3.
  16811. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  16812. *
  16813. * @example
  16814. <example module="numberFilterExample">
  16815. <file name="index.html">
  16816. <script>
  16817. angular.module('numberFilterExample', [])
  16818. .controller('ExampleController', ['$scope', function($scope) {
  16819. $scope.val = 1234.56789;
  16820. }]);
  16821. </script>
  16822. <div ng-controller="ExampleController">
  16823. <label>Enter number: <input ng-model='val'></label><br>
  16824. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  16825. No fractions: <span>{{val | number:0}}</span><br>
  16826. Negative number: <span>{{-val | number:4}}</span>
  16827. </div>
  16828. </file>
  16829. <file name="protractor.js" type="protractor">
  16830. it('should format numbers', function() {
  16831. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  16832. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  16833. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  16834. });
  16835. it('should update', function() {
  16836. element(by.model('val')).clear();
  16837. element(by.model('val')).sendKeys('3374.333');
  16838. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  16839. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  16840. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  16841. });
  16842. </file>
  16843. </example>
  16844. */
  16845. numberFilter.$inject = ['$locale'];
  16846. function numberFilter($locale) {
  16847. var formats = $locale.NUMBER_FORMATS;
  16848. return function(number, fractionSize) {
  16849. // if null or undefined pass it through
  16850. return (number == null)
  16851. ? number
  16852. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  16853. fractionSize);
  16854. };
  16855. }
  16856. var DECIMAL_SEP = '.';
  16857. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  16858. if (isObject(number)) return '';
  16859. var isNegative = number < 0;
  16860. number = Math.abs(number);
  16861. var isInfinity = number === Infinity;
  16862. if (!isInfinity && !isFinite(number)) return '';
  16863. var numStr = number + '',
  16864. formatedText = '',
  16865. hasExponent = false,
  16866. parts = [];
  16867. if (isInfinity) formatedText = '\u221e';
  16868. if (!isInfinity && numStr.indexOf('e') !== -1) {
  16869. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  16870. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  16871. number = 0;
  16872. } else {
  16873. formatedText = numStr;
  16874. hasExponent = true;
  16875. }
  16876. }
  16877. if (!isInfinity && !hasExponent) {
  16878. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  16879. // determine fractionSize if it is not specified
  16880. if (isUndefined(fractionSize)) {
  16881. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  16882. }
  16883. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  16884. // inspired by:
  16885. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  16886. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  16887. var fraction = ('' + number).split(DECIMAL_SEP);
  16888. var whole = fraction[0];
  16889. fraction = fraction[1] || '';
  16890. var i, pos = 0,
  16891. lgroup = pattern.lgSize,
  16892. group = pattern.gSize;
  16893. if (whole.length >= (lgroup + group)) {
  16894. pos = whole.length - lgroup;
  16895. for (i = 0; i < pos; i++) {
  16896. if ((pos - i) % group === 0 && i !== 0) {
  16897. formatedText += groupSep;
  16898. }
  16899. formatedText += whole.charAt(i);
  16900. }
  16901. }
  16902. for (i = pos; i < whole.length; i++) {
  16903. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  16904. formatedText += groupSep;
  16905. }
  16906. formatedText += whole.charAt(i);
  16907. }
  16908. // format fraction part.
  16909. while (fraction.length < fractionSize) {
  16910. fraction += '0';
  16911. }
  16912. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  16913. } else {
  16914. if (fractionSize > 0 && number < 1) {
  16915. formatedText = number.toFixed(fractionSize);
  16916. number = parseFloat(formatedText);
  16917. }
  16918. }
  16919. if (number === 0) {
  16920. isNegative = false;
  16921. }
  16922. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  16923. formatedText,
  16924. isNegative ? pattern.negSuf : pattern.posSuf);
  16925. return parts.join('');
  16926. }
  16927. function padNumber(num, digits, trim) {
  16928. var neg = '';
  16929. if (num < 0) {
  16930. neg = '-';
  16931. num = -num;
  16932. }
  16933. num = '' + num;
  16934. while (num.length < digits) num = '0' + num;
  16935. if (trim) {
  16936. num = num.substr(num.length - digits);
  16937. }
  16938. return neg + num;
  16939. }
  16940. function dateGetter(name, size, offset, trim) {
  16941. offset = offset || 0;
  16942. return function(date) {
  16943. var value = date['get' + name]();
  16944. if (offset > 0 || value > -offset) {
  16945. value += offset;
  16946. }
  16947. if (value === 0 && offset == -12) value = 12;
  16948. return padNumber(value, size, trim);
  16949. };
  16950. }
  16951. function dateStrGetter(name, shortForm) {
  16952. return function(date, formats) {
  16953. var value = date['get' + name]();
  16954. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  16955. return formats[get][value];
  16956. };
  16957. }
  16958. function timeZoneGetter(date, formats, offset) {
  16959. var zone = -1 * offset;
  16960. var paddedZone = (zone >= 0) ? "+" : "";
  16961. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  16962. padNumber(Math.abs(zone % 60), 2);
  16963. return paddedZone;
  16964. }
  16965. function getFirstThursdayOfYear(year) {
  16966. // 0 = index of January
  16967. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  16968. // 4 = index of Thursday (+1 to account for 1st = 5)
  16969. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  16970. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  16971. }
  16972. function getThursdayThisWeek(datetime) {
  16973. return new Date(datetime.getFullYear(), datetime.getMonth(),
  16974. // 4 = index of Thursday
  16975. datetime.getDate() + (4 - datetime.getDay()));
  16976. }
  16977. function weekGetter(size) {
  16978. return function(date) {
  16979. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  16980. thisThurs = getThursdayThisWeek(date);
  16981. var diff = +thisThurs - +firstThurs,
  16982. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  16983. return padNumber(result, size);
  16984. };
  16985. }
  16986. function ampmGetter(date, formats) {
  16987. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  16988. }
  16989. function eraGetter(date, formats) {
  16990. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  16991. }
  16992. function longEraGetter(date, formats) {
  16993. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  16994. }
  16995. var DATE_FORMATS = {
  16996. yyyy: dateGetter('FullYear', 4),
  16997. yy: dateGetter('FullYear', 2, 0, true),
  16998. y: dateGetter('FullYear', 1),
  16999. MMMM: dateStrGetter('Month'),
  17000. MMM: dateStrGetter('Month', true),
  17001. MM: dateGetter('Month', 2, 1),
  17002. M: dateGetter('Month', 1, 1),
  17003. dd: dateGetter('Date', 2),
  17004. d: dateGetter('Date', 1),
  17005. HH: dateGetter('Hours', 2),
  17006. H: dateGetter('Hours', 1),
  17007. hh: dateGetter('Hours', 2, -12),
  17008. h: dateGetter('Hours', 1, -12),
  17009. mm: dateGetter('Minutes', 2),
  17010. m: dateGetter('Minutes', 1),
  17011. ss: dateGetter('Seconds', 2),
  17012. s: dateGetter('Seconds', 1),
  17013. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  17014. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  17015. sss: dateGetter('Milliseconds', 3),
  17016. EEEE: dateStrGetter('Day'),
  17017. EEE: dateStrGetter('Day', true),
  17018. a: ampmGetter,
  17019. Z: timeZoneGetter,
  17020. ww: weekGetter(2),
  17021. w: weekGetter(1),
  17022. G: eraGetter,
  17023. GG: eraGetter,
  17024. GGG: eraGetter,
  17025. GGGG: longEraGetter
  17026. };
  17027. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  17028. NUMBER_STRING = /^\-?\d+$/;
  17029. /**
  17030. * @ngdoc filter
  17031. * @name date
  17032. * @kind function
  17033. *
  17034. * @description
  17035. * Formats `date` to a string based on the requested `format`.
  17036. *
  17037. * `format` string can be composed of the following elements:
  17038. *
  17039. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  17040. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  17041. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  17042. * * `'MMMM'`: Month in year (January-December)
  17043. * * `'MMM'`: Month in year (Jan-Dec)
  17044. * * `'MM'`: Month in year, padded (01-12)
  17045. * * `'M'`: Month in year (1-12)
  17046. * * `'dd'`: Day in month, padded (01-31)
  17047. * * `'d'`: Day in month (1-31)
  17048. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  17049. * * `'EEE'`: Day in Week, (Sun-Sat)
  17050. * * `'HH'`: Hour in day, padded (00-23)
  17051. * * `'H'`: Hour in day (0-23)
  17052. * * `'hh'`: Hour in AM/PM, padded (01-12)
  17053. * * `'h'`: Hour in AM/PM, (1-12)
  17054. * * `'mm'`: Minute in hour, padded (00-59)
  17055. * * `'m'`: Minute in hour (0-59)
  17056. * * `'ss'`: Second in minute, padded (00-59)
  17057. * * `'s'`: Second in minute (0-59)
  17058. * * `'sss'`: Millisecond in second, padded (000-999)
  17059. * * `'a'`: AM/PM marker
  17060. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  17061. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  17062. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  17063. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  17064. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  17065. *
  17066. * `format` string can also be one of the following predefined
  17067. * {@link guide/i18n localizable formats}:
  17068. *
  17069. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  17070. * (e.g. Sep 3, 2010 12:05:08 PM)
  17071. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  17072. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  17073. * (e.g. Friday, September 3, 2010)
  17074. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  17075. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  17076. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  17077. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  17078. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  17079. *
  17080. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  17081. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  17082. * (e.g. `"h 'o''clock'"`).
  17083. *
  17084. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  17085. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  17086. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  17087. * specified in the string input, the time is considered to be in the local timezone.
  17088. * @param {string=} format Formatting rules (see Description). If not specified,
  17089. * `mediumDate` is used.
  17090. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  17091. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  17092. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  17093. * If not specified, the timezone of the browser will be used.
  17094. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  17095. *
  17096. * @example
  17097. <example>
  17098. <file name="index.html">
  17099. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  17100. <span>{{1288323623006 | date:'medium'}}</span><br>
  17101. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  17102. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  17103. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  17104. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  17105. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  17106. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  17107. </file>
  17108. <file name="protractor.js" type="protractor">
  17109. it('should format date', function() {
  17110. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  17111. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  17112. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  17113. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  17114. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  17115. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  17116. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  17117. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  17118. });
  17119. </file>
  17120. </example>
  17121. */
  17122. dateFilter.$inject = ['$locale'];
  17123. function dateFilter($locale) {
  17124. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  17125. // 1 2 3 4 5 6 7 8 9 10 11
  17126. function jsonStringToDate(string) {
  17127. var match;
  17128. if (match = string.match(R_ISO8601_STR)) {
  17129. var date = new Date(0),
  17130. tzHour = 0,
  17131. tzMin = 0,
  17132. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  17133. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  17134. if (match[9]) {
  17135. tzHour = toInt(match[9] + match[10]);
  17136. tzMin = toInt(match[9] + match[11]);
  17137. }
  17138. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  17139. var h = toInt(match[4] || 0) - tzHour;
  17140. var m = toInt(match[5] || 0) - tzMin;
  17141. var s = toInt(match[6] || 0);
  17142. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  17143. timeSetter.call(date, h, m, s, ms);
  17144. return date;
  17145. }
  17146. return string;
  17147. }
  17148. return function(date, format, timezone) {
  17149. var text = '',
  17150. parts = [],
  17151. fn, match;
  17152. format = format || 'mediumDate';
  17153. format = $locale.DATETIME_FORMATS[format] || format;
  17154. if (isString(date)) {
  17155. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  17156. }
  17157. if (isNumber(date)) {
  17158. date = new Date(date);
  17159. }
  17160. if (!isDate(date) || !isFinite(date.getTime())) {
  17161. return date;
  17162. }
  17163. while (format) {
  17164. match = DATE_FORMATS_SPLIT.exec(format);
  17165. if (match) {
  17166. parts = concat(parts, match, 1);
  17167. format = parts.pop();
  17168. } else {
  17169. parts.push(format);
  17170. format = null;
  17171. }
  17172. }
  17173. var dateTimezoneOffset = date.getTimezoneOffset();
  17174. if (timezone) {
  17175. dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  17176. date = convertTimezoneToLocal(date, timezone, true);
  17177. }
  17178. forEach(parts, function(value) {
  17179. fn = DATE_FORMATS[value];
  17180. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  17181. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  17182. });
  17183. return text;
  17184. };
  17185. }
  17186. /**
  17187. * @ngdoc filter
  17188. * @name json
  17189. * @kind function
  17190. *
  17191. * @description
  17192. * Allows you to convert a JavaScript object into JSON string.
  17193. *
  17194. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  17195. * the binding is automatically converted to JSON.
  17196. *
  17197. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  17198. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  17199. * @returns {string} JSON string.
  17200. *
  17201. *
  17202. * @example
  17203. <example>
  17204. <file name="index.html">
  17205. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  17206. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  17207. </file>
  17208. <file name="protractor.js" type="protractor">
  17209. it('should jsonify filtered objects', function() {
  17210. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17211. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17212. });
  17213. </file>
  17214. </example>
  17215. *
  17216. */
  17217. function jsonFilter() {
  17218. return function(object, spacing) {
  17219. if (isUndefined(spacing)) {
  17220. spacing = 2;
  17221. }
  17222. return toJson(object, spacing);
  17223. };
  17224. }
  17225. /**
  17226. * @ngdoc filter
  17227. * @name lowercase
  17228. * @kind function
  17229. * @description
  17230. * Converts string to lowercase.
  17231. * @see angular.lowercase
  17232. */
  17233. var lowercaseFilter = valueFn(lowercase);
  17234. /**
  17235. * @ngdoc filter
  17236. * @name uppercase
  17237. * @kind function
  17238. * @description
  17239. * Converts string to uppercase.
  17240. * @see angular.uppercase
  17241. */
  17242. var uppercaseFilter = valueFn(uppercase);
  17243. /**
  17244. * @ngdoc filter
  17245. * @name limitTo
  17246. * @kind function
  17247. *
  17248. * @description
  17249. * Creates a new array or string containing only a specified number of elements. The elements
  17250. * are taken from either the beginning or the end of the source array, string or number, as specified by
  17251. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  17252. * converted to a string.
  17253. *
  17254. * @param {Array|string|number} input Source array, string or number to be limited.
  17255. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  17256. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  17257. * If the number is negative, `limit` number of items from the end of the source array/string
  17258. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  17259. * the input will be returned unchanged.
  17260. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  17261. * indicates an offset from the end of `input`. Defaults to `0`.
  17262. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  17263. * had less than `limit` elements.
  17264. *
  17265. * @example
  17266. <example module="limitToExample">
  17267. <file name="index.html">
  17268. <script>
  17269. angular.module('limitToExample', [])
  17270. .controller('ExampleController', ['$scope', function($scope) {
  17271. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  17272. $scope.letters = "abcdefghi";
  17273. $scope.longNumber = 2345432342;
  17274. $scope.numLimit = 3;
  17275. $scope.letterLimit = 3;
  17276. $scope.longNumberLimit = 3;
  17277. }]);
  17278. </script>
  17279. <div ng-controller="ExampleController">
  17280. <label>
  17281. Limit {{numbers}} to:
  17282. <input type="number" step="1" ng-model="numLimit">
  17283. </label>
  17284. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  17285. <label>
  17286. Limit {{letters}} to:
  17287. <input type="number" step="1" ng-model="letterLimit">
  17288. </label>
  17289. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  17290. <label>
  17291. Limit {{longNumber}} to:
  17292. <input type="number" step="1" ng-model="longNumberLimit">
  17293. </label>
  17294. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  17295. </div>
  17296. </file>
  17297. <file name="protractor.js" type="protractor">
  17298. var numLimitInput = element(by.model('numLimit'));
  17299. var letterLimitInput = element(by.model('letterLimit'));
  17300. var longNumberLimitInput = element(by.model('longNumberLimit'));
  17301. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  17302. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  17303. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  17304. it('should limit the number array to first three items', function() {
  17305. expect(numLimitInput.getAttribute('value')).toBe('3');
  17306. expect(letterLimitInput.getAttribute('value')).toBe('3');
  17307. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  17308. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  17309. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  17310. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  17311. });
  17312. // There is a bug in safari and protractor that doesn't like the minus key
  17313. // it('should update the output when -3 is entered', function() {
  17314. // numLimitInput.clear();
  17315. // numLimitInput.sendKeys('-3');
  17316. // letterLimitInput.clear();
  17317. // letterLimitInput.sendKeys('-3');
  17318. // longNumberLimitInput.clear();
  17319. // longNumberLimitInput.sendKeys('-3');
  17320. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  17321. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  17322. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  17323. // });
  17324. it('should not exceed the maximum size of input array', function() {
  17325. numLimitInput.clear();
  17326. numLimitInput.sendKeys('100');
  17327. letterLimitInput.clear();
  17328. letterLimitInput.sendKeys('100');
  17329. longNumberLimitInput.clear();
  17330. longNumberLimitInput.sendKeys('100');
  17331. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  17332. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  17333. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  17334. });
  17335. </file>
  17336. </example>
  17337. */
  17338. function limitToFilter() {
  17339. return function(input, limit, begin) {
  17340. if (Math.abs(Number(limit)) === Infinity) {
  17341. limit = Number(limit);
  17342. } else {
  17343. limit = toInt(limit);
  17344. }
  17345. if (isNaN(limit)) return input;
  17346. if (isNumber(input)) input = input.toString();
  17347. if (!isArray(input) && !isString(input)) return input;
  17348. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  17349. begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;
  17350. if (limit >= 0) {
  17351. return input.slice(begin, begin + limit);
  17352. } else {
  17353. if (begin === 0) {
  17354. return input.slice(limit, input.length);
  17355. } else {
  17356. return input.slice(Math.max(0, begin + limit), begin);
  17357. }
  17358. }
  17359. };
  17360. }
  17361. /**
  17362. * @ngdoc filter
  17363. * @name orderBy
  17364. * @kind function
  17365. *
  17366. * @description
  17367. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  17368. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  17369. * as expected, make sure they are actually being saved as numbers and not strings.
  17370. *
  17371. * @param {Array} array The array to sort.
  17372. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  17373. * used by the comparator to determine the order of elements.
  17374. *
  17375. * Can be one of:
  17376. *
  17377. * - `function`: Getter function. The result of this function will be sorted using the
  17378. * `<`, `===`, `>` operator.
  17379. * - `string`: An Angular expression. The result of this expression is used to compare elements
  17380. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  17381. * 3 first characters of a property called `name`). The result of a constant expression
  17382. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  17383. * to sort object by the value of their `special name` property). An expression can be
  17384. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  17385. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  17386. * element itself is used to compare where sorting.
  17387. * - `Array`: An array of function or string predicates. The first predicate in the array
  17388. * is used for sorting, but when two items are equivalent, the next predicate is used.
  17389. *
  17390. * If the predicate is missing or empty then it defaults to `'+'`.
  17391. *
  17392. * @param {boolean=} reverse Reverse the order of the array.
  17393. * @returns {Array} Sorted copy of the source array.
  17394. *
  17395. *
  17396. * @example
  17397. * The example below demonstrates a simple ngRepeat, where the data is sorted
  17398. * by age in descending order (predicate is set to `'-age'`).
  17399. * `reverse` is not set, which means it defaults to `false`.
  17400. <example module="orderByExample">
  17401. <file name="index.html">
  17402. <script>
  17403. angular.module('orderByExample', [])
  17404. .controller('ExampleController', ['$scope', function($scope) {
  17405. $scope.friends =
  17406. [{name:'John', phone:'555-1212', age:10},
  17407. {name:'Mary', phone:'555-9876', age:19},
  17408. {name:'Mike', phone:'555-4321', age:21},
  17409. {name:'Adam', phone:'555-5678', age:35},
  17410. {name:'Julie', phone:'555-8765', age:29}];
  17411. }]);
  17412. </script>
  17413. <div ng-controller="ExampleController">
  17414. <table class="friend">
  17415. <tr>
  17416. <th>Name</th>
  17417. <th>Phone Number</th>
  17418. <th>Age</th>
  17419. </tr>
  17420. <tr ng-repeat="friend in friends | orderBy:'-age'">
  17421. <td>{{friend.name}}</td>
  17422. <td>{{friend.phone}}</td>
  17423. <td>{{friend.age}}</td>
  17424. </tr>
  17425. </table>
  17426. </div>
  17427. </file>
  17428. </example>
  17429. *
  17430. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  17431. * as shown in the next example.
  17432. * @example
  17433. <example module="orderByExample">
  17434. <file name="index.html">
  17435. <script>
  17436. angular.module('orderByExample', [])
  17437. .controller('ExampleController', ['$scope', function($scope) {
  17438. $scope.friends =
  17439. [{name:'John', phone:'555-1212', age:10},
  17440. {name:'Mary', phone:'555-9876', age:19},
  17441. {name:'Mike', phone:'555-4321', age:21},
  17442. {name:'Adam', phone:'555-5678', age:35},
  17443. {name:'Julie', phone:'555-8765', age:29}];
  17444. $scope.predicate = 'age';
  17445. $scope.reverse = true;
  17446. $scope.order = function(predicate) {
  17447. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  17448. $scope.predicate = predicate;
  17449. };
  17450. }]);
  17451. </script>
  17452. <style type="text/css">
  17453. .sortorder:after {
  17454. content: '\25b2';
  17455. }
  17456. .sortorder.reverse:after {
  17457. content: '\25bc';
  17458. }
  17459. </style>
  17460. <div ng-controller="ExampleController">
  17461. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  17462. <hr/>
  17463. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  17464. <table class="friend">
  17465. <tr>
  17466. <th>
  17467. <a href="" ng-click="order('name')">Name</a>
  17468. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  17469. </th>
  17470. <th>
  17471. <a href="" ng-click="order('phone')">Phone Number</a>
  17472. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  17473. </th>
  17474. <th>
  17475. <a href="" ng-click="order('age')">Age</a>
  17476. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  17477. </th>
  17478. </tr>
  17479. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  17480. <td>{{friend.name}}</td>
  17481. <td>{{friend.phone}}</td>
  17482. <td>{{friend.age}}</td>
  17483. </tr>
  17484. </table>
  17485. </div>
  17486. </file>
  17487. </example>
  17488. *
  17489. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  17490. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  17491. * desired parameters.
  17492. *
  17493. * Example:
  17494. *
  17495. * @example
  17496. <example module="orderByExample">
  17497. <file name="index.html">
  17498. <div ng-controller="ExampleController">
  17499. <table class="friend">
  17500. <tr>
  17501. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  17502. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  17503. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  17504. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  17505. </tr>
  17506. <tr ng-repeat="friend in friends">
  17507. <td>{{friend.name}}</td>
  17508. <td>{{friend.phone}}</td>
  17509. <td>{{friend.age}}</td>
  17510. </tr>
  17511. </table>
  17512. </div>
  17513. </file>
  17514. <file name="script.js">
  17515. angular.module('orderByExample', [])
  17516. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  17517. var orderBy = $filter('orderBy');
  17518. $scope.friends = [
  17519. { name: 'John', phone: '555-1212', age: 10 },
  17520. { name: 'Mary', phone: '555-9876', age: 19 },
  17521. { name: 'Mike', phone: '555-4321', age: 21 },
  17522. { name: 'Adam', phone: '555-5678', age: 35 },
  17523. { name: 'Julie', phone: '555-8765', age: 29 }
  17524. ];
  17525. $scope.order = function(predicate, reverse) {
  17526. $scope.friends = orderBy($scope.friends, predicate, reverse);
  17527. };
  17528. $scope.order('-age',false);
  17529. }]);
  17530. </file>
  17531. </example>
  17532. */
  17533. orderByFilter.$inject = ['$parse'];
  17534. function orderByFilter($parse) {
  17535. return function(array, sortPredicate, reverseOrder) {
  17536. if (!(isArrayLike(array))) return array;
  17537. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  17538. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  17539. var predicates = processPredicates(sortPredicate, reverseOrder);
  17540. // Add a predicate at the end that evaluates to the element index. This makes the
  17541. // sort stable as it works as a tie-breaker when all the input predicates cannot
  17542. // distinguish between two elements.
  17543. predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
  17544. // The next three lines are a version of a Swartzian Transform idiom from Perl
  17545. // (sometimes called the Decorate-Sort-Undecorate idiom)
  17546. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  17547. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  17548. compareValues.sort(doComparison);
  17549. array = compareValues.map(function(item) { return item.value; });
  17550. return array;
  17551. function getComparisonObject(value, index) {
  17552. return {
  17553. value: value,
  17554. predicateValues: predicates.map(function(predicate) {
  17555. return getPredicateValue(predicate.get(value), index);
  17556. })
  17557. };
  17558. }
  17559. function doComparison(v1, v2) {
  17560. var result = 0;
  17561. for (var index=0, length = predicates.length; index < length; ++index) {
  17562. result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
  17563. if (result) break;
  17564. }
  17565. return result;
  17566. }
  17567. };
  17568. function processPredicates(sortPredicate, reverseOrder) {
  17569. reverseOrder = reverseOrder ? -1 : 1;
  17570. return sortPredicate.map(function(predicate) {
  17571. var descending = 1, get = identity;
  17572. if (isFunction(predicate)) {
  17573. get = predicate;
  17574. } else if (isString(predicate)) {
  17575. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  17576. descending = predicate.charAt(0) == '-' ? -1 : 1;
  17577. predicate = predicate.substring(1);
  17578. }
  17579. if (predicate !== '') {
  17580. get = $parse(predicate);
  17581. if (get.constant) {
  17582. var key = get();
  17583. get = function(value) { return value[key]; };
  17584. }
  17585. }
  17586. }
  17587. return { get: get, descending: descending * reverseOrder };
  17588. });
  17589. }
  17590. function isPrimitive(value) {
  17591. switch (typeof value) {
  17592. case 'number': /* falls through */
  17593. case 'boolean': /* falls through */
  17594. case 'string':
  17595. return true;
  17596. default:
  17597. return false;
  17598. }
  17599. }
  17600. function objectValue(value, index) {
  17601. // If `valueOf` is a valid function use that
  17602. if (typeof value.valueOf === 'function') {
  17603. value = value.valueOf();
  17604. if (isPrimitive(value)) return value;
  17605. }
  17606. // If `toString` is a valid function and not the one from `Object.prototype` use that
  17607. if (hasCustomToString(value)) {
  17608. value = value.toString();
  17609. if (isPrimitive(value)) return value;
  17610. }
  17611. // We have a basic object so we use the position of the object in the collection
  17612. return index;
  17613. }
  17614. function getPredicateValue(value, index) {
  17615. var type = typeof value;
  17616. if (value === null) {
  17617. type = 'string';
  17618. value = 'null';
  17619. } else if (type === 'string') {
  17620. value = value.toLowerCase();
  17621. } else if (type === 'object') {
  17622. value = objectValue(value, index);
  17623. }
  17624. return { value: value, type: type };
  17625. }
  17626. function compare(v1, v2) {
  17627. var result = 0;
  17628. if (v1.type === v2.type) {
  17629. if (v1.value !== v2.value) {
  17630. result = v1.value < v2.value ? -1 : 1;
  17631. }
  17632. } else {
  17633. result = v1.type < v2.type ? -1 : 1;
  17634. }
  17635. return result;
  17636. }
  17637. }
  17638. function ngDirective(directive) {
  17639. if (isFunction(directive)) {
  17640. directive = {
  17641. link: directive
  17642. };
  17643. }
  17644. directive.restrict = directive.restrict || 'AC';
  17645. return valueFn(directive);
  17646. }
  17647. /**
  17648. * @ngdoc directive
  17649. * @name a
  17650. * @restrict E
  17651. *
  17652. * @description
  17653. * Modifies the default behavior of the html A tag so that the default action is prevented when
  17654. * the href attribute is empty.
  17655. *
  17656. * This change permits the easy creation of action links with the `ngClick` directive
  17657. * without changing the location or causing page reloads, e.g.:
  17658. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  17659. */
  17660. var htmlAnchorDirective = valueFn({
  17661. restrict: 'E',
  17662. compile: function(element, attr) {
  17663. if (!attr.href && !attr.xlinkHref) {
  17664. return function(scope, element) {
  17665. // If the linked element is not an anchor tag anymore, do nothing
  17666. if (element[0].nodeName.toLowerCase() !== 'a') return;
  17667. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  17668. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  17669. 'xlink:href' : 'href';
  17670. element.on('click', function(event) {
  17671. // if we have no href url, then don't navigate anywhere.
  17672. if (!element.attr(href)) {
  17673. event.preventDefault();
  17674. }
  17675. });
  17676. };
  17677. }
  17678. }
  17679. });
  17680. /**
  17681. * @ngdoc directive
  17682. * @name ngHref
  17683. * @restrict A
  17684. * @priority 99
  17685. *
  17686. * @description
  17687. * Using Angular markup like `{{hash}}` in an href attribute will
  17688. * make the link go to the wrong URL if the user clicks it before
  17689. * Angular has a chance to replace the `{{hash}}` markup with its
  17690. * value. Until Angular replaces the markup the link will be broken
  17691. * and will most likely return a 404 error. The `ngHref` directive
  17692. * solves this problem.
  17693. *
  17694. * The wrong way to write it:
  17695. * ```html
  17696. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17697. * ```
  17698. *
  17699. * The correct way to write it:
  17700. * ```html
  17701. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17702. * ```
  17703. *
  17704. * @element A
  17705. * @param {template} ngHref any string which can contain `{{}}` markup.
  17706. *
  17707. * @example
  17708. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  17709. * in links and their different behaviors:
  17710. <example>
  17711. <file name="index.html">
  17712. <input ng-model="value" /><br />
  17713. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  17714. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  17715. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  17716. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  17717. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  17718. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  17719. </file>
  17720. <file name="protractor.js" type="protractor">
  17721. it('should execute ng-click but not reload when href without value', function() {
  17722. element(by.id('link-1')).click();
  17723. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  17724. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  17725. });
  17726. it('should execute ng-click but not reload when href empty string', function() {
  17727. element(by.id('link-2')).click();
  17728. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  17729. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  17730. });
  17731. it('should execute ng-click and change url when ng-href specified', function() {
  17732. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  17733. element(by.id('link-3')).click();
  17734. // At this point, we navigate away from an Angular page, so we need
  17735. // to use browser.driver to get the base webdriver.
  17736. browser.wait(function() {
  17737. return browser.driver.getCurrentUrl().then(function(url) {
  17738. return url.match(/\/123$/);
  17739. });
  17740. }, 5000, 'page should navigate to /123');
  17741. });
  17742. it('should execute ng-click but not reload when href empty string and name specified', function() {
  17743. element(by.id('link-4')).click();
  17744. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  17745. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  17746. });
  17747. it('should execute ng-click but not reload when no href but name specified', function() {
  17748. element(by.id('link-5')).click();
  17749. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  17750. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  17751. });
  17752. it('should only change url when only ng-href', function() {
  17753. element(by.model('value')).clear();
  17754. element(by.model('value')).sendKeys('6');
  17755. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  17756. element(by.id('link-6')).click();
  17757. // At this point, we navigate away from an Angular page, so we need
  17758. // to use browser.driver to get the base webdriver.
  17759. browser.wait(function() {
  17760. return browser.driver.getCurrentUrl().then(function(url) {
  17761. return url.match(/\/6$/);
  17762. });
  17763. }, 5000, 'page should navigate to /6');
  17764. });
  17765. </file>
  17766. </example>
  17767. */
  17768. /**
  17769. * @ngdoc directive
  17770. * @name ngSrc
  17771. * @restrict A
  17772. * @priority 99
  17773. *
  17774. * @description
  17775. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  17776. * work right: The browser will fetch from the URL with the literal
  17777. * text `{{hash}}` until Angular replaces the expression inside
  17778. * `{{hash}}`. The `ngSrc` directive solves this problem.
  17779. *
  17780. * The buggy way to write it:
  17781. * ```html
  17782. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  17783. * ```
  17784. *
  17785. * The correct way to write it:
  17786. * ```html
  17787. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  17788. * ```
  17789. *
  17790. * @element IMG
  17791. * @param {template} ngSrc any string which can contain `{{}}` markup.
  17792. */
  17793. /**
  17794. * @ngdoc directive
  17795. * @name ngSrcset
  17796. * @restrict A
  17797. * @priority 99
  17798. *
  17799. * @description
  17800. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  17801. * work right: The browser will fetch from the URL with the literal
  17802. * text `{{hash}}` until Angular replaces the expression inside
  17803. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  17804. *
  17805. * The buggy way to write it:
  17806. * ```html
  17807. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  17808. * ```
  17809. *
  17810. * The correct way to write it:
  17811. * ```html
  17812. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  17813. * ```
  17814. *
  17815. * @element IMG
  17816. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  17817. */
  17818. /**
  17819. * @ngdoc directive
  17820. * @name ngDisabled
  17821. * @restrict A
  17822. * @priority 100
  17823. *
  17824. * @description
  17825. *
  17826. * This directive sets the `disabled` attribute on the element if the
  17827. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  17828. *
  17829. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  17830. * attribute. The following example would make the button enabled on Chrome/Firefox
  17831. * but not on older IEs:
  17832. *
  17833. * ```html
  17834. * <!-- See below for an example of ng-disabled being used correctly -->
  17835. * <div ng-init="isDisabled = false">
  17836. * <button disabled="{{isDisabled}}">Disabled</button>
  17837. * </div>
  17838. * ```
  17839. *
  17840. * This is because the HTML specification does not require browsers to preserve the values of
  17841. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  17842. * If we put an Angular interpolation expression into such an attribute then the
  17843. * binding information would be lost when the browser removes the attribute.
  17844. *
  17845. * @example
  17846. <example>
  17847. <file name="index.html">
  17848. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  17849. <button ng-model="button" ng-disabled="checked">Button</button>
  17850. </file>
  17851. <file name="protractor.js" type="protractor">
  17852. it('should toggle button', function() {
  17853. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  17854. element(by.model('checked')).click();
  17855. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  17856. });
  17857. </file>
  17858. </example>
  17859. *
  17860. * @element INPUT
  17861. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  17862. * then the `disabled` attribute will be set on the element
  17863. */
  17864. /**
  17865. * @ngdoc directive
  17866. * @name ngChecked
  17867. * @restrict A
  17868. * @priority 100
  17869. *
  17870. * @description
  17871. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  17872. *
  17873. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  17874. * as this can lead to unexpected behavior.
  17875. *
  17876. * ### Why do we need `ngChecked`?
  17877. *
  17878. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17879. * such as checked. (Their presence means true and their absence means false.)
  17880. * If we put an Angular interpolation expression into such an attribute then the
  17881. * binding information would be lost when the browser removes the attribute.
  17882. * The `ngChecked` directive solves this problem for the `checked` attribute.
  17883. * This complementary directive is not removed by the browser and so provides
  17884. * a permanent reliable place to store the binding information.
  17885. * @example
  17886. <example>
  17887. <file name="index.html">
  17888. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  17889. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  17890. </file>
  17891. <file name="protractor.js" type="protractor">
  17892. it('should check both checkBoxes', function() {
  17893. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  17894. element(by.model('master')).click();
  17895. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  17896. });
  17897. </file>
  17898. </example>
  17899. *
  17900. * @element INPUT
  17901. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  17902. * then the `checked` attribute will be set on the element
  17903. */
  17904. /**
  17905. * @ngdoc directive
  17906. * @name ngReadonly
  17907. * @restrict A
  17908. * @priority 100
  17909. *
  17910. * @description
  17911. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17912. * such as readonly. (Their presence means true and their absence means false.)
  17913. * If we put an Angular interpolation expression into such an attribute then the
  17914. * binding information would be lost when the browser removes the attribute.
  17915. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  17916. * This complementary directive is not removed by the browser and so provides
  17917. * a permanent reliable place to store the binding information.
  17918. * @example
  17919. <example>
  17920. <file name="index.html">
  17921. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  17922. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  17923. </file>
  17924. <file name="protractor.js" type="protractor">
  17925. it('should toggle readonly attr', function() {
  17926. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  17927. element(by.model('checked')).click();
  17928. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  17929. });
  17930. </file>
  17931. </example>
  17932. *
  17933. * @element INPUT
  17934. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  17935. * then special attribute "readonly" will be set on the element
  17936. */
  17937. /**
  17938. * @ngdoc directive
  17939. * @name ngSelected
  17940. * @restrict A
  17941. * @priority 100
  17942. *
  17943. * @description
  17944. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17945. * such as selected. (Their presence means true and their absence means false.)
  17946. * If we put an Angular interpolation expression into such an attribute then the
  17947. * binding information would be lost when the browser removes the attribute.
  17948. * The `ngSelected` directive solves this problem for the `selected` attribute.
  17949. * This complementary directive is not removed by the browser and so provides
  17950. * a permanent reliable place to store the binding information.
  17951. *
  17952. * @example
  17953. <example>
  17954. <file name="index.html">
  17955. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  17956. <select aria-label="ngSelected demo">
  17957. <option>Hello!</option>
  17958. <option id="greet" ng-selected="selected">Greetings!</option>
  17959. </select>
  17960. </file>
  17961. <file name="protractor.js" type="protractor">
  17962. it('should select Greetings!', function() {
  17963. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  17964. element(by.model('selected')).click();
  17965. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  17966. });
  17967. </file>
  17968. </example>
  17969. *
  17970. * @element OPTION
  17971. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  17972. * then special attribute "selected" will be set on the element
  17973. */
  17974. /**
  17975. * @ngdoc directive
  17976. * @name ngOpen
  17977. * @restrict A
  17978. * @priority 100
  17979. *
  17980. * @description
  17981. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17982. * such as open. (Their presence means true and their absence means false.)
  17983. * If we put an Angular interpolation expression into such an attribute then the
  17984. * binding information would be lost when the browser removes the attribute.
  17985. * The `ngOpen` directive solves this problem for the `open` attribute.
  17986. * This complementary directive is not removed by the browser and so provides
  17987. * a permanent reliable place to store the binding information.
  17988. * @example
  17989. <example>
  17990. <file name="index.html">
  17991. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  17992. <details id="details" ng-open="open">
  17993. <summary>Show/Hide me</summary>
  17994. </details>
  17995. </file>
  17996. <file name="protractor.js" type="protractor">
  17997. it('should toggle open', function() {
  17998. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  17999. element(by.model('open')).click();
  18000. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  18001. });
  18002. </file>
  18003. </example>
  18004. *
  18005. * @element DETAILS
  18006. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  18007. * then special attribute "open" will be set on the element
  18008. */
  18009. var ngAttributeAliasDirectives = {};
  18010. // boolean attrs are evaluated
  18011. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  18012. // binding to multiple is not supported
  18013. if (propName == "multiple") return;
  18014. function defaultLinkFn(scope, element, attr) {
  18015. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  18016. attr.$set(attrName, !!value);
  18017. });
  18018. }
  18019. var normalized = directiveNormalize('ng-' + attrName);
  18020. var linkFn = defaultLinkFn;
  18021. if (propName === 'checked') {
  18022. linkFn = function(scope, element, attr) {
  18023. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  18024. if (attr.ngModel !== attr[normalized]) {
  18025. defaultLinkFn(scope, element, attr);
  18026. }
  18027. };
  18028. }
  18029. ngAttributeAliasDirectives[normalized] = function() {
  18030. return {
  18031. restrict: 'A',
  18032. priority: 100,
  18033. link: linkFn
  18034. };
  18035. };
  18036. });
  18037. // aliased input attrs are evaluated
  18038. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  18039. ngAttributeAliasDirectives[ngAttr] = function() {
  18040. return {
  18041. priority: 100,
  18042. link: function(scope, element, attr) {
  18043. //special case ngPattern when a literal regular expression value
  18044. //is used as the expression (this way we don't have to watch anything).
  18045. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  18046. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  18047. if (match) {
  18048. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  18049. return;
  18050. }
  18051. }
  18052. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  18053. attr.$set(ngAttr, value);
  18054. });
  18055. }
  18056. };
  18057. };
  18058. });
  18059. // ng-src, ng-srcset, ng-href are interpolated
  18060. forEach(['src', 'srcset', 'href'], function(attrName) {
  18061. var normalized = directiveNormalize('ng-' + attrName);
  18062. ngAttributeAliasDirectives[normalized] = function() {
  18063. return {
  18064. priority: 99, // it needs to run after the attributes are interpolated
  18065. link: function(scope, element, attr) {
  18066. var propName = attrName,
  18067. name = attrName;
  18068. if (attrName === 'href' &&
  18069. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  18070. name = 'xlinkHref';
  18071. attr.$attr[name] = 'xlink:href';
  18072. propName = null;
  18073. }
  18074. attr.$observe(normalized, function(value) {
  18075. if (!value) {
  18076. if (attrName === 'href') {
  18077. attr.$set(name, null);
  18078. }
  18079. return;
  18080. }
  18081. attr.$set(name, value);
  18082. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  18083. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  18084. // to set the property as well to achieve the desired effect.
  18085. // we use attr[attrName] value since $set can sanitize the url.
  18086. if (msie && propName) element.prop(propName, attr[name]);
  18087. });
  18088. }
  18089. };
  18090. };
  18091. });
  18092. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  18093. */
  18094. var nullFormCtrl = {
  18095. $addControl: noop,
  18096. $$renameControl: nullFormRenameControl,
  18097. $removeControl: noop,
  18098. $setValidity: noop,
  18099. $setDirty: noop,
  18100. $setPristine: noop,
  18101. $setSubmitted: noop
  18102. },
  18103. SUBMITTED_CLASS = 'ng-submitted';
  18104. function nullFormRenameControl(control, name) {
  18105. control.$name = name;
  18106. }
  18107. /**
  18108. * @ngdoc type
  18109. * @name form.FormController
  18110. *
  18111. * @property {boolean} $pristine True if user has not interacted with the form yet.
  18112. * @property {boolean} $dirty True if user has already interacted with the form.
  18113. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  18114. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  18115. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  18116. *
  18117. * @property {Object} $error Is an object hash, containing references to controls or
  18118. * forms with failing validators, where:
  18119. *
  18120. * - keys are validation tokens (error names),
  18121. * - values are arrays of controls or forms that have a failing validator for given error name.
  18122. *
  18123. * Built-in validation tokens:
  18124. *
  18125. * - `email`
  18126. * - `max`
  18127. * - `maxlength`
  18128. * - `min`
  18129. * - `minlength`
  18130. * - `number`
  18131. * - `pattern`
  18132. * - `required`
  18133. * - `url`
  18134. * - `date`
  18135. * - `datetimelocal`
  18136. * - `time`
  18137. * - `week`
  18138. * - `month`
  18139. *
  18140. * @description
  18141. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  18142. * such as being valid/invalid or dirty/pristine.
  18143. *
  18144. * Each {@link ng.directive:form form} directive creates an instance
  18145. * of `FormController`.
  18146. *
  18147. */
  18148. //asks for $scope to fool the BC controller module
  18149. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  18150. function FormController(element, attrs, $scope, $animate, $interpolate) {
  18151. var form = this,
  18152. controls = [];
  18153. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  18154. // init state
  18155. form.$error = {};
  18156. form.$$success = {};
  18157. form.$pending = undefined;
  18158. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  18159. form.$dirty = false;
  18160. form.$pristine = true;
  18161. form.$valid = true;
  18162. form.$invalid = false;
  18163. form.$submitted = false;
  18164. parentForm.$addControl(form);
  18165. /**
  18166. * @ngdoc method
  18167. * @name form.FormController#$rollbackViewValue
  18168. *
  18169. * @description
  18170. * Rollback all form controls pending updates to the `$modelValue`.
  18171. *
  18172. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18173. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  18174. * a form that uses `ng-model-options` to pend updates.
  18175. */
  18176. form.$rollbackViewValue = function() {
  18177. forEach(controls, function(control) {
  18178. control.$rollbackViewValue();
  18179. });
  18180. };
  18181. /**
  18182. * @ngdoc method
  18183. * @name form.FormController#$commitViewValue
  18184. *
  18185. * @description
  18186. * Commit all form controls pending updates to the `$modelValue`.
  18187. *
  18188. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18189. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  18190. * usually handles calling this in response to input events.
  18191. */
  18192. form.$commitViewValue = function() {
  18193. forEach(controls, function(control) {
  18194. control.$commitViewValue();
  18195. });
  18196. };
  18197. /**
  18198. * @ngdoc method
  18199. * @name form.FormController#$addControl
  18200. *
  18201. * @description
  18202. * Register a control with the form.
  18203. *
  18204. * Input elements using ngModelController do this automatically when they are linked.
  18205. */
  18206. form.$addControl = function(control) {
  18207. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  18208. // and not added to the scope. Now we throw an error.
  18209. assertNotHasOwnProperty(control.$name, 'input');
  18210. controls.push(control);
  18211. if (control.$name) {
  18212. form[control.$name] = control;
  18213. }
  18214. };
  18215. // Private API: rename a form control
  18216. form.$$renameControl = function(control, newName) {
  18217. var oldName = control.$name;
  18218. if (form[oldName] === control) {
  18219. delete form[oldName];
  18220. }
  18221. form[newName] = control;
  18222. control.$name = newName;
  18223. };
  18224. /**
  18225. * @ngdoc method
  18226. * @name form.FormController#$removeControl
  18227. *
  18228. * @description
  18229. * Deregister a control from the form.
  18230. *
  18231. * Input elements using ngModelController do this automatically when they are destroyed.
  18232. */
  18233. form.$removeControl = function(control) {
  18234. if (control.$name && form[control.$name] === control) {
  18235. delete form[control.$name];
  18236. }
  18237. forEach(form.$pending, function(value, name) {
  18238. form.$setValidity(name, null, control);
  18239. });
  18240. forEach(form.$error, function(value, name) {
  18241. form.$setValidity(name, null, control);
  18242. });
  18243. forEach(form.$$success, function(value, name) {
  18244. form.$setValidity(name, null, control);
  18245. });
  18246. arrayRemove(controls, control);
  18247. };
  18248. /**
  18249. * @ngdoc method
  18250. * @name form.FormController#$setValidity
  18251. *
  18252. * @description
  18253. * Sets the validity of a form control.
  18254. *
  18255. * This method will also propagate to parent forms.
  18256. */
  18257. addSetValidityMethod({
  18258. ctrl: this,
  18259. $element: element,
  18260. set: function(object, property, controller) {
  18261. var list = object[property];
  18262. if (!list) {
  18263. object[property] = [controller];
  18264. } else {
  18265. var index = list.indexOf(controller);
  18266. if (index === -1) {
  18267. list.push(controller);
  18268. }
  18269. }
  18270. },
  18271. unset: function(object, property, controller) {
  18272. var list = object[property];
  18273. if (!list) {
  18274. return;
  18275. }
  18276. arrayRemove(list, controller);
  18277. if (list.length === 0) {
  18278. delete object[property];
  18279. }
  18280. },
  18281. parentForm: parentForm,
  18282. $animate: $animate
  18283. });
  18284. /**
  18285. * @ngdoc method
  18286. * @name form.FormController#$setDirty
  18287. *
  18288. * @description
  18289. * Sets the form to a dirty state.
  18290. *
  18291. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  18292. * state (ng-dirty class). This method will also propagate to parent forms.
  18293. */
  18294. form.$setDirty = function() {
  18295. $animate.removeClass(element, PRISTINE_CLASS);
  18296. $animate.addClass(element, DIRTY_CLASS);
  18297. form.$dirty = true;
  18298. form.$pristine = false;
  18299. parentForm.$setDirty();
  18300. };
  18301. /**
  18302. * @ngdoc method
  18303. * @name form.FormController#$setPristine
  18304. *
  18305. * @description
  18306. * Sets the form to its pristine state.
  18307. *
  18308. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  18309. * state (ng-pristine class). This method will also propagate to all the controls contained
  18310. * in this form.
  18311. *
  18312. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  18313. * saving or resetting it.
  18314. */
  18315. form.$setPristine = function() {
  18316. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  18317. form.$dirty = false;
  18318. form.$pristine = true;
  18319. form.$submitted = false;
  18320. forEach(controls, function(control) {
  18321. control.$setPristine();
  18322. });
  18323. };
  18324. /**
  18325. * @ngdoc method
  18326. * @name form.FormController#$setUntouched
  18327. *
  18328. * @description
  18329. * Sets the form to its untouched state.
  18330. *
  18331. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  18332. * untouched state (ng-untouched class).
  18333. *
  18334. * Setting a form controls back to their untouched state is often useful when setting the form
  18335. * back to its pristine state.
  18336. */
  18337. form.$setUntouched = function() {
  18338. forEach(controls, function(control) {
  18339. control.$setUntouched();
  18340. });
  18341. };
  18342. /**
  18343. * @ngdoc method
  18344. * @name form.FormController#$setSubmitted
  18345. *
  18346. * @description
  18347. * Sets the form to its submitted state.
  18348. */
  18349. form.$setSubmitted = function() {
  18350. $animate.addClass(element, SUBMITTED_CLASS);
  18351. form.$submitted = true;
  18352. parentForm.$setSubmitted();
  18353. };
  18354. }
  18355. /**
  18356. * @ngdoc directive
  18357. * @name ngForm
  18358. * @restrict EAC
  18359. *
  18360. * @description
  18361. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  18362. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  18363. * sub-group of controls needs to be determined.
  18364. *
  18365. * Note: the purpose of `ngForm` is to group controls,
  18366. * but not to be a replacement for the `<form>` tag with all of its capabilities
  18367. * (e.g. posting to the server, ...).
  18368. *
  18369. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  18370. * related scope, under this name.
  18371. *
  18372. */
  18373. /**
  18374. * @ngdoc directive
  18375. * @name form
  18376. * @restrict E
  18377. *
  18378. * @description
  18379. * Directive that instantiates
  18380. * {@link form.FormController FormController}.
  18381. *
  18382. * If the `name` attribute is specified, the form controller is published onto the current scope under
  18383. * this name.
  18384. *
  18385. * # Alias: {@link ng.directive:ngForm `ngForm`}
  18386. *
  18387. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  18388. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  18389. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  18390. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  18391. * using Angular validation directives in forms that are dynamically generated using the
  18392. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  18393. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  18394. * `ngForm` directive and nest these in an outer `form` element.
  18395. *
  18396. *
  18397. * # CSS classes
  18398. * - `ng-valid` is set if the form is valid.
  18399. * - `ng-invalid` is set if the form is invalid.
  18400. * - `ng-pristine` is set if the form is pristine.
  18401. * - `ng-dirty` is set if the form is dirty.
  18402. * - `ng-submitted` is set if the form was submitted.
  18403. *
  18404. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  18405. *
  18406. *
  18407. * # Submitting a form and preventing the default action
  18408. *
  18409. * Since the role of forms in client-side Angular applications is different than in classical
  18410. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  18411. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  18412. * to handle the form submission in an application-specific way.
  18413. *
  18414. * For this reason, Angular prevents the default action (form submission to the server) unless the
  18415. * `<form>` element has an `action` attribute specified.
  18416. *
  18417. * You can use one of the following two ways to specify what javascript method should be called when
  18418. * a form is submitted:
  18419. *
  18420. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  18421. * - {@link ng.directive:ngClick ngClick} directive on the first
  18422. * button or input field of type submit (input[type=submit])
  18423. *
  18424. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  18425. * or {@link ng.directive:ngClick ngClick} directives.
  18426. * This is because of the following form submission rules in the HTML specification:
  18427. *
  18428. * - If a form has only one input field then hitting enter in this field triggers form submit
  18429. * (`ngSubmit`)
  18430. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  18431. * doesn't trigger submit
  18432. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  18433. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  18434. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  18435. *
  18436. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  18437. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  18438. * to have access to the updated model.
  18439. *
  18440. * ## Animation Hooks
  18441. *
  18442. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  18443. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  18444. * other validations that are performed within the form. Animations in ngForm are similar to how
  18445. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  18446. * as JS animations.
  18447. *
  18448. * The following example shows a simple way to utilize CSS transitions to style a form element
  18449. * that has been rendered as invalid after it has been validated:
  18450. *
  18451. * <pre>
  18452. * //be sure to include ngAnimate as a module to hook into more
  18453. * //advanced animations
  18454. * .my-form {
  18455. * transition:0.5s linear all;
  18456. * background: white;
  18457. * }
  18458. * .my-form.ng-invalid {
  18459. * background: red;
  18460. * color:white;
  18461. * }
  18462. * </pre>
  18463. *
  18464. * @example
  18465. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  18466. <file name="index.html">
  18467. <script>
  18468. angular.module('formExample', [])
  18469. .controller('FormController', ['$scope', function($scope) {
  18470. $scope.userType = 'guest';
  18471. }]);
  18472. </script>
  18473. <style>
  18474. .my-form {
  18475. -webkit-transition:all linear 0.5s;
  18476. transition:all linear 0.5s;
  18477. background: transparent;
  18478. }
  18479. .my-form.ng-invalid {
  18480. background: red;
  18481. }
  18482. </style>
  18483. <form name="myForm" ng-controller="FormController" class="my-form">
  18484. userType: <input name="input" ng-model="userType" required>
  18485. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  18486. <code>userType = {{userType}}</code><br>
  18487. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  18488. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  18489. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  18490. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  18491. </form>
  18492. </file>
  18493. <file name="protractor.js" type="protractor">
  18494. it('should initialize to model', function() {
  18495. var userType = element(by.binding('userType'));
  18496. var valid = element(by.binding('myForm.input.$valid'));
  18497. expect(userType.getText()).toContain('guest');
  18498. expect(valid.getText()).toContain('true');
  18499. });
  18500. it('should be invalid if empty', function() {
  18501. var userType = element(by.binding('userType'));
  18502. var valid = element(by.binding('myForm.input.$valid'));
  18503. var userInput = element(by.model('userType'));
  18504. userInput.clear();
  18505. userInput.sendKeys('');
  18506. expect(userType.getText()).toEqual('userType =');
  18507. expect(valid.getText()).toContain('false');
  18508. });
  18509. </file>
  18510. </example>
  18511. *
  18512. * @param {string=} name Name of the form. If specified, the form controller will be published into
  18513. * related scope, under this name.
  18514. */
  18515. var formDirectiveFactory = function(isNgForm) {
  18516. return ['$timeout', '$parse', function($timeout, $parse) {
  18517. var formDirective = {
  18518. name: 'form',
  18519. restrict: isNgForm ? 'EAC' : 'E',
  18520. controller: FormController,
  18521. compile: function ngFormCompile(formElement, attr) {
  18522. // Setup initial state of the control
  18523. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  18524. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  18525. return {
  18526. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  18527. // if `action` attr is not present on the form, prevent the default action (submission)
  18528. if (!('action' in attr)) {
  18529. // we can't use jq events because if a form is destroyed during submission the default
  18530. // action is not prevented. see #1238
  18531. //
  18532. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  18533. // page reload if the form was destroyed by submission of the form via a click handler
  18534. // on a button in the form. Looks like an IE9 specific bug.
  18535. var handleFormSubmission = function(event) {
  18536. scope.$apply(function() {
  18537. controller.$commitViewValue();
  18538. controller.$setSubmitted();
  18539. });
  18540. event.preventDefault();
  18541. };
  18542. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18543. // unregister the preventDefault listener so that we don't not leak memory but in a
  18544. // way that will achieve the prevention of the default action.
  18545. formElement.on('$destroy', function() {
  18546. $timeout(function() {
  18547. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18548. }, 0, false);
  18549. });
  18550. }
  18551. var parentFormCtrl = controller.$$parentForm;
  18552. var setter = nameAttr ? getSetter(controller.$name) : noop;
  18553. if (nameAttr) {
  18554. setter(scope, controller);
  18555. attr.$observe(nameAttr, function(newValue) {
  18556. if (controller.$name === newValue) return;
  18557. setter(scope, undefined);
  18558. parentFormCtrl.$$renameControl(controller, newValue);
  18559. setter = getSetter(controller.$name);
  18560. setter(scope, controller);
  18561. });
  18562. }
  18563. formElement.on('$destroy', function() {
  18564. parentFormCtrl.$removeControl(controller);
  18565. setter(scope, undefined);
  18566. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  18567. });
  18568. }
  18569. };
  18570. }
  18571. };
  18572. return formDirective;
  18573. function getSetter(expression) {
  18574. if (expression === '') {
  18575. //create an assignable expression, so forms with an empty name can be renamed later
  18576. return $parse('this[""]').assign;
  18577. }
  18578. return $parse(expression).assign || noop;
  18579. }
  18580. }];
  18581. };
  18582. var formDirective = formDirectiveFactory();
  18583. var ngFormDirective = formDirectiveFactory(true);
  18584. /* global VALID_CLASS: false,
  18585. INVALID_CLASS: false,
  18586. PRISTINE_CLASS: false,
  18587. DIRTY_CLASS: false,
  18588. UNTOUCHED_CLASS: false,
  18589. TOUCHED_CLASS: false,
  18590. ngModelMinErr: false,
  18591. */
  18592. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  18593. var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
  18594. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  18595. var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
  18596. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  18597. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  18598. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18599. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  18600. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  18601. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18602. var inputType = {
  18603. /**
  18604. * @ngdoc input
  18605. * @name input[text]
  18606. *
  18607. * @description
  18608. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  18609. *
  18610. *
  18611. * @param {string} ngModel Assignable angular expression to data-bind to.
  18612. * @param {string=} name Property name of the form under which the control is published.
  18613. * @param {string=} required Adds `required` validation error key if the value is not entered.
  18614. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18615. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18616. * `required` when you want to data-bind to the `required` attribute.
  18617. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18618. * minlength.
  18619. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18620. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  18621. * any length.
  18622. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  18623. * that contains the regular expression body that will be converted to a regular expression
  18624. * as in the ngPattern directive.
  18625. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  18626. * a RegExp found by evaluating the Angular expression given in the attribute value.
  18627. * If the expression evaluates to a RegExp object, then this is used directly.
  18628. * If the expression evaluates to a string, then it will be converted to a RegExp
  18629. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  18630. * `new RegExp('^abc$')`.<br />
  18631. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  18632. * start at the index of the last search's match, thus not taking the whole input value into
  18633. * account.
  18634. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18635. * interaction with the input element.
  18636. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18637. * This parameter is ignored for input[type=password] controls, which will never trim the
  18638. * input.
  18639. *
  18640. * @example
  18641. <example name="text-input-directive" module="textInputExample">
  18642. <file name="index.html">
  18643. <script>
  18644. angular.module('textInputExample', [])
  18645. .controller('ExampleController', ['$scope', function($scope) {
  18646. $scope.example = {
  18647. text: 'guest',
  18648. word: /^\s*\w*\s*$/
  18649. };
  18650. }]);
  18651. </script>
  18652. <form name="myForm" ng-controller="ExampleController">
  18653. <label>Single word:
  18654. <input type="text" name="input" ng-model="example.text"
  18655. ng-pattern="example.word" required ng-trim="false">
  18656. </label>
  18657. <div role="alert">
  18658. <span class="error" ng-show="myForm.input.$error.required">
  18659. Required!</span>
  18660. <span class="error" ng-show="myForm.input.$error.pattern">
  18661. Single word only!</span>
  18662. </div>
  18663. <tt>text = {{example.text}}</tt><br/>
  18664. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18665. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18666. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18667. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18668. </form>
  18669. </file>
  18670. <file name="protractor.js" type="protractor">
  18671. var text = element(by.binding('example.text'));
  18672. var valid = element(by.binding('myForm.input.$valid'));
  18673. var input = element(by.model('example.text'));
  18674. it('should initialize to model', function() {
  18675. expect(text.getText()).toContain('guest');
  18676. expect(valid.getText()).toContain('true');
  18677. });
  18678. it('should be invalid if empty', function() {
  18679. input.clear();
  18680. input.sendKeys('');
  18681. expect(text.getText()).toEqual('text =');
  18682. expect(valid.getText()).toContain('false');
  18683. });
  18684. it('should be invalid if multi word', function() {
  18685. input.clear();
  18686. input.sendKeys('hello world');
  18687. expect(valid.getText()).toContain('false');
  18688. });
  18689. </file>
  18690. </example>
  18691. */
  18692. 'text': textInputType,
  18693. /**
  18694. * @ngdoc input
  18695. * @name input[date]
  18696. *
  18697. * @description
  18698. * Input with date validation and transformation. In browsers that do not yet support
  18699. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  18700. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  18701. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  18702. * expected input format via a placeholder or label.
  18703. *
  18704. * The model must always be a Date object, otherwise Angular will throw an error.
  18705. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18706. *
  18707. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18708. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18709. *
  18710. * @param {string} ngModel Assignable angular expression to data-bind to.
  18711. * @param {string=} name Property name of the form under which the control is published.
  18712. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18713. * valid ISO date string (yyyy-MM-dd).
  18714. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18715. * a valid ISO date string (yyyy-MM-dd).
  18716. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18717. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18718. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18719. * `required` when you want to data-bind to the `required` attribute.
  18720. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18721. * interaction with the input element.
  18722. *
  18723. * @example
  18724. <example name="date-input-directive" module="dateInputExample">
  18725. <file name="index.html">
  18726. <script>
  18727. angular.module('dateInputExample', [])
  18728. .controller('DateController', ['$scope', function($scope) {
  18729. $scope.example = {
  18730. value: new Date(2013, 9, 22)
  18731. };
  18732. }]);
  18733. </script>
  18734. <form name="myForm" ng-controller="DateController as dateCtrl">
  18735. <label for="exampleInput">Pick a date in 2013:</label>
  18736. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  18737. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  18738. <div role="alert">
  18739. <span class="error" ng-show="myForm.input.$error.required">
  18740. Required!</span>
  18741. <span class="error" ng-show="myForm.input.$error.date">
  18742. Not a valid date!</span>
  18743. </div>
  18744. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  18745. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18746. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18747. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18748. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18749. </form>
  18750. </file>
  18751. <file name="protractor.js" type="protractor">
  18752. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  18753. var valid = element(by.binding('myForm.input.$valid'));
  18754. var input = element(by.model('example.value'));
  18755. // currently protractor/webdriver does not support
  18756. // sending keys to all known HTML5 input controls
  18757. // for various browsers (see https://github.com/angular/protractor/issues/562).
  18758. function setInput(val) {
  18759. // set the value of the element and force validation.
  18760. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18761. "ipt.value = '" + val + "';" +
  18762. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18763. browser.executeScript(scr);
  18764. }
  18765. it('should initialize to model', function() {
  18766. expect(value.getText()).toContain('2013-10-22');
  18767. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18768. });
  18769. it('should be invalid if empty', function() {
  18770. setInput('');
  18771. expect(value.getText()).toEqual('value =');
  18772. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18773. });
  18774. it('should be invalid if over max', function() {
  18775. setInput('2015-01-01');
  18776. expect(value.getText()).toContain('');
  18777. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18778. });
  18779. </file>
  18780. </example>
  18781. */
  18782. 'date': createDateInputType('date', DATE_REGEXP,
  18783. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  18784. 'yyyy-MM-dd'),
  18785. /**
  18786. * @ngdoc input
  18787. * @name input[datetime-local]
  18788. *
  18789. * @description
  18790. * Input with datetime validation and transformation. In browsers that do not yet support
  18791. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18792. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  18793. *
  18794. * The model must always be a Date object, otherwise Angular will throw an error.
  18795. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18796. *
  18797. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18798. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18799. *
  18800. * @param {string} ngModel Assignable angular expression to data-bind to.
  18801. * @param {string=} name Property name of the form under which the control is published.
  18802. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18803. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  18804. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18805. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  18806. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18807. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18808. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18809. * `required` when you want to data-bind to the `required` attribute.
  18810. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18811. * interaction with the input element.
  18812. *
  18813. * @example
  18814. <example name="datetimelocal-input-directive" module="dateExample">
  18815. <file name="index.html">
  18816. <script>
  18817. angular.module('dateExample', [])
  18818. .controller('DateController', ['$scope', function($scope) {
  18819. $scope.example = {
  18820. value: new Date(2010, 11, 28, 14, 57)
  18821. };
  18822. }]);
  18823. </script>
  18824. <form name="myForm" ng-controller="DateController as dateCtrl">
  18825. <label for="exampleInput">Pick a date between in 2013:</label>
  18826. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  18827. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  18828. <div role="alert">
  18829. <span class="error" ng-show="myForm.input.$error.required">
  18830. Required!</span>
  18831. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  18832. Not a valid date!</span>
  18833. </div>
  18834. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  18835. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18836. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18837. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18838. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18839. </form>
  18840. </file>
  18841. <file name="protractor.js" type="protractor">
  18842. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  18843. var valid = element(by.binding('myForm.input.$valid'));
  18844. var input = element(by.model('example.value'));
  18845. // currently protractor/webdriver does not support
  18846. // sending keys to all known HTML5 input controls
  18847. // for various browsers (https://github.com/angular/protractor/issues/562).
  18848. function setInput(val) {
  18849. // set the value of the element and force validation.
  18850. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18851. "ipt.value = '" + val + "';" +
  18852. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18853. browser.executeScript(scr);
  18854. }
  18855. it('should initialize to model', function() {
  18856. expect(value.getText()).toContain('2010-12-28T14:57:00');
  18857. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18858. });
  18859. it('should be invalid if empty', function() {
  18860. setInput('');
  18861. expect(value.getText()).toEqual('value =');
  18862. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18863. });
  18864. it('should be invalid if over max', function() {
  18865. setInput('2015-01-01T23:59:00');
  18866. expect(value.getText()).toContain('');
  18867. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18868. });
  18869. </file>
  18870. </example>
  18871. */
  18872. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  18873. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  18874. 'yyyy-MM-ddTHH:mm:ss.sss'),
  18875. /**
  18876. * @ngdoc input
  18877. * @name input[time]
  18878. *
  18879. * @description
  18880. * Input with time validation and transformation. In browsers that do not yet support
  18881. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18882. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  18883. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  18884. *
  18885. * The model must always be a Date object, otherwise Angular will throw an error.
  18886. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18887. *
  18888. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18889. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18890. *
  18891. * @param {string} ngModel Assignable angular expression to data-bind to.
  18892. * @param {string=} name Property name of the form under which the control is published.
  18893. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18894. * valid ISO time format (HH:mm:ss).
  18895. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  18896. * valid ISO time format (HH:mm:ss).
  18897. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18898. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18899. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18900. * `required` when you want to data-bind to the `required` attribute.
  18901. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18902. * interaction with the input element.
  18903. *
  18904. * @example
  18905. <example name="time-input-directive" module="timeExample">
  18906. <file name="index.html">
  18907. <script>
  18908. angular.module('timeExample', [])
  18909. .controller('DateController', ['$scope', function($scope) {
  18910. $scope.example = {
  18911. value: new Date(1970, 0, 1, 14, 57, 0)
  18912. };
  18913. }]);
  18914. </script>
  18915. <form name="myForm" ng-controller="DateController as dateCtrl">
  18916. <label for="exampleInput">Pick a between 8am and 5pm:</label>
  18917. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  18918. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  18919. <div role="alert">
  18920. <span class="error" ng-show="myForm.input.$error.required">
  18921. Required!</span>
  18922. <span class="error" ng-show="myForm.input.$error.time">
  18923. Not a valid date!</span>
  18924. </div>
  18925. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  18926. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18927. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18928. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18929. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18930. </form>
  18931. </file>
  18932. <file name="protractor.js" type="protractor">
  18933. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  18934. var valid = element(by.binding('myForm.input.$valid'));
  18935. var input = element(by.model('example.value'));
  18936. // currently protractor/webdriver does not support
  18937. // sending keys to all known HTML5 input controls
  18938. // for various browsers (https://github.com/angular/protractor/issues/562).
  18939. function setInput(val) {
  18940. // set the value of the element and force validation.
  18941. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18942. "ipt.value = '" + val + "';" +
  18943. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18944. browser.executeScript(scr);
  18945. }
  18946. it('should initialize to model', function() {
  18947. expect(value.getText()).toContain('14:57:00');
  18948. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18949. });
  18950. it('should be invalid if empty', function() {
  18951. setInput('');
  18952. expect(value.getText()).toEqual('value =');
  18953. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18954. });
  18955. it('should be invalid if over max', function() {
  18956. setInput('23:59:00');
  18957. expect(value.getText()).toContain('');
  18958. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18959. });
  18960. </file>
  18961. </example>
  18962. */
  18963. 'time': createDateInputType('time', TIME_REGEXP,
  18964. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  18965. 'HH:mm:ss.sss'),
  18966. /**
  18967. * @ngdoc input
  18968. * @name input[week]
  18969. *
  18970. * @description
  18971. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  18972. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18973. * week format (yyyy-W##), for example: `2013-W02`.
  18974. *
  18975. * The model must always be a Date object, otherwise Angular will throw an error.
  18976. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18977. *
  18978. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18979. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18980. *
  18981. * @param {string} ngModel Assignable angular expression to data-bind to.
  18982. * @param {string=} name Property name of the form under which the control is published.
  18983. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18984. * valid ISO week format (yyyy-W##).
  18985. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18986. * a valid ISO week format (yyyy-W##).
  18987. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18988. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18989. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18990. * `required` when you want to data-bind to the `required` attribute.
  18991. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18992. * interaction with the input element.
  18993. *
  18994. * @example
  18995. <example name="week-input-directive" module="weekExample">
  18996. <file name="index.html">
  18997. <script>
  18998. angular.module('weekExample', [])
  18999. .controller('DateController', ['$scope', function($scope) {
  19000. $scope.example = {
  19001. value: new Date(2013, 0, 3)
  19002. };
  19003. }]);
  19004. </script>
  19005. <form name="myForm" ng-controller="DateController as dateCtrl">
  19006. <label>Pick a date between in 2013:
  19007. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  19008. placeholder="YYYY-W##" min="2012-W32"
  19009. max="2013-W52" required />
  19010. </label>
  19011. <div role="alert">
  19012. <span class="error" ng-show="myForm.input.$error.required">
  19013. Required!</span>
  19014. <span class="error" ng-show="myForm.input.$error.week">
  19015. Not a valid date!</span>
  19016. </div>
  19017. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  19018. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19019. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19020. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19021. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19022. </form>
  19023. </file>
  19024. <file name="protractor.js" type="protractor">
  19025. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  19026. var valid = element(by.binding('myForm.input.$valid'));
  19027. var input = element(by.model('example.value'));
  19028. // currently protractor/webdriver does not support
  19029. // sending keys to all known HTML5 input controls
  19030. // for various browsers (https://github.com/angular/protractor/issues/562).
  19031. function setInput(val) {
  19032. // set the value of the element and force validation.
  19033. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19034. "ipt.value = '" + val + "';" +
  19035. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19036. browser.executeScript(scr);
  19037. }
  19038. it('should initialize to model', function() {
  19039. expect(value.getText()).toContain('2013-W01');
  19040. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19041. });
  19042. it('should be invalid if empty', function() {
  19043. setInput('');
  19044. expect(value.getText()).toEqual('value =');
  19045. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19046. });
  19047. it('should be invalid if over max', function() {
  19048. setInput('2015-W01');
  19049. expect(value.getText()).toContain('');
  19050. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19051. });
  19052. </file>
  19053. </example>
  19054. */
  19055. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  19056. /**
  19057. * @ngdoc input
  19058. * @name input[month]
  19059. *
  19060. * @description
  19061. * Input with month validation and transformation. In browsers that do not yet support
  19062. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19063. * month format (yyyy-MM), for example: `2009-01`.
  19064. *
  19065. * The model must always be a Date object, otherwise Angular will throw an error.
  19066. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19067. * If the model is not set to the first of the month, the next view to model update will set it
  19068. * to the first of the month.
  19069. *
  19070. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19071. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19072. *
  19073. * @param {string} ngModel Assignable angular expression to data-bind to.
  19074. * @param {string=} name Property name of the form under which the control is published.
  19075. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  19076. * a valid ISO month format (yyyy-MM).
  19077. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  19078. * be a valid ISO month format (yyyy-MM).
  19079. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19080. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19081. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19082. * `required` when you want to data-bind to the `required` attribute.
  19083. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19084. * interaction with the input element.
  19085. *
  19086. * @example
  19087. <example name="month-input-directive" module="monthExample">
  19088. <file name="index.html">
  19089. <script>
  19090. angular.module('monthExample', [])
  19091. .controller('DateController', ['$scope', function($scope) {
  19092. $scope.example = {
  19093. value: new Date(2013, 9, 1)
  19094. };
  19095. }]);
  19096. </script>
  19097. <form name="myForm" ng-controller="DateController as dateCtrl">
  19098. <label for="exampleInput">Pick a month in 2013:</label>
  19099. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  19100. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  19101. <div role="alert">
  19102. <span class="error" ng-show="myForm.input.$error.required">
  19103. Required!</span>
  19104. <span class="error" ng-show="myForm.input.$error.month">
  19105. Not a valid month!</span>
  19106. </div>
  19107. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  19108. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19109. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19110. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19111. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19112. </form>
  19113. </file>
  19114. <file name="protractor.js" type="protractor">
  19115. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  19116. var valid = element(by.binding('myForm.input.$valid'));
  19117. var input = element(by.model('example.value'));
  19118. // currently protractor/webdriver does not support
  19119. // sending keys to all known HTML5 input controls
  19120. // for various browsers (https://github.com/angular/protractor/issues/562).
  19121. function setInput(val) {
  19122. // set the value of the element and force validation.
  19123. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19124. "ipt.value = '" + val + "';" +
  19125. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19126. browser.executeScript(scr);
  19127. }
  19128. it('should initialize to model', function() {
  19129. expect(value.getText()).toContain('2013-10');
  19130. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19131. });
  19132. it('should be invalid if empty', function() {
  19133. setInput('');
  19134. expect(value.getText()).toEqual('value =');
  19135. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19136. });
  19137. it('should be invalid if over max', function() {
  19138. setInput('2015-01');
  19139. expect(value.getText()).toContain('');
  19140. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19141. });
  19142. </file>
  19143. </example>
  19144. */
  19145. 'month': createDateInputType('month', MONTH_REGEXP,
  19146. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  19147. 'yyyy-MM'),
  19148. /**
  19149. * @ngdoc input
  19150. * @name input[number]
  19151. *
  19152. * @description
  19153. * Text input with number validation and transformation. Sets the `number` validation
  19154. * error if not a valid number.
  19155. *
  19156. * <div class="alert alert-warning">
  19157. * The model must always be of type `number` otherwise Angular will throw an error.
  19158. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  19159. * error docs for more information and an example of how to convert your model if necessary.
  19160. * </div>
  19161. *
  19162. * ## Issues with HTML5 constraint validation
  19163. *
  19164. * In browsers that follow the
  19165. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  19166. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  19167. * If a non-number is entered in the input, the browser will report the value as an empty string,
  19168. * which means the view / model values in `ngModel` and subsequently the scope value
  19169. * will also be an empty string.
  19170. *
  19171. *
  19172. * @param {string} ngModel Assignable angular expression to data-bind to.
  19173. * @param {string=} name Property name of the form under which the control is published.
  19174. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19175. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19176. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19177. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19178. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19179. * `required` when you want to data-bind to the `required` attribute.
  19180. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19181. * minlength.
  19182. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19183. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19184. * any length.
  19185. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19186. * that contains the regular expression body that will be converted to a regular expression
  19187. * as in the ngPattern directive.
  19188. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19189. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19190. * If the expression evaluates to a RegExp object, then this is used directly.
  19191. * If the expression evaluates to a string, then it will be converted to a RegExp
  19192. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19193. * `new RegExp('^abc$')`.<br />
  19194. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19195. * start at the index of the last search's match, thus not taking the whole input value into
  19196. * account.
  19197. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19198. * interaction with the input element.
  19199. *
  19200. * @example
  19201. <example name="number-input-directive" module="numberExample">
  19202. <file name="index.html">
  19203. <script>
  19204. angular.module('numberExample', [])
  19205. .controller('ExampleController', ['$scope', function($scope) {
  19206. $scope.example = {
  19207. value: 12
  19208. };
  19209. }]);
  19210. </script>
  19211. <form name="myForm" ng-controller="ExampleController">
  19212. <label>Number:
  19213. <input type="number" name="input" ng-model="example.value"
  19214. min="0" max="99" required>
  19215. </label>
  19216. <div role="alert">
  19217. <span class="error" ng-show="myForm.input.$error.required">
  19218. Required!</span>
  19219. <span class="error" ng-show="myForm.input.$error.number">
  19220. Not valid number!</span>
  19221. </div>
  19222. <tt>value = {{example.value}}</tt><br/>
  19223. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19224. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19225. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19226. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19227. </form>
  19228. </file>
  19229. <file name="protractor.js" type="protractor">
  19230. var value = element(by.binding('example.value'));
  19231. var valid = element(by.binding('myForm.input.$valid'));
  19232. var input = element(by.model('example.value'));
  19233. it('should initialize to model', function() {
  19234. expect(value.getText()).toContain('12');
  19235. expect(valid.getText()).toContain('true');
  19236. });
  19237. it('should be invalid if empty', function() {
  19238. input.clear();
  19239. input.sendKeys('');
  19240. expect(value.getText()).toEqual('value =');
  19241. expect(valid.getText()).toContain('false');
  19242. });
  19243. it('should be invalid if over max', function() {
  19244. input.clear();
  19245. input.sendKeys('123');
  19246. expect(value.getText()).toEqual('value =');
  19247. expect(valid.getText()).toContain('false');
  19248. });
  19249. </file>
  19250. </example>
  19251. */
  19252. 'number': numberInputType,
  19253. /**
  19254. * @ngdoc input
  19255. * @name input[url]
  19256. *
  19257. * @description
  19258. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  19259. * valid URL.
  19260. *
  19261. * <div class="alert alert-warning">
  19262. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  19263. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  19264. * the built-in validators (see the {@link guide/forms Forms guide})
  19265. * </div>
  19266. *
  19267. * @param {string} ngModel Assignable angular expression to data-bind to.
  19268. * @param {string=} name Property name of the form under which the control is published.
  19269. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19270. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19271. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19272. * `required` when you want to data-bind to the `required` attribute.
  19273. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19274. * minlength.
  19275. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19276. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19277. * any length.
  19278. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19279. * that contains the regular expression body that will be converted to a regular expression
  19280. * as in the ngPattern directive.
  19281. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19282. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19283. * If the expression evaluates to a RegExp object, then this is used directly.
  19284. * If the expression evaluates to a string, then it will be converted to a RegExp
  19285. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19286. * `new RegExp('^abc$')`.<br />
  19287. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19288. * start at the index of the last search's match, thus not taking the whole input value into
  19289. * account.
  19290. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19291. * interaction with the input element.
  19292. *
  19293. * @example
  19294. <example name="url-input-directive" module="urlExample">
  19295. <file name="index.html">
  19296. <script>
  19297. angular.module('urlExample', [])
  19298. .controller('ExampleController', ['$scope', function($scope) {
  19299. $scope.url = {
  19300. text: 'http://google.com'
  19301. };
  19302. }]);
  19303. </script>
  19304. <form name="myForm" ng-controller="ExampleController">
  19305. <label>URL:
  19306. <input type="url" name="input" ng-model="url.text" required>
  19307. <label>
  19308. <div role="alert">
  19309. <span class="error" ng-show="myForm.input.$error.required">
  19310. Required!</span>
  19311. <span class="error" ng-show="myForm.input.$error.url">
  19312. Not valid url!</span>
  19313. </div>
  19314. <tt>text = {{url.text}}</tt><br/>
  19315. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19316. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19317. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19318. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19319. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  19320. </form>
  19321. </file>
  19322. <file name="protractor.js" type="protractor">
  19323. var text = element(by.binding('url.text'));
  19324. var valid = element(by.binding('myForm.input.$valid'));
  19325. var input = element(by.model('url.text'));
  19326. it('should initialize to model', function() {
  19327. expect(text.getText()).toContain('http://google.com');
  19328. expect(valid.getText()).toContain('true');
  19329. });
  19330. it('should be invalid if empty', function() {
  19331. input.clear();
  19332. input.sendKeys('');
  19333. expect(text.getText()).toEqual('text =');
  19334. expect(valid.getText()).toContain('false');
  19335. });
  19336. it('should be invalid if not url', function() {
  19337. input.clear();
  19338. input.sendKeys('box');
  19339. expect(valid.getText()).toContain('false');
  19340. });
  19341. </file>
  19342. </example>
  19343. */
  19344. 'url': urlInputType,
  19345. /**
  19346. * @ngdoc input
  19347. * @name input[email]
  19348. *
  19349. * @description
  19350. * Text input with email validation. Sets the `email` validation error key if not a valid email
  19351. * address.
  19352. *
  19353. * <div class="alert alert-warning">
  19354. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  19355. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  19356. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  19357. * </div>
  19358. *
  19359. * @param {string} ngModel Assignable angular expression to data-bind to.
  19360. * @param {string=} name Property name of the form under which the control is published.
  19361. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19362. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19363. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19364. * `required` when you want to data-bind to the `required` attribute.
  19365. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19366. * minlength.
  19367. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19368. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19369. * any length.
  19370. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19371. * that contains the regular expression body that will be converted to a regular expression
  19372. * as in the ngPattern directive.
  19373. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19374. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19375. * If the expression evaluates to a RegExp object, then this is used directly.
  19376. * If the expression evaluates to a string, then it will be converted to a RegExp
  19377. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19378. * `new RegExp('^abc$')`.<br />
  19379. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19380. * start at the index of the last search's match, thus not taking the whole input value into
  19381. * account.
  19382. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19383. * interaction with the input element.
  19384. *
  19385. * @example
  19386. <example name="email-input-directive" module="emailExample">
  19387. <file name="index.html">
  19388. <script>
  19389. angular.module('emailExample', [])
  19390. .controller('ExampleController', ['$scope', function($scope) {
  19391. $scope.email = {
  19392. text: 'me@example.com'
  19393. };
  19394. }]);
  19395. </script>
  19396. <form name="myForm" ng-controller="ExampleController">
  19397. <label>Email:
  19398. <input type="email" name="input" ng-model="email.text" required>
  19399. </label>
  19400. <div role="alert">
  19401. <span class="error" ng-show="myForm.input.$error.required">
  19402. Required!</span>
  19403. <span class="error" ng-show="myForm.input.$error.email">
  19404. Not valid email!</span>
  19405. </div>
  19406. <tt>text = {{email.text}}</tt><br/>
  19407. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19408. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19409. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19410. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19411. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  19412. </form>
  19413. </file>
  19414. <file name="protractor.js" type="protractor">
  19415. var text = element(by.binding('email.text'));
  19416. var valid = element(by.binding('myForm.input.$valid'));
  19417. var input = element(by.model('email.text'));
  19418. it('should initialize to model', function() {
  19419. expect(text.getText()).toContain('me@example.com');
  19420. expect(valid.getText()).toContain('true');
  19421. });
  19422. it('should be invalid if empty', function() {
  19423. input.clear();
  19424. input.sendKeys('');
  19425. expect(text.getText()).toEqual('text =');
  19426. expect(valid.getText()).toContain('false');
  19427. });
  19428. it('should be invalid if not email', function() {
  19429. input.clear();
  19430. input.sendKeys('xxx');
  19431. expect(valid.getText()).toContain('false');
  19432. });
  19433. </file>
  19434. </example>
  19435. */
  19436. 'email': emailInputType,
  19437. /**
  19438. * @ngdoc input
  19439. * @name input[radio]
  19440. *
  19441. * @description
  19442. * HTML radio button.
  19443. *
  19444. * @param {string} ngModel Assignable angular expression to data-bind to.
  19445. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  19446. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  19447. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  19448. * @param {string=} name Property name of the form under which the control is published.
  19449. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19450. * interaction with the input element.
  19451. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  19452. * is selected. Should be used instead of the `value` attribute if you need
  19453. * a non-string `ngModel` (`boolean`, `array`, ...).
  19454. *
  19455. * @example
  19456. <example name="radio-input-directive" module="radioExample">
  19457. <file name="index.html">
  19458. <script>
  19459. angular.module('radioExample', [])
  19460. .controller('ExampleController', ['$scope', function($scope) {
  19461. $scope.color = {
  19462. name: 'blue'
  19463. };
  19464. $scope.specialValue = {
  19465. "id": "12345",
  19466. "value": "green"
  19467. };
  19468. }]);
  19469. </script>
  19470. <form name="myForm" ng-controller="ExampleController">
  19471. <label>
  19472. <input type="radio" ng-model="color.name" value="red">
  19473. Red
  19474. </label><br/>
  19475. <label>
  19476. <input type="radio" ng-model="color.name" ng-value="specialValue">
  19477. Green
  19478. </label><br/>
  19479. <label>
  19480. <input type="radio" ng-model="color.name" value="blue">
  19481. Blue
  19482. </label><br/>
  19483. <tt>color = {{color.name | json}}</tt><br/>
  19484. </form>
  19485. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  19486. </file>
  19487. <file name="protractor.js" type="protractor">
  19488. it('should change state', function() {
  19489. var color = element(by.binding('color.name'));
  19490. expect(color.getText()).toContain('blue');
  19491. element.all(by.model('color.name')).get(0).click();
  19492. expect(color.getText()).toContain('red');
  19493. });
  19494. </file>
  19495. </example>
  19496. */
  19497. 'radio': radioInputType,
  19498. /**
  19499. * @ngdoc input
  19500. * @name input[checkbox]
  19501. *
  19502. * @description
  19503. * HTML checkbox.
  19504. *
  19505. * @param {string} ngModel Assignable angular expression to data-bind to.
  19506. * @param {string=} name Property name of the form under which the control is published.
  19507. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  19508. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  19509. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19510. * interaction with the input element.
  19511. *
  19512. * @example
  19513. <example name="checkbox-input-directive" module="checkboxExample">
  19514. <file name="index.html">
  19515. <script>
  19516. angular.module('checkboxExample', [])
  19517. .controller('ExampleController', ['$scope', function($scope) {
  19518. $scope.checkboxModel = {
  19519. value1 : true,
  19520. value2 : 'YES'
  19521. };
  19522. }]);
  19523. </script>
  19524. <form name="myForm" ng-controller="ExampleController">
  19525. <label>Value1:
  19526. <input type="checkbox" ng-model="checkboxModel.value1">
  19527. </label><br/>
  19528. <label>Value2:
  19529. <input type="checkbox" ng-model="checkboxModel.value2"
  19530. ng-true-value="'YES'" ng-false-value="'NO'">
  19531. </label><br/>
  19532. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  19533. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  19534. </form>
  19535. </file>
  19536. <file name="protractor.js" type="protractor">
  19537. it('should change state', function() {
  19538. var value1 = element(by.binding('checkboxModel.value1'));
  19539. var value2 = element(by.binding('checkboxModel.value2'));
  19540. expect(value1.getText()).toContain('true');
  19541. expect(value2.getText()).toContain('YES');
  19542. element(by.model('checkboxModel.value1')).click();
  19543. element(by.model('checkboxModel.value2')).click();
  19544. expect(value1.getText()).toContain('false');
  19545. expect(value2.getText()).toContain('NO');
  19546. });
  19547. </file>
  19548. </example>
  19549. */
  19550. 'checkbox': checkboxInputType,
  19551. 'hidden': noop,
  19552. 'button': noop,
  19553. 'submit': noop,
  19554. 'reset': noop,
  19555. 'file': noop
  19556. };
  19557. function stringBasedInputType(ctrl) {
  19558. ctrl.$formatters.push(function(value) {
  19559. return ctrl.$isEmpty(value) ? value : value.toString();
  19560. });
  19561. }
  19562. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19563. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19564. stringBasedInputType(ctrl);
  19565. }
  19566. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19567. var type = lowercase(element[0].type);
  19568. // In composition mode, users are still inputing intermediate text buffer,
  19569. // hold the listener until composition is done.
  19570. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  19571. if (!$sniffer.android) {
  19572. var composing = false;
  19573. element.on('compositionstart', function(data) {
  19574. composing = true;
  19575. });
  19576. element.on('compositionend', function() {
  19577. composing = false;
  19578. listener();
  19579. });
  19580. }
  19581. var listener = function(ev) {
  19582. if (timeout) {
  19583. $browser.defer.cancel(timeout);
  19584. timeout = null;
  19585. }
  19586. if (composing) return;
  19587. var value = element.val(),
  19588. event = ev && ev.type;
  19589. // By default we will trim the value
  19590. // If the attribute ng-trim exists we will avoid trimming
  19591. // If input type is 'password', the value is never trimmed
  19592. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  19593. value = trim(value);
  19594. }
  19595. // If a control is suffering from bad input (due to native validators), browsers discard its
  19596. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  19597. // control's value is the same empty value twice in a row.
  19598. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  19599. ctrl.$setViewValue(value, event);
  19600. }
  19601. };
  19602. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  19603. // input event on backspace, delete or cut
  19604. if ($sniffer.hasEvent('input')) {
  19605. element.on('input', listener);
  19606. } else {
  19607. var timeout;
  19608. var deferListener = function(ev, input, origValue) {
  19609. if (!timeout) {
  19610. timeout = $browser.defer(function() {
  19611. timeout = null;
  19612. if (!input || input.value !== origValue) {
  19613. listener(ev);
  19614. }
  19615. });
  19616. }
  19617. };
  19618. element.on('keydown', function(event) {
  19619. var key = event.keyCode;
  19620. // ignore
  19621. // command modifiers arrows
  19622. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  19623. deferListener(event, this, this.value);
  19624. });
  19625. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  19626. if ($sniffer.hasEvent('paste')) {
  19627. element.on('paste cut', deferListener);
  19628. }
  19629. }
  19630. // if user paste into input using mouse on older browser
  19631. // or form autocomplete on newer browser, we need "change" event to catch it
  19632. element.on('change', listener);
  19633. ctrl.$render = function() {
  19634. // Workaround for Firefox validation #12102.
  19635. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  19636. if (element.val() !== value) {
  19637. element.val(value);
  19638. }
  19639. };
  19640. }
  19641. function weekParser(isoWeek, existingDate) {
  19642. if (isDate(isoWeek)) {
  19643. return isoWeek;
  19644. }
  19645. if (isString(isoWeek)) {
  19646. WEEK_REGEXP.lastIndex = 0;
  19647. var parts = WEEK_REGEXP.exec(isoWeek);
  19648. if (parts) {
  19649. var year = +parts[1],
  19650. week = +parts[2],
  19651. hours = 0,
  19652. minutes = 0,
  19653. seconds = 0,
  19654. milliseconds = 0,
  19655. firstThurs = getFirstThursdayOfYear(year),
  19656. addDays = (week - 1) * 7;
  19657. if (existingDate) {
  19658. hours = existingDate.getHours();
  19659. minutes = existingDate.getMinutes();
  19660. seconds = existingDate.getSeconds();
  19661. milliseconds = existingDate.getMilliseconds();
  19662. }
  19663. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  19664. }
  19665. }
  19666. return NaN;
  19667. }
  19668. function createDateParser(regexp, mapping) {
  19669. return function(iso, date) {
  19670. var parts, map;
  19671. if (isDate(iso)) {
  19672. return iso;
  19673. }
  19674. if (isString(iso)) {
  19675. // When a date is JSON'ified to wraps itself inside of an extra
  19676. // set of double quotes. This makes the date parsing code unable
  19677. // to match the date string and parse it as a date.
  19678. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  19679. iso = iso.substring(1, iso.length - 1);
  19680. }
  19681. if (ISO_DATE_REGEXP.test(iso)) {
  19682. return new Date(iso);
  19683. }
  19684. regexp.lastIndex = 0;
  19685. parts = regexp.exec(iso);
  19686. if (parts) {
  19687. parts.shift();
  19688. if (date) {
  19689. map = {
  19690. yyyy: date.getFullYear(),
  19691. MM: date.getMonth() + 1,
  19692. dd: date.getDate(),
  19693. HH: date.getHours(),
  19694. mm: date.getMinutes(),
  19695. ss: date.getSeconds(),
  19696. sss: date.getMilliseconds() / 1000
  19697. };
  19698. } else {
  19699. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  19700. }
  19701. forEach(parts, function(part, index) {
  19702. if (index < mapping.length) {
  19703. map[mapping[index]] = +part;
  19704. }
  19705. });
  19706. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  19707. }
  19708. }
  19709. return NaN;
  19710. };
  19711. }
  19712. function createDateInputType(type, regexp, parseDate, format) {
  19713. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  19714. badInputChecker(scope, element, attr, ctrl);
  19715. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19716. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  19717. var previousDate;
  19718. ctrl.$$parserName = type;
  19719. ctrl.$parsers.push(function(value) {
  19720. if (ctrl.$isEmpty(value)) return null;
  19721. if (regexp.test(value)) {
  19722. // Note: We cannot read ctrl.$modelValue, as there might be a different
  19723. // parser/formatter in the processing chain so that the model
  19724. // contains some different data format!
  19725. var parsedDate = parseDate(value, previousDate);
  19726. if (timezone) {
  19727. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  19728. }
  19729. return parsedDate;
  19730. }
  19731. return undefined;
  19732. });
  19733. ctrl.$formatters.push(function(value) {
  19734. if (value && !isDate(value)) {
  19735. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  19736. }
  19737. if (isValidDate(value)) {
  19738. previousDate = value;
  19739. if (previousDate && timezone) {
  19740. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  19741. }
  19742. return $filter('date')(value, format, timezone);
  19743. } else {
  19744. previousDate = null;
  19745. return '';
  19746. }
  19747. });
  19748. if (isDefined(attr.min) || attr.ngMin) {
  19749. var minVal;
  19750. ctrl.$validators.min = function(value) {
  19751. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  19752. };
  19753. attr.$observe('min', function(val) {
  19754. minVal = parseObservedDateValue(val);
  19755. ctrl.$validate();
  19756. });
  19757. }
  19758. if (isDefined(attr.max) || attr.ngMax) {
  19759. var maxVal;
  19760. ctrl.$validators.max = function(value) {
  19761. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  19762. };
  19763. attr.$observe('max', function(val) {
  19764. maxVal = parseObservedDateValue(val);
  19765. ctrl.$validate();
  19766. });
  19767. }
  19768. function isValidDate(value) {
  19769. // Invalid Date: getTime() returns NaN
  19770. return value && !(value.getTime && value.getTime() !== value.getTime());
  19771. }
  19772. function parseObservedDateValue(val) {
  19773. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  19774. }
  19775. };
  19776. }
  19777. function badInputChecker(scope, element, attr, ctrl) {
  19778. var node = element[0];
  19779. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  19780. if (nativeValidation) {
  19781. ctrl.$parsers.push(function(value) {
  19782. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  19783. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  19784. // - also sets validity.badInput (should only be validity.typeMismatch).
  19785. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  19786. // - can ignore this case as we can still read out the erroneous email...
  19787. return validity.badInput && !validity.typeMismatch ? undefined : value;
  19788. });
  19789. }
  19790. }
  19791. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19792. badInputChecker(scope, element, attr, ctrl);
  19793. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19794. ctrl.$$parserName = 'number';
  19795. ctrl.$parsers.push(function(value) {
  19796. if (ctrl.$isEmpty(value)) return null;
  19797. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  19798. return undefined;
  19799. });
  19800. ctrl.$formatters.push(function(value) {
  19801. if (!ctrl.$isEmpty(value)) {
  19802. if (!isNumber(value)) {
  19803. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  19804. }
  19805. value = value.toString();
  19806. }
  19807. return value;
  19808. });
  19809. if (isDefined(attr.min) || attr.ngMin) {
  19810. var minVal;
  19811. ctrl.$validators.min = function(value) {
  19812. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  19813. };
  19814. attr.$observe('min', function(val) {
  19815. if (isDefined(val) && !isNumber(val)) {
  19816. val = parseFloat(val, 10);
  19817. }
  19818. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19819. // TODO(matsko): implement validateLater to reduce number of validations
  19820. ctrl.$validate();
  19821. });
  19822. }
  19823. if (isDefined(attr.max) || attr.ngMax) {
  19824. var maxVal;
  19825. ctrl.$validators.max = function(value) {
  19826. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  19827. };
  19828. attr.$observe('max', function(val) {
  19829. if (isDefined(val) && !isNumber(val)) {
  19830. val = parseFloat(val, 10);
  19831. }
  19832. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19833. // TODO(matsko): implement validateLater to reduce number of validations
  19834. ctrl.$validate();
  19835. });
  19836. }
  19837. }
  19838. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19839. // Note: no badInputChecker here by purpose as `url` is only a validation
  19840. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19841. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19842. stringBasedInputType(ctrl);
  19843. ctrl.$$parserName = 'url';
  19844. ctrl.$validators.url = function(modelValue, viewValue) {
  19845. var value = modelValue || viewValue;
  19846. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  19847. };
  19848. }
  19849. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19850. // Note: no badInputChecker here by purpose as `url` is only a validation
  19851. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19852. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19853. stringBasedInputType(ctrl);
  19854. ctrl.$$parserName = 'email';
  19855. ctrl.$validators.email = function(modelValue, viewValue) {
  19856. var value = modelValue || viewValue;
  19857. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  19858. };
  19859. }
  19860. function radioInputType(scope, element, attr, ctrl) {
  19861. // make the name unique, if not defined
  19862. if (isUndefined(attr.name)) {
  19863. element.attr('name', nextUid());
  19864. }
  19865. var listener = function(ev) {
  19866. if (element[0].checked) {
  19867. ctrl.$setViewValue(attr.value, ev && ev.type);
  19868. }
  19869. };
  19870. element.on('click', listener);
  19871. ctrl.$render = function() {
  19872. var value = attr.value;
  19873. element[0].checked = (value == ctrl.$viewValue);
  19874. };
  19875. attr.$observe('value', ctrl.$render);
  19876. }
  19877. function parseConstantExpr($parse, context, name, expression, fallback) {
  19878. var parseFn;
  19879. if (isDefined(expression)) {
  19880. parseFn = $parse(expression);
  19881. if (!parseFn.constant) {
  19882. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  19883. '`{1}`.', name, expression);
  19884. }
  19885. return parseFn(context);
  19886. }
  19887. return fallback;
  19888. }
  19889. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  19890. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  19891. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  19892. var listener = function(ev) {
  19893. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  19894. };
  19895. element.on('click', listener);
  19896. ctrl.$render = function() {
  19897. element[0].checked = ctrl.$viewValue;
  19898. };
  19899. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  19900. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  19901. // it to a boolean.
  19902. ctrl.$isEmpty = function(value) {
  19903. return value === false;
  19904. };
  19905. ctrl.$formatters.push(function(value) {
  19906. return equals(value, trueValue);
  19907. });
  19908. ctrl.$parsers.push(function(value) {
  19909. return value ? trueValue : falseValue;
  19910. });
  19911. }
  19912. /**
  19913. * @ngdoc directive
  19914. * @name textarea
  19915. * @restrict E
  19916. *
  19917. * @description
  19918. * HTML textarea element control with angular data-binding. The data-binding and validation
  19919. * properties of this element are exactly the same as those of the
  19920. * {@link ng.directive:input input element}.
  19921. *
  19922. * @param {string} ngModel Assignable angular expression to data-bind to.
  19923. * @param {string=} name Property name of the form under which the control is published.
  19924. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19925. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19926. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19927. * `required` when you want to data-bind to the `required` attribute.
  19928. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19929. * minlength.
  19930. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19931. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  19932. * length.
  19933. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19934. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19935. * If the expression evaluates to a RegExp object, then this is used directly.
  19936. * If the expression evaluates to a string, then it will be converted to a RegExp
  19937. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19938. * `new RegExp('^abc$')`.<br />
  19939. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19940. * start at the index of the last search's match, thus not taking the whole input value into
  19941. * account.
  19942. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19943. * interaction with the input element.
  19944. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19945. */
  19946. /**
  19947. * @ngdoc directive
  19948. * @name input
  19949. * @restrict E
  19950. *
  19951. * @description
  19952. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  19953. * input state control, and validation.
  19954. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  19955. *
  19956. * <div class="alert alert-warning">
  19957. * **Note:** Not every feature offered is available for all input types.
  19958. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  19959. * </div>
  19960. *
  19961. * @param {string} ngModel Assignable angular expression to data-bind to.
  19962. * @param {string=} name Property name of the form under which the control is published.
  19963. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19964. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  19965. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19966. * minlength.
  19967. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19968. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  19969. * length.
  19970. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19971. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19972. * If the expression evaluates to a RegExp object, then this is used directly.
  19973. * If the expression evaluates to a string, then it will be converted to a RegExp
  19974. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19975. * `new RegExp('^abc$')`.<br />
  19976. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19977. * start at the index of the last search's match, thus not taking the whole input value into
  19978. * account.
  19979. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19980. * interaction with the input element.
  19981. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19982. * This parameter is ignored for input[type=password] controls, which will never trim the
  19983. * input.
  19984. *
  19985. * @example
  19986. <example name="input-directive" module="inputExample">
  19987. <file name="index.html">
  19988. <script>
  19989. angular.module('inputExample', [])
  19990. .controller('ExampleController', ['$scope', function($scope) {
  19991. $scope.user = {name: 'guest', last: 'visitor'};
  19992. }]);
  19993. </script>
  19994. <div ng-controller="ExampleController">
  19995. <form name="myForm">
  19996. <label>
  19997. User name:
  19998. <input type="text" name="userName" ng-model="user.name" required>
  19999. </label>
  20000. <div role="alert">
  20001. <span class="error" ng-show="myForm.userName.$error.required">
  20002. Required!</span>
  20003. </div>
  20004. <label>
  20005. Last name:
  20006. <input type="text" name="lastName" ng-model="user.last"
  20007. ng-minlength="3" ng-maxlength="10">
  20008. </label>
  20009. <div role="alert">
  20010. <span class="error" ng-show="myForm.lastName.$error.minlength">
  20011. Too short!</span>
  20012. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  20013. Too long!</span>
  20014. </div>
  20015. </form>
  20016. <hr>
  20017. <tt>user = {{user}}</tt><br/>
  20018. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  20019. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  20020. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  20021. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  20022. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20023. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20024. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  20025. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  20026. </div>
  20027. </file>
  20028. <file name="protractor.js" type="protractor">
  20029. var user = element(by.exactBinding('user'));
  20030. var userNameValid = element(by.binding('myForm.userName.$valid'));
  20031. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  20032. var lastNameError = element(by.binding('myForm.lastName.$error'));
  20033. var formValid = element(by.binding('myForm.$valid'));
  20034. var userNameInput = element(by.model('user.name'));
  20035. var userLastInput = element(by.model('user.last'));
  20036. it('should initialize to model', function() {
  20037. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  20038. expect(userNameValid.getText()).toContain('true');
  20039. expect(formValid.getText()).toContain('true');
  20040. });
  20041. it('should be invalid if empty when required', function() {
  20042. userNameInput.clear();
  20043. userNameInput.sendKeys('');
  20044. expect(user.getText()).toContain('{"last":"visitor"}');
  20045. expect(userNameValid.getText()).toContain('false');
  20046. expect(formValid.getText()).toContain('false');
  20047. });
  20048. it('should be valid if empty when min length is set', function() {
  20049. userLastInput.clear();
  20050. userLastInput.sendKeys('');
  20051. expect(user.getText()).toContain('{"name":"guest","last":""}');
  20052. expect(lastNameValid.getText()).toContain('true');
  20053. expect(formValid.getText()).toContain('true');
  20054. });
  20055. it('should be invalid if less than required min length', function() {
  20056. userLastInput.clear();
  20057. userLastInput.sendKeys('xx');
  20058. expect(user.getText()).toContain('{"name":"guest"}');
  20059. expect(lastNameValid.getText()).toContain('false');
  20060. expect(lastNameError.getText()).toContain('minlength');
  20061. expect(formValid.getText()).toContain('false');
  20062. });
  20063. it('should be invalid if longer than max length', function() {
  20064. userLastInput.clear();
  20065. userLastInput.sendKeys('some ridiculously long name');
  20066. expect(user.getText()).toContain('{"name":"guest"}');
  20067. expect(lastNameValid.getText()).toContain('false');
  20068. expect(lastNameError.getText()).toContain('maxlength');
  20069. expect(formValid.getText()).toContain('false');
  20070. });
  20071. </file>
  20072. </example>
  20073. */
  20074. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  20075. function($browser, $sniffer, $filter, $parse) {
  20076. return {
  20077. restrict: 'E',
  20078. require: ['?ngModel'],
  20079. link: {
  20080. pre: function(scope, element, attr, ctrls) {
  20081. if (ctrls[0]) {
  20082. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  20083. $browser, $filter, $parse);
  20084. }
  20085. }
  20086. }
  20087. };
  20088. }];
  20089. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  20090. /**
  20091. * @ngdoc directive
  20092. * @name ngValue
  20093. *
  20094. * @description
  20095. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  20096. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  20097. * the bound value.
  20098. *
  20099. * `ngValue` is useful when dynamically generating lists of radio buttons using
  20100. * {@link ngRepeat `ngRepeat`}, as shown below.
  20101. *
  20102. * Likewise, `ngValue` can be used to generate `<option>` elements for
  20103. * the {@link select `select`} element. In that case however, only strings are supported
  20104. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  20105. * Support for `select` models with non-string values is available via `ngOptions`.
  20106. *
  20107. * @element input
  20108. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  20109. * of the `input` element
  20110. *
  20111. * @example
  20112. <example name="ngValue-directive" module="valueExample">
  20113. <file name="index.html">
  20114. <script>
  20115. angular.module('valueExample', [])
  20116. .controller('ExampleController', ['$scope', function($scope) {
  20117. $scope.names = ['pizza', 'unicorns', 'robots'];
  20118. $scope.my = { favorite: 'unicorns' };
  20119. }]);
  20120. </script>
  20121. <form ng-controller="ExampleController">
  20122. <h2>Which is your favorite?</h2>
  20123. <label ng-repeat="name in names" for="{{name}}">
  20124. {{name}}
  20125. <input type="radio"
  20126. ng-model="my.favorite"
  20127. ng-value="name"
  20128. id="{{name}}"
  20129. name="favorite">
  20130. </label>
  20131. <div>You chose {{my.favorite}}</div>
  20132. </form>
  20133. </file>
  20134. <file name="protractor.js" type="protractor">
  20135. var favorite = element(by.binding('my.favorite'));
  20136. it('should initialize to model', function() {
  20137. expect(favorite.getText()).toContain('unicorns');
  20138. });
  20139. it('should bind the values to the inputs', function() {
  20140. element.all(by.model('my.favorite')).get(0).click();
  20141. expect(favorite.getText()).toContain('pizza');
  20142. });
  20143. </file>
  20144. </example>
  20145. */
  20146. var ngValueDirective = function() {
  20147. return {
  20148. restrict: 'A',
  20149. priority: 100,
  20150. compile: function(tpl, tplAttr) {
  20151. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  20152. return function ngValueConstantLink(scope, elm, attr) {
  20153. attr.$set('value', scope.$eval(attr.ngValue));
  20154. };
  20155. } else {
  20156. return function ngValueLink(scope, elm, attr) {
  20157. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  20158. attr.$set('value', value);
  20159. });
  20160. };
  20161. }
  20162. }
  20163. };
  20164. };
  20165. /**
  20166. * @ngdoc directive
  20167. * @name ngBind
  20168. * @restrict AC
  20169. *
  20170. * @description
  20171. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  20172. * with the value of a given expression, and to update the text content when the value of that
  20173. * expression changes.
  20174. *
  20175. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  20176. * `{{ expression }}` which is similar but less verbose.
  20177. *
  20178. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  20179. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  20180. * element attribute, it makes the bindings invisible to the user while the page is loading.
  20181. *
  20182. * An alternative solution to this problem would be using the
  20183. * {@link ng.directive:ngCloak ngCloak} directive.
  20184. *
  20185. *
  20186. * @element ANY
  20187. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  20188. *
  20189. * @example
  20190. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  20191. <example module="bindExample">
  20192. <file name="index.html">
  20193. <script>
  20194. angular.module('bindExample', [])
  20195. .controller('ExampleController', ['$scope', function($scope) {
  20196. $scope.name = 'Whirled';
  20197. }]);
  20198. </script>
  20199. <div ng-controller="ExampleController">
  20200. <label>Enter name: <input type="text" ng-model="name"></label><br>
  20201. Hello <span ng-bind="name"></span>!
  20202. </div>
  20203. </file>
  20204. <file name="protractor.js" type="protractor">
  20205. it('should check ng-bind', function() {
  20206. var nameInput = element(by.model('name'));
  20207. expect(element(by.binding('name')).getText()).toBe('Whirled');
  20208. nameInput.clear();
  20209. nameInput.sendKeys('world');
  20210. expect(element(by.binding('name')).getText()).toBe('world');
  20211. });
  20212. </file>
  20213. </example>
  20214. */
  20215. var ngBindDirective = ['$compile', function($compile) {
  20216. return {
  20217. restrict: 'AC',
  20218. compile: function ngBindCompile(templateElement) {
  20219. $compile.$$addBindingClass(templateElement);
  20220. return function ngBindLink(scope, element, attr) {
  20221. $compile.$$addBindingInfo(element, attr.ngBind);
  20222. element = element[0];
  20223. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  20224. element.textContent = value === undefined ? '' : value;
  20225. });
  20226. };
  20227. }
  20228. };
  20229. }];
  20230. /**
  20231. * @ngdoc directive
  20232. * @name ngBindTemplate
  20233. *
  20234. * @description
  20235. * The `ngBindTemplate` directive specifies that the element
  20236. * text content should be replaced with the interpolation of the template
  20237. * in the `ngBindTemplate` attribute.
  20238. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  20239. * expressions. This directive is needed since some HTML elements
  20240. * (such as TITLE and OPTION) cannot contain SPAN elements.
  20241. *
  20242. * @element ANY
  20243. * @param {string} ngBindTemplate template of form
  20244. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  20245. *
  20246. * @example
  20247. * Try it here: enter text in text box and watch the greeting change.
  20248. <example module="bindExample">
  20249. <file name="index.html">
  20250. <script>
  20251. angular.module('bindExample', [])
  20252. .controller('ExampleController', ['$scope', function($scope) {
  20253. $scope.salutation = 'Hello';
  20254. $scope.name = 'World';
  20255. }]);
  20256. </script>
  20257. <div ng-controller="ExampleController">
  20258. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  20259. <label>Name: <input type="text" ng-model="name"></label><br>
  20260. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  20261. </div>
  20262. </file>
  20263. <file name="protractor.js" type="protractor">
  20264. it('should check ng-bind', function() {
  20265. var salutationElem = element(by.binding('salutation'));
  20266. var salutationInput = element(by.model('salutation'));
  20267. var nameInput = element(by.model('name'));
  20268. expect(salutationElem.getText()).toBe('Hello World!');
  20269. salutationInput.clear();
  20270. salutationInput.sendKeys('Greetings');
  20271. nameInput.clear();
  20272. nameInput.sendKeys('user');
  20273. expect(salutationElem.getText()).toBe('Greetings user!');
  20274. });
  20275. </file>
  20276. </example>
  20277. */
  20278. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  20279. return {
  20280. compile: function ngBindTemplateCompile(templateElement) {
  20281. $compile.$$addBindingClass(templateElement);
  20282. return function ngBindTemplateLink(scope, element, attr) {
  20283. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  20284. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  20285. element = element[0];
  20286. attr.$observe('ngBindTemplate', function(value) {
  20287. element.textContent = value === undefined ? '' : value;
  20288. });
  20289. };
  20290. }
  20291. };
  20292. }];
  20293. /**
  20294. * @ngdoc directive
  20295. * @name ngBindHtml
  20296. *
  20297. * @description
  20298. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  20299. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  20300. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  20301. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  20302. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  20303. *
  20304. * You may also bypass sanitization for values you know are safe. To do so, bind to
  20305. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  20306. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  20307. *
  20308. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  20309. * will have an exception (instead of an exploit.)
  20310. *
  20311. * @element ANY
  20312. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  20313. *
  20314. * @example
  20315. <example module="bindHtmlExample" deps="angular-sanitize.js">
  20316. <file name="index.html">
  20317. <div ng-controller="ExampleController">
  20318. <p ng-bind-html="myHTML"></p>
  20319. </div>
  20320. </file>
  20321. <file name="script.js">
  20322. angular.module('bindHtmlExample', ['ngSanitize'])
  20323. .controller('ExampleController', ['$scope', function($scope) {
  20324. $scope.myHTML =
  20325. 'I am an <code>HTML</code>string with ' +
  20326. '<a href="#">links!</a> and other <em>stuff</em>';
  20327. }]);
  20328. </file>
  20329. <file name="protractor.js" type="protractor">
  20330. it('should check ng-bind-html', function() {
  20331. expect(element(by.binding('myHTML')).getText()).toBe(
  20332. 'I am an HTMLstring with links! and other stuff');
  20333. });
  20334. </file>
  20335. </example>
  20336. */
  20337. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  20338. return {
  20339. restrict: 'A',
  20340. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  20341. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  20342. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  20343. return (value || '').toString();
  20344. });
  20345. $compile.$$addBindingClass(tElement);
  20346. return function ngBindHtmlLink(scope, element, attr) {
  20347. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  20348. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  20349. // we re-evaluate the expr because we want a TrustedValueHolderType
  20350. // for $sce, not a string
  20351. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  20352. });
  20353. };
  20354. }
  20355. };
  20356. }];
  20357. /**
  20358. * @ngdoc directive
  20359. * @name ngChange
  20360. *
  20361. * @description
  20362. * Evaluate the given expression when the user changes the input.
  20363. * The expression is evaluated immediately, unlike the JavaScript onchange event
  20364. * which only triggers at the end of a change (usually, when the user leaves the
  20365. * form element or presses the return key).
  20366. *
  20367. * The `ngChange` expression is only evaluated when a change in the input value causes
  20368. * a new value to be committed to the model.
  20369. *
  20370. * It will not be evaluated:
  20371. * * if the value returned from the `$parsers` transformation pipeline has not changed
  20372. * * if the input has continued to be invalid since the model will stay `null`
  20373. * * if the model is changed programmatically and not by a change to the input value
  20374. *
  20375. *
  20376. * Note, this directive requires `ngModel` to be present.
  20377. *
  20378. * @element input
  20379. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  20380. * in input value.
  20381. *
  20382. * @example
  20383. * <example name="ngChange-directive" module="changeExample">
  20384. * <file name="index.html">
  20385. * <script>
  20386. * angular.module('changeExample', [])
  20387. * .controller('ExampleController', ['$scope', function($scope) {
  20388. * $scope.counter = 0;
  20389. * $scope.change = function() {
  20390. * $scope.counter++;
  20391. * };
  20392. * }]);
  20393. * </script>
  20394. * <div ng-controller="ExampleController">
  20395. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  20396. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  20397. * <label for="ng-change-example2">Confirmed</label><br />
  20398. * <tt>debug = {{confirmed}}</tt><br/>
  20399. * <tt>counter = {{counter}}</tt><br/>
  20400. * </div>
  20401. * </file>
  20402. * <file name="protractor.js" type="protractor">
  20403. * var counter = element(by.binding('counter'));
  20404. * var debug = element(by.binding('confirmed'));
  20405. *
  20406. * it('should evaluate the expression if changing from view', function() {
  20407. * expect(counter.getText()).toContain('0');
  20408. *
  20409. * element(by.id('ng-change-example1')).click();
  20410. *
  20411. * expect(counter.getText()).toContain('1');
  20412. * expect(debug.getText()).toContain('true');
  20413. * });
  20414. *
  20415. * it('should not evaluate the expression if changing from model', function() {
  20416. * element(by.id('ng-change-example2')).click();
  20417. * expect(counter.getText()).toContain('0');
  20418. * expect(debug.getText()).toContain('true');
  20419. * });
  20420. * </file>
  20421. * </example>
  20422. */
  20423. var ngChangeDirective = valueFn({
  20424. restrict: 'A',
  20425. require: 'ngModel',
  20426. link: function(scope, element, attr, ctrl) {
  20427. ctrl.$viewChangeListeners.push(function() {
  20428. scope.$eval(attr.ngChange);
  20429. });
  20430. }
  20431. });
  20432. function classDirective(name, selector) {
  20433. name = 'ngClass' + name;
  20434. return ['$animate', function($animate) {
  20435. return {
  20436. restrict: 'AC',
  20437. link: function(scope, element, attr) {
  20438. var oldVal;
  20439. scope.$watch(attr[name], ngClassWatchAction, true);
  20440. attr.$observe('class', function(value) {
  20441. ngClassWatchAction(scope.$eval(attr[name]));
  20442. });
  20443. if (name !== 'ngClass') {
  20444. scope.$watch('$index', function($index, old$index) {
  20445. // jshint bitwise: false
  20446. var mod = $index & 1;
  20447. if (mod !== (old$index & 1)) {
  20448. var classes = arrayClasses(scope.$eval(attr[name]));
  20449. mod === selector ?
  20450. addClasses(classes) :
  20451. removeClasses(classes);
  20452. }
  20453. });
  20454. }
  20455. function addClasses(classes) {
  20456. var newClasses = digestClassCounts(classes, 1);
  20457. attr.$addClass(newClasses);
  20458. }
  20459. function removeClasses(classes) {
  20460. var newClasses = digestClassCounts(classes, -1);
  20461. attr.$removeClass(newClasses);
  20462. }
  20463. function digestClassCounts(classes, count) {
  20464. // Use createMap() to prevent class assumptions involving property
  20465. // names in Object.prototype
  20466. var classCounts = element.data('$classCounts') || createMap();
  20467. var classesToUpdate = [];
  20468. forEach(classes, function(className) {
  20469. if (count > 0 || classCounts[className]) {
  20470. classCounts[className] = (classCounts[className] || 0) + count;
  20471. if (classCounts[className] === +(count > 0)) {
  20472. classesToUpdate.push(className);
  20473. }
  20474. }
  20475. });
  20476. element.data('$classCounts', classCounts);
  20477. return classesToUpdate.join(' ');
  20478. }
  20479. function updateClasses(oldClasses, newClasses) {
  20480. var toAdd = arrayDifference(newClasses, oldClasses);
  20481. var toRemove = arrayDifference(oldClasses, newClasses);
  20482. toAdd = digestClassCounts(toAdd, 1);
  20483. toRemove = digestClassCounts(toRemove, -1);
  20484. if (toAdd && toAdd.length) {
  20485. $animate.addClass(element, toAdd);
  20486. }
  20487. if (toRemove && toRemove.length) {
  20488. $animate.removeClass(element, toRemove);
  20489. }
  20490. }
  20491. function ngClassWatchAction(newVal) {
  20492. if (selector === true || scope.$index % 2 === selector) {
  20493. var newClasses = arrayClasses(newVal || []);
  20494. if (!oldVal) {
  20495. addClasses(newClasses);
  20496. } else if (!equals(newVal,oldVal)) {
  20497. var oldClasses = arrayClasses(oldVal);
  20498. updateClasses(oldClasses, newClasses);
  20499. }
  20500. }
  20501. oldVal = shallowCopy(newVal);
  20502. }
  20503. }
  20504. };
  20505. function arrayDifference(tokens1, tokens2) {
  20506. var values = [];
  20507. outer:
  20508. for (var i = 0; i < tokens1.length; i++) {
  20509. var token = tokens1[i];
  20510. for (var j = 0; j < tokens2.length; j++) {
  20511. if (token == tokens2[j]) continue outer;
  20512. }
  20513. values.push(token);
  20514. }
  20515. return values;
  20516. }
  20517. function arrayClasses(classVal) {
  20518. var classes = [];
  20519. if (isArray(classVal)) {
  20520. forEach(classVal, function(v) {
  20521. classes = classes.concat(arrayClasses(v));
  20522. });
  20523. return classes;
  20524. } else if (isString(classVal)) {
  20525. return classVal.split(' ');
  20526. } else if (isObject(classVal)) {
  20527. forEach(classVal, function(v, k) {
  20528. if (v) {
  20529. classes = classes.concat(k.split(' '));
  20530. }
  20531. });
  20532. return classes;
  20533. }
  20534. return classVal;
  20535. }
  20536. }];
  20537. }
  20538. /**
  20539. * @ngdoc directive
  20540. * @name ngClass
  20541. * @restrict AC
  20542. *
  20543. * @description
  20544. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  20545. * an expression that represents all classes to be added.
  20546. *
  20547. * The directive operates in three different ways, depending on which of three types the expression
  20548. * evaluates to:
  20549. *
  20550. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  20551. * names.
  20552. *
  20553. * 2. If the expression evaluates to an object, then for each key-value pair of the
  20554. * object with a truthy value the corresponding key is used as a class name.
  20555. *
  20556. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  20557. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  20558. * to give you more control over what CSS classes appear. See the code below for an example of this.
  20559. *
  20560. *
  20561. * The directive won't add duplicate classes if a particular class was already set.
  20562. *
  20563. * When the expression changes, the previously added classes are removed and only then are the
  20564. * new classes added.
  20565. *
  20566. * @animations
  20567. * **add** - happens just before the class is applied to the elements
  20568. *
  20569. * **remove** - happens just before the class is removed from the element
  20570. *
  20571. * @element ANY
  20572. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  20573. * of the evaluation can be a string representing space delimited class
  20574. * names, an array, or a map of class names to boolean values. In the case of a map, the
  20575. * names of the properties whose values are truthy will be added as css classes to the
  20576. * element.
  20577. *
  20578. * @example Example that demonstrates basic bindings via ngClass directive.
  20579. <example>
  20580. <file name="index.html">
  20581. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  20582. <label>
  20583. <input type="checkbox" ng-model="deleted">
  20584. deleted (apply "strike" class)
  20585. </label><br>
  20586. <label>
  20587. <input type="checkbox" ng-model="important">
  20588. important (apply "bold" class)
  20589. </label><br>
  20590. <label>
  20591. <input type="checkbox" ng-model="error">
  20592. error (apply "has-error" class)
  20593. </label>
  20594. <hr>
  20595. <p ng-class="style">Using String Syntax</p>
  20596. <input type="text" ng-model="style"
  20597. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  20598. <hr>
  20599. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  20600. <input ng-model="style1"
  20601. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  20602. <input ng-model="style2"
  20603. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  20604. <input ng-model="style3"
  20605. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  20606. <hr>
  20607. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  20608. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  20609. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  20610. </file>
  20611. <file name="style.css">
  20612. .strike {
  20613. text-decoration: line-through;
  20614. }
  20615. .bold {
  20616. font-weight: bold;
  20617. }
  20618. .red {
  20619. color: red;
  20620. }
  20621. .has-error {
  20622. color: red;
  20623. background-color: yellow;
  20624. }
  20625. .orange {
  20626. color: orange;
  20627. }
  20628. </file>
  20629. <file name="protractor.js" type="protractor">
  20630. var ps = element.all(by.css('p'));
  20631. it('should let you toggle the class', function() {
  20632. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  20633. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  20634. element(by.model('important')).click();
  20635. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  20636. element(by.model('error')).click();
  20637. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  20638. });
  20639. it('should let you toggle string example', function() {
  20640. expect(ps.get(1).getAttribute('class')).toBe('');
  20641. element(by.model('style')).clear();
  20642. element(by.model('style')).sendKeys('red');
  20643. expect(ps.get(1).getAttribute('class')).toBe('red');
  20644. });
  20645. it('array example should have 3 classes', function() {
  20646. expect(ps.get(2).getAttribute('class')).toBe('');
  20647. element(by.model('style1')).sendKeys('bold');
  20648. element(by.model('style2')).sendKeys('strike');
  20649. element(by.model('style3')).sendKeys('red');
  20650. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  20651. });
  20652. it('array with map example should have 2 classes', function() {
  20653. expect(ps.last().getAttribute('class')).toBe('');
  20654. element(by.model('style4')).sendKeys('bold');
  20655. element(by.model('warning')).click();
  20656. expect(ps.last().getAttribute('class')).toBe('bold orange');
  20657. });
  20658. </file>
  20659. </example>
  20660. ## Animations
  20661. The example below demonstrates how to perform animations using ngClass.
  20662. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20663. <file name="index.html">
  20664. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  20665. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  20666. <br>
  20667. <span class="base-class" ng-class="myVar">Sample Text</span>
  20668. </file>
  20669. <file name="style.css">
  20670. .base-class {
  20671. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20672. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20673. }
  20674. .base-class.my-class {
  20675. color: red;
  20676. font-size:3em;
  20677. }
  20678. </file>
  20679. <file name="protractor.js" type="protractor">
  20680. it('should check ng-class', function() {
  20681. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20682. toMatch(/my-class/);
  20683. element(by.id('setbtn')).click();
  20684. expect(element(by.css('.base-class')).getAttribute('class')).
  20685. toMatch(/my-class/);
  20686. element(by.id('clearbtn')).click();
  20687. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20688. toMatch(/my-class/);
  20689. });
  20690. </file>
  20691. </example>
  20692. ## ngClass and pre-existing CSS3 Transitions/Animations
  20693. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  20694. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  20695. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  20696. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  20697. {@link $animate#removeClass $animate.removeClass}.
  20698. */
  20699. var ngClassDirective = classDirective('', true);
  20700. /**
  20701. * @ngdoc directive
  20702. * @name ngClassOdd
  20703. * @restrict AC
  20704. *
  20705. * @description
  20706. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20707. * {@link ng.directive:ngClass ngClass}, except they work in
  20708. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20709. *
  20710. * This directive can be applied only within the scope of an
  20711. * {@link ng.directive:ngRepeat ngRepeat}.
  20712. *
  20713. * @element ANY
  20714. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  20715. * of the evaluation can be a string representing space delimited class names or an array.
  20716. *
  20717. * @example
  20718. <example>
  20719. <file name="index.html">
  20720. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20721. <li ng-repeat="name in names">
  20722. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20723. {{name}}
  20724. </span>
  20725. </li>
  20726. </ol>
  20727. </file>
  20728. <file name="style.css">
  20729. .odd {
  20730. color: red;
  20731. }
  20732. .even {
  20733. color: blue;
  20734. }
  20735. </file>
  20736. <file name="protractor.js" type="protractor">
  20737. it('should check ng-class-odd and ng-class-even', function() {
  20738. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20739. toMatch(/odd/);
  20740. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20741. toMatch(/even/);
  20742. });
  20743. </file>
  20744. </example>
  20745. */
  20746. var ngClassOddDirective = classDirective('Odd', 0);
  20747. /**
  20748. * @ngdoc directive
  20749. * @name ngClassEven
  20750. * @restrict AC
  20751. *
  20752. * @description
  20753. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20754. * {@link ng.directive:ngClass ngClass}, except they work in
  20755. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20756. *
  20757. * This directive can be applied only within the scope of an
  20758. * {@link ng.directive:ngRepeat ngRepeat}.
  20759. *
  20760. * @element ANY
  20761. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  20762. * result of the evaluation can be a string representing space delimited class names or an array.
  20763. *
  20764. * @example
  20765. <example>
  20766. <file name="index.html">
  20767. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20768. <li ng-repeat="name in names">
  20769. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20770. {{name}} &nbsp; &nbsp; &nbsp;
  20771. </span>
  20772. </li>
  20773. </ol>
  20774. </file>
  20775. <file name="style.css">
  20776. .odd {
  20777. color: red;
  20778. }
  20779. .even {
  20780. color: blue;
  20781. }
  20782. </file>
  20783. <file name="protractor.js" type="protractor">
  20784. it('should check ng-class-odd and ng-class-even', function() {
  20785. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20786. toMatch(/odd/);
  20787. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20788. toMatch(/even/);
  20789. });
  20790. </file>
  20791. </example>
  20792. */
  20793. var ngClassEvenDirective = classDirective('Even', 1);
  20794. /**
  20795. * @ngdoc directive
  20796. * @name ngCloak
  20797. * @restrict AC
  20798. *
  20799. * @description
  20800. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  20801. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  20802. * directive to avoid the undesirable flicker effect caused by the html template display.
  20803. *
  20804. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  20805. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  20806. * of the browser view.
  20807. *
  20808. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  20809. * `angular.min.js`.
  20810. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  20811. *
  20812. * ```css
  20813. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  20814. * display: none !important;
  20815. * }
  20816. * ```
  20817. *
  20818. * When this css rule is loaded by the browser, all html elements (including their children) that
  20819. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  20820. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  20821. * the compiled element visible.
  20822. *
  20823. * For the best result, the `angular.js` script must be loaded in the head section of the html
  20824. * document; alternatively, the css rule above must be included in the external stylesheet of the
  20825. * application.
  20826. *
  20827. * @element ANY
  20828. *
  20829. * @example
  20830. <example>
  20831. <file name="index.html">
  20832. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  20833. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  20834. </file>
  20835. <file name="protractor.js" type="protractor">
  20836. it('should remove the template directive and css class', function() {
  20837. expect($('#template1').getAttribute('ng-cloak')).
  20838. toBeNull();
  20839. expect($('#template2').getAttribute('ng-cloak')).
  20840. toBeNull();
  20841. });
  20842. </file>
  20843. </example>
  20844. *
  20845. */
  20846. var ngCloakDirective = ngDirective({
  20847. compile: function(element, attr) {
  20848. attr.$set('ngCloak', undefined);
  20849. element.removeClass('ng-cloak');
  20850. }
  20851. });
  20852. /**
  20853. * @ngdoc directive
  20854. * @name ngController
  20855. *
  20856. * @description
  20857. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  20858. * supports the principles behind the Model-View-Controller design pattern.
  20859. *
  20860. * MVC components in angular:
  20861. *
  20862. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  20863. * are accessed through bindings.
  20864. * * View — The template (HTML with data bindings) that is rendered into the View.
  20865. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  20866. * logic behind the application to decorate the scope with functions and values
  20867. *
  20868. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  20869. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  20870. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  20871. * and executed twice.
  20872. *
  20873. * @element ANY
  20874. * @scope
  20875. * @priority 500
  20876. * @param {expression} ngController Name of a constructor function registered with the current
  20877. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  20878. * that on the current scope evaluates to a constructor function.
  20879. *
  20880. * The controller instance can be published into a scope property by specifying
  20881. * `ng-controller="as propertyName"`.
  20882. *
  20883. * If the current `$controllerProvider` is configured to use globals (via
  20884. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  20885. * also be the name of a globally accessible constructor function (not recommended).
  20886. *
  20887. * @example
  20888. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  20889. * greeting are methods declared on the controller (see source tab). These methods can
  20890. * easily be called from the angular markup. Any changes to the data are automatically reflected
  20891. * in the View without the need for a manual update.
  20892. *
  20893. * Two different declaration styles are included below:
  20894. *
  20895. * * one binds methods and properties directly onto the controller using `this`:
  20896. * `ng-controller="SettingsController1 as settings"`
  20897. * * one injects `$scope` into the controller:
  20898. * `ng-controller="SettingsController2"`
  20899. *
  20900. * The second option is more common in the Angular community, and is generally used in boilerplates
  20901. * and in this guide. However, there are advantages to binding properties directly to the controller
  20902. * and avoiding scope.
  20903. *
  20904. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  20905. * multiple controllers apply to an element.
  20906. * * If you are writing your controllers as classes you have easier access to the properties and
  20907. * methods, which will appear on the scope, from inside the controller code.
  20908. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  20909. * inheritance masking primitives.
  20910. *
  20911. * This example demonstrates the `controller as` syntax.
  20912. *
  20913. * <example name="ngControllerAs" module="controllerAsExample">
  20914. * <file name="index.html">
  20915. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  20916. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  20917. * <button ng-click="settings.greet()">greet</button><br/>
  20918. * Contact:
  20919. * <ul>
  20920. * <li ng-repeat="contact in settings.contacts">
  20921. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  20922. * <option>phone</option>
  20923. * <option>email</option>
  20924. * </select>
  20925. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  20926. * <button ng-click="settings.clearContact(contact)">clear</button>
  20927. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  20928. * </li>
  20929. * <li><button ng-click="settings.addContact()">add</button></li>
  20930. * </ul>
  20931. * </div>
  20932. * </file>
  20933. * <file name="app.js">
  20934. * angular.module('controllerAsExample', [])
  20935. * .controller('SettingsController1', SettingsController1);
  20936. *
  20937. * function SettingsController1() {
  20938. * this.name = "John Smith";
  20939. * this.contacts = [
  20940. * {type: 'phone', value: '408 555 1212'},
  20941. * {type: 'email', value: 'john.smith@example.org'} ];
  20942. * }
  20943. *
  20944. * SettingsController1.prototype.greet = function() {
  20945. * alert(this.name);
  20946. * };
  20947. *
  20948. * SettingsController1.prototype.addContact = function() {
  20949. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  20950. * };
  20951. *
  20952. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  20953. * var index = this.contacts.indexOf(contactToRemove);
  20954. * this.contacts.splice(index, 1);
  20955. * };
  20956. *
  20957. * SettingsController1.prototype.clearContact = function(contact) {
  20958. * contact.type = 'phone';
  20959. * contact.value = '';
  20960. * };
  20961. * </file>
  20962. * <file name="protractor.js" type="protractor">
  20963. * it('should check controller as', function() {
  20964. * var container = element(by.id('ctrl-as-exmpl'));
  20965. * expect(container.element(by.model('settings.name'))
  20966. * .getAttribute('value')).toBe('John Smith');
  20967. *
  20968. * var firstRepeat =
  20969. * container.element(by.repeater('contact in settings.contacts').row(0));
  20970. * var secondRepeat =
  20971. * container.element(by.repeater('contact in settings.contacts').row(1));
  20972. *
  20973. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20974. * .toBe('408 555 1212');
  20975. *
  20976. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20977. * .toBe('john.smith@example.org');
  20978. *
  20979. * firstRepeat.element(by.buttonText('clear')).click();
  20980. *
  20981. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20982. * .toBe('');
  20983. *
  20984. * container.element(by.buttonText('add')).click();
  20985. *
  20986. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  20987. * .element(by.model('contact.value'))
  20988. * .getAttribute('value'))
  20989. * .toBe('yourname@example.org');
  20990. * });
  20991. * </file>
  20992. * </example>
  20993. *
  20994. * This example demonstrates the "attach to `$scope`" style of controller.
  20995. *
  20996. * <example name="ngController" module="controllerExample">
  20997. * <file name="index.html">
  20998. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  20999. * <label>Name: <input type="text" ng-model="name"/></label>
  21000. * <button ng-click="greet()">greet</button><br/>
  21001. * Contact:
  21002. * <ul>
  21003. * <li ng-repeat="contact in contacts">
  21004. * <select ng-model="contact.type" id="select_{{$index}}">
  21005. * <option>phone</option>
  21006. * <option>email</option>
  21007. * </select>
  21008. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  21009. * <button ng-click="clearContact(contact)">clear</button>
  21010. * <button ng-click="removeContact(contact)">X</button>
  21011. * </li>
  21012. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  21013. * </ul>
  21014. * </div>
  21015. * </file>
  21016. * <file name="app.js">
  21017. * angular.module('controllerExample', [])
  21018. * .controller('SettingsController2', ['$scope', SettingsController2]);
  21019. *
  21020. * function SettingsController2($scope) {
  21021. * $scope.name = "John Smith";
  21022. * $scope.contacts = [
  21023. * {type:'phone', value:'408 555 1212'},
  21024. * {type:'email', value:'john.smith@example.org'} ];
  21025. *
  21026. * $scope.greet = function() {
  21027. * alert($scope.name);
  21028. * };
  21029. *
  21030. * $scope.addContact = function() {
  21031. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  21032. * };
  21033. *
  21034. * $scope.removeContact = function(contactToRemove) {
  21035. * var index = $scope.contacts.indexOf(contactToRemove);
  21036. * $scope.contacts.splice(index, 1);
  21037. * };
  21038. *
  21039. * $scope.clearContact = function(contact) {
  21040. * contact.type = 'phone';
  21041. * contact.value = '';
  21042. * };
  21043. * }
  21044. * </file>
  21045. * <file name="protractor.js" type="protractor">
  21046. * it('should check controller', function() {
  21047. * var container = element(by.id('ctrl-exmpl'));
  21048. *
  21049. * expect(container.element(by.model('name'))
  21050. * .getAttribute('value')).toBe('John Smith');
  21051. *
  21052. * var firstRepeat =
  21053. * container.element(by.repeater('contact in contacts').row(0));
  21054. * var secondRepeat =
  21055. * container.element(by.repeater('contact in contacts').row(1));
  21056. *
  21057. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21058. * .toBe('408 555 1212');
  21059. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  21060. * .toBe('john.smith@example.org');
  21061. *
  21062. * firstRepeat.element(by.buttonText('clear')).click();
  21063. *
  21064. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21065. * .toBe('');
  21066. *
  21067. * container.element(by.buttonText('add')).click();
  21068. *
  21069. * expect(container.element(by.repeater('contact in contacts').row(2))
  21070. * .element(by.model('contact.value'))
  21071. * .getAttribute('value'))
  21072. * .toBe('yourname@example.org');
  21073. * });
  21074. * </file>
  21075. *</example>
  21076. */
  21077. var ngControllerDirective = [function() {
  21078. return {
  21079. restrict: 'A',
  21080. scope: true,
  21081. controller: '@',
  21082. priority: 500
  21083. };
  21084. }];
  21085. /**
  21086. * @ngdoc directive
  21087. * @name ngCsp
  21088. *
  21089. * @element html
  21090. * @description
  21091. *
  21092. * Angular has some features that can break certain
  21093. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  21094. *
  21095. * If you intend to implement these rules then you must tell Angular not to use these features.
  21096. *
  21097. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  21098. *
  21099. *
  21100. * The following rules affect Angular:
  21101. *
  21102. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  21103. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  21104. * increase in the speed of evaluating Angular expressions.
  21105. *
  21106. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  21107. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  21108. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  21109. * `angular-csp.css` in your HTML manually.
  21110. *
  21111. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  21112. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  21113. * however, triggers a CSP error to be logged in the console:
  21114. *
  21115. * ```
  21116. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  21117. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  21118. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  21119. * ```
  21120. *
  21121. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  21122. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  21123. * the `angular.js` file.
  21124. *
  21125. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  21126. *
  21127. * You can specify which of the CSP related Angular features should be deactivated by providing
  21128. * a value for the `ng-csp` attribute. The options are as follows:
  21129. *
  21130. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  21131. *
  21132. * * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings
  21133. *
  21134. * You can use these values in the following combinations:
  21135. *
  21136. *
  21137. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  21138. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  21139. * of Angular.
  21140. *
  21141. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  21142. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  21143. * of Angular.
  21144. *
  21145. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  21146. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  21147. *
  21148. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  21149. * run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  21150. *
  21151. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  21152. * styles nor use eval, which is the same as an empty: ng-csp.
  21153. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  21154. *
  21155. * @example
  21156. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  21157. ```html
  21158. <!doctype html>
  21159. <html ng-app ng-csp>
  21160. ...
  21161. ...
  21162. </html>
  21163. ```
  21164. * @example
  21165. // Note: the suffix `.csp` in the example name triggers
  21166. // csp mode in our http server!
  21167. <example name="example.csp" module="cspExample" ng-csp="true">
  21168. <file name="index.html">
  21169. <div ng-controller="MainController as ctrl">
  21170. <div>
  21171. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  21172. <span id="counter">
  21173. {{ctrl.counter}}
  21174. </span>
  21175. </div>
  21176. <div>
  21177. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  21178. <span id="evilError">
  21179. {{ctrl.evilError}}
  21180. </span>
  21181. </div>
  21182. </div>
  21183. </file>
  21184. <file name="script.js">
  21185. angular.module('cspExample', [])
  21186. .controller('MainController', function() {
  21187. this.counter = 0;
  21188. this.inc = function() {
  21189. this.counter++;
  21190. };
  21191. this.evil = function() {
  21192. // jshint evil:true
  21193. try {
  21194. eval('1+2');
  21195. } catch (e) {
  21196. this.evilError = e.message;
  21197. }
  21198. };
  21199. });
  21200. </file>
  21201. <file name="protractor.js" type="protractor">
  21202. var util, webdriver;
  21203. var incBtn = element(by.id('inc'));
  21204. var counter = element(by.id('counter'));
  21205. var evilBtn = element(by.id('evil'));
  21206. var evilError = element(by.id('evilError'));
  21207. function getAndClearSevereErrors() {
  21208. return browser.manage().logs().get('browser').then(function(browserLog) {
  21209. return browserLog.filter(function(logEntry) {
  21210. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  21211. });
  21212. });
  21213. }
  21214. function clearErrors() {
  21215. getAndClearSevereErrors();
  21216. }
  21217. function expectNoErrors() {
  21218. getAndClearSevereErrors().then(function(filteredLog) {
  21219. expect(filteredLog.length).toEqual(0);
  21220. if (filteredLog.length) {
  21221. console.log('browser console errors: ' + util.inspect(filteredLog));
  21222. }
  21223. });
  21224. }
  21225. function expectError(regex) {
  21226. getAndClearSevereErrors().then(function(filteredLog) {
  21227. var found = false;
  21228. filteredLog.forEach(function(log) {
  21229. if (log.message.match(regex)) {
  21230. found = true;
  21231. }
  21232. });
  21233. if (!found) {
  21234. throw new Error('expected an error that matches ' + regex);
  21235. }
  21236. });
  21237. }
  21238. beforeEach(function() {
  21239. util = require('util');
  21240. webdriver = require('protractor/node_modules/selenium-webdriver');
  21241. });
  21242. // For now, we only test on Chrome,
  21243. // as Safari does not load the page with Protractor's injected scripts,
  21244. // and Firefox webdriver always disables content security policy (#6358)
  21245. if (browser.params.browser !== 'chrome') {
  21246. return;
  21247. }
  21248. it('should not report errors when the page is loaded', function() {
  21249. // clear errors so we are not dependent on previous tests
  21250. clearErrors();
  21251. // Need to reload the page as the page is already loaded when
  21252. // we come here
  21253. browser.driver.getCurrentUrl().then(function(url) {
  21254. browser.get(url);
  21255. });
  21256. expectNoErrors();
  21257. });
  21258. it('should evaluate expressions', function() {
  21259. expect(counter.getText()).toEqual('0');
  21260. incBtn.click();
  21261. expect(counter.getText()).toEqual('1');
  21262. expectNoErrors();
  21263. });
  21264. it('should throw and report an error when using "eval"', function() {
  21265. evilBtn.click();
  21266. expect(evilError.getText()).toMatch(/Content Security Policy/);
  21267. expectError(/Content Security Policy/);
  21268. });
  21269. </file>
  21270. </example>
  21271. */
  21272. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  21273. // bootstrap the system (before $parse is instantiated), for this reason we just have
  21274. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  21275. /**
  21276. * @ngdoc directive
  21277. * @name ngClick
  21278. *
  21279. * @description
  21280. * The ngClick directive allows you to specify custom behavior when
  21281. * an element is clicked.
  21282. *
  21283. * @element ANY
  21284. * @priority 0
  21285. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  21286. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  21287. *
  21288. * @example
  21289. <example>
  21290. <file name="index.html">
  21291. <button ng-click="count = count + 1" ng-init="count=0">
  21292. Increment
  21293. </button>
  21294. <span>
  21295. count: {{count}}
  21296. </span>
  21297. </file>
  21298. <file name="protractor.js" type="protractor">
  21299. it('should check ng-click', function() {
  21300. expect(element(by.binding('count')).getText()).toMatch('0');
  21301. element(by.css('button')).click();
  21302. expect(element(by.binding('count')).getText()).toMatch('1');
  21303. });
  21304. </file>
  21305. </example>
  21306. */
  21307. /*
  21308. * A collection of directives that allows creation of custom event handlers that are defined as
  21309. * angular expressions and are compiled and executed within the current scope.
  21310. */
  21311. var ngEventDirectives = {};
  21312. // For events that might fire synchronously during DOM manipulation
  21313. // we need to execute their event handlers asynchronously using $evalAsync,
  21314. // so that they are not executed in an inconsistent state.
  21315. var forceAsyncEvents = {
  21316. 'blur': true,
  21317. 'focus': true
  21318. };
  21319. forEach(
  21320. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  21321. function(eventName) {
  21322. var directiveName = directiveNormalize('ng-' + eventName);
  21323. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  21324. return {
  21325. restrict: 'A',
  21326. compile: function($element, attr) {
  21327. // We expose the powerful $event object on the scope that provides access to the Window,
  21328. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  21329. // checks at the cost of speed since event handler expressions are not executed as
  21330. // frequently as regular change detection.
  21331. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  21332. return function ngEventHandler(scope, element) {
  21333. element.on(eventName, function(event) {
  21334. var callback = function() {
  21335. fn(scope, {$event:event});
  21336. };
  21337. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  21338. scope.$evalAsync(callback);
  21339. } else {
  21340. scope.$apply(callback);
  21341. }
  21342. });
  21343. };
  21344. }
  21345. };
  21346. }];
  21347. }
  21348. );
  21349. /**
  21350. * @ngdoc directive
  21351. * @name ngDblclick
  21352. *
  21353. * @description
  21354. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  21355. *
  21356. * @element ANY
  21357. * @priority 0
  21358. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  21359. * a dblclick. (The Event object is available as `$event`)
  21360. *
  21361. * @example
  21362. <example>
  21363. <file name="index.html">
  21364. <button ng-dblclick="count = count + 1" ng-init="count=0">
  21365. Increment (on double click)
  21366. </button>
  21367. count: {{count}}
  21368. </file>
  21369. </example>
  21370. */
  21371. /**
  21372. * @ngdoc directive
  21373. * @name ngMousedown
  21374. *
  21375. * @description
  21376. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  21377. *
  21378. * @element ANY
  21379. * @priority 0
  21380. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  21381. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  21382. *
  21383. * @example
  21384. <example>
  21385. <file name="index.html">
  21386. <button ng-mousedown="count = count + 1" ng-init="count=0">
  21387. Increment (on mouse down)
  21388. </button>
  21389. count: {{count}}
  21390. </file>
  21391. </example>
  21392. */
  21393. /**
  21394. * @ngdoc directive
  21395. * @name ngMouseup
  21396. *
  21397. * @description
  21398. * Specify custom behavior on mouseup event.
  21399. *
  21400. * @element ANY
  21401. * @priority 0
  21402. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  21403. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  21404. *
  21405. * @example
  21406. <example>
  21407. <file name="index.html">
  21408. <button ng-mouseup="count = count + 1" ng-init="count=0">
  21409. Increment (on mouse up)
  21410. </button>
  21411. count: {{count}}
  21412. </file>
  21413. </example>
  21414. */
  21415. /**
  21416. * @ngdoc directive
  21417. * @name ngMouseover
  21418. *
  21419. * @description
  21420. * Specify custom behavior on mouseover event.
  21421. *
  21422. * @element ANY
  21423. * @priority 0
  21424. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  21425. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  21426. *
  21427. * @example
  21428. <example>
  21429. <file name="index.html">
  21430. <button ng-mouseover="count = count + 1" ng-init="count=0">
  21431. Increment (when mouse is over)
  21432. </button>
  21433. count: {{count}}
  21434. </file>
  21435. </example>
  21436. */
  21437. /**
  21438. * @ngdoc directive
  21439. * @name ngMouseenter
  21440. *
  21441. * @description
  21442. * Specify custom behavior on mouseenter event.
  21443. *
  21444. * @element ANY
  21445. * @priority 0
  21446. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  21447. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  21448. *
  21449. * @example
  21450. <example>
  21451. <file name="index.html">
  21452. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  21453. Increment (when mouse enters)
  21454. </button>
  21455. count: {{count}}
  21456. </file>
  21457. </example>
  21458. */
  21459. /**
  21460. * @ngdoc directive
  21461. * @name ngMouseleave
  21462. *
  21463. * @description
  21464. * Specify custom behavior on mouseleave event.
  21465. *
  21466. * @element ANY
  21467. * @priority 0
  21468. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  21469. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  21470. *
  21471. * @example
  21472. <example>
  21473. <file name="index.html">
  21474. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  21475. Increment (when mouse leaves)
  21476. </button>
  21477. count: {{count}}
  21478. </file>
  21479. </example>
  21480. */
  21481. /**
  21482. * @ngdoc directive
  21483. * @name ngMousemove
  21484. *
  21485. * @description
  21486. * Specify custom behavior on mousemove event.
  21487. *
  21488. * @element ANY
  21489. * @priority 0
  21490. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  21491. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  21492. *
  21493. * @example
  21494. <example>
  21495. <file name="index.html">
  21496. <button ng-mousemove="count = count + 1" ng-init="count=0">
  21497. Increment (when mouse moves)
  21498. </button>
  21499. count: {{count}}
  21500. </file>
  21501. </example>
  21502. */
  21503. /**
  21504. * @ngdoc directive
  21505. * @name ngKeydown
  21506. *
  21507. * @description
  21508. * Specify custom behavior on keydown event.
  21509. *
  21510. * @element ANY
  21511. * @priority 0
  21512. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  21513. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21514. *
  21515. * @example
  21516. <example>
  21517. <file name="index.html">
  21518. <input ng-keydown="count = count + 1" ng-init="count=0">
  21519. key down count: {{count}}
  21520. </file>
  21521. </example>
  21522. */
  21523. /**
  21524. * @ngdoc directive
  21525. * @name ngKeyup
  21526. *
  21527. * @description
  21528. * Specify custom behavior on keyup event.
  21529. *
  21530. * @element ANY
  21531. * @priority 0
  21532. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  21533. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21534. *
  21535. * @example
  21536. <example>
  21537. <file name="index.html">
  21538. <p>Typing in the input box below updates the key count</p>
  21539. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  21540. <p>Typing in the input box below updates the keycode</p>
  21541. <input ng-keyup="event=$event">
  21542. <p>event keyCode: {{ event.keyCode }}</p>
  21543. <p>event altKey: {{ event.altKey }}</p>
  21544. </file>
  21545. </example>
  21546. */
  21547. /**
  21548. * @ngdoc directive
  21549. * @name ngKeypress
  21550. *
  21551. * @description
  21552. * Specify custom behavior on keypress event.
  21553. *
  21554. * @element ANY
  21555. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  21556. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  21557. * and can be interrogated for keyCode, altKey, etc.)
  21558. *
  21559. * @example
  21560. <example>
  21561. <file name="index.html">
  21562. <input ng-keypress="count = count + 1" ng-init="count=0">
  21563. key press count: {{count}}
  21564. </file>
  21565. </example>
  21566. */
  21567. /**
  21568. * @ngdoc directive
  21569. * @name ngSubmit
  21570. *
  21571. * @description
  21572. * Enables binding angular expressions to onsubmit events.
  21573. *
  21574. * Additionally it prevents the default action (which for form means sending the request to the
  21575. * server and reloading the current page), but only if the form does not contain `action`,
  21576. * `data-action`, or `x-action` attributes.
  21577. *
  21578. * <div class="alert alert-warning">
  21579. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  21580. * `ngSubmit` handlers together. See the
  21581. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  21582. * for a detailed discussion of when `ngSubmit` may be triggered.
  21583. * </div>
  21584. *
  21585. * @element form
  21586. * @priority 0
  21587. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  21588. * ({@link guide/expression#-event- Event object is available as `$event`})
  21589. *
  21590. * @example
  21591. <example module="submitExample">
  21592. <file name="index.html">
  21593. <script>
  21594. angular.module('submitExample', [])
  21595. .controller('ExampleController', ['$scope', function($scope) {
  21596. $scope.list = [];
  21597. $scope.text = 'hello';
  21598. $scope.submit = function() {
  21599. if ($scope.text) {
  21600. $scope.list.push(this.text);
  21601. $scope.text = '';
  21602. }
  21603. };
  21604. }]);
  21605. </script>
  21606. <form ng-submit="submit()" ng-controller="ExampleController">
  21607. Enter text and hit enter:
  21608. <input type="text" ng-model="text" name="text" />
  21609. <input type="submit" id="submit" value="Submit" />
  21610. <pre>list={{list}}</pre>
  21611. </form>
  21612. </file>
  21613. <file name="protractor.js" type="protractor">
  21614. it('should check ng-submit', function() {
  21615. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21616. element(by.css('#submit')).click();
  21617. expect(element(by.binding('list')).getText()).toContain('hello');
  21618. expect(element(by.model('text')).getAttribute('value')).toBe('');
  21619. });
  21620. it('should ignore empty strings', function() {
  21621. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21622. element(by.css('#submit')).click();
  21623. element(by.css('#submit')).click();
  21624. expect(element(by.binding('list')).getText()).toContain('hello');
  21625. });
  21626. </file>
  21627. </example>
  21628. */
  21629. /**
  21630. * @ngdoc directive
  21631. * @name ngFocus
  21632. *
  21633. * @description
  21634. * Specify custom behavior on focus event.
  21635. *
  21636. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  21637. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21638. * during an `$apply` to ensure a consistent state.
  21639. *
  21640. * @element window, input, select, textarea, a
  21641. * @priority 0
  21642. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  21643. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  21644. *
  21645. * @example
  21646. * See {@link ng.directive:ngClick ngClick}
  21647. */
  21648. /**
  21649. * @ngdoc directive
  21650. * @name ngBlur
  21651. *
  21652. * @description
  21653. * Specify custom behavior on blur event.
  21654. *
  21655. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  21656. * an element has lost focus.
  21657. *
  21658. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  21659. * (e.g. removing a focussed input),
  21660. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21661. * during an `$apply` to ensure a consistent state.
  21662. *
  21663. * @element window, input, select, textarea, a
  21664. * @priority 0
  21665. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  21666. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  21667. *
  21668. * @example
  21669. * See {@link ng.directive:ngClick ngClick}
  21670. */
  21671. /**
  21672. * @ngdoc directive
  21673. * @name ngCopy
  21674. *
  21675. * @description
  21676. * Specify custom behavior on copy event.
  21677. *
  21678. * @element window, input, select, textarea, a
  21679. * @priority 0
  21680. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  21681. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  21682. *
  21683. * @example
  21684. <example>
  21685. <file name="index.html">
  21686. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  21687. copied: {{copied}}
  21688. </file>
  21689. </example>
  21690. */
  21691. /**
  21692. * @ngdoc directive
  21693. * @name ngCut
  21694. *
  21695. * @description
  21696. * Specify custom behavior on cut event.
  21697. *
  21698. * @element window, input, select, textarea, a
  21699. * @priority 0
  21700. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  21701. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  21702. *
  21703. * @example
  21704. <example>
  21705. <file name="index.html">
  21706. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  21707. cut: {{cut}}
  21708. </file>
  21709. </example>
  21710. */
  21711. /**
  21712. * @ngdoc directive
  21713. * @name ngPaste
  21714. *
  21715. * @description
  21716. * Specify custom behavior on paste event.
  21717. *
  21718. * @element window, input, select, textarea, a
  21719. * @priority 0
  21720. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  21721. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  21722. *
  21723. * @example
  21724. <example>
  21725. <file name="index.html">
  21726. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  21727. pasted: {{paste}}
  21728. </file>
  21729. </example>
  21730. */
  21731. /**
  21732. * @ngdoc directive
  21733. * @name ngIf
  21734. * @restrict A
  21735. * @multiElement
  21736. *
  21737. * @description
  21738. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  21739. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  21740. * value then the element is removed from the DOM, otherwise a clone of the
  21741. * element is reinserted into the DOM.
  21742. *
  21743. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  21744. * element in the DOM rather than changing its visibility via the `display` css property. A common
  21745. * case when this difference is significant is when using css selectors that rely on an element's
  21746. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  21747. *
  21748. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  21749. * is created when the element is restored. The scope created within `ngIf` inherits from
  21750. * its parent scope using
  21751. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  21752. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  21753. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  21754. * variable within the child scope will override (hide) the value in the parent scope.
  21755. *
  21756. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  21757. * is if an element's class attribute is directly modified after it's compiled, using something like
  21758. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  21759. * the added class will be lost because the original compiled state is used to regenerate the element.
  21760. *
  21761. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  21762. * and `leave` effects.
  21763. *
  21764. * @animations
  21765. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  21766. * leave - happens just before the `ngIf` contents are removed from the DOM
  21767. *
  21768. * @element ANY
  21769. * @scope
  21770. * @priority 600
  21771. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  21772. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  21773. * element is added to the DOM tree.
  21774. *
  21775. * @example
  21776. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21777. <file name="index.html">
  21778. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  21779. Show when checked:
  21780. <span ng-if="checked" class="animate-if">
  21781. This is removed when the checkbox is unchecked.
  21782. </span>
  21783. </file>
  21784. <file name="animations.css">
  21785. .animate-if {
  21786. background:white;
  21787. border:1px solid black;
  21788. padding:10px;
  21789. }
  21790. .animate-if.ng-enter, .animate-if.ng-leave {
  21791. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21792. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21793. }
  21794. .animate-if.ng-enter,
  21795. .animate-if.ng-leave.ng-leave-active {
  21796. opacity:0;
  21797. }
  21798. .animate-if.ng-leave,
  21799. .animate-if.ng-enter.ng-enter-active {
  21800. opacity:1;
  21801. }
  21802. </file>
  21803. </example>
  21804. */
  21805. var ngIfDirective = ['$animate', function($animate) {
  21806. return {
  21807. multiElement: true,
  21808. transclude: 'element',
  21809. priority: 600,
  21810. terminal: true,
  21811. restrict: 'A',
  21812. $$tlb: true,
  21813. link: function($scope, $element, $attr, ctrl, $transclude) {
  21814. var block, childScope, previousElements;
  21815. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  21816. if (value) {
  21817. if (!childScope) {
  21818. $transclude(function(clone, newScope) {
  21819. childScope = newScope;
  21820. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  21821. // Note: We only need the first/last node of the cloned nodes.
  21822. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  21823. // by a directive with templateUrl when its template arrives.
  21824. block = {
  21825. clone: clone
  21826. };
  21827. $animate.enter(clone, $element.parent(), $element);
  21828. });
  21829. }
  21830. } else {
  21831. if (previousElements) {
  21832. previousElements.remove();
  21833. previousElements = null;
  21834. }
  21835. if (childScope) {
  21836. childScope.$destroy();
  21837. childScope = null;
  21838. }
  21839. if (block) {
  21840. previousElements = getBlockNodes(block.clone);
  21841. $animate.leave(previousElements).then(function() {
  21842. previousElements = null;
  21843. });
  21844. block = null;
  21845. }
  21846. }
  21847. });
  21848. }
  21849. };
  21850. }];
  21851. /**
  21852. * @ngdoc directive
  21853. * @name ngInclude
  21854. * @restrict ECA
  21855. *
  21856. * @description
  21857. * Fetches, compiles and includes an external HTML fragment.
  21858. *
  21859. * By default, the template URL is restricted to the same domain and protocol as the
  21860. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  21861. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  21862. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  21863. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  21864. * ng.$sce Strict Contextual Escaping}.
  21865. *
  21866. * In addition, the browser's
  21867. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  21868. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  21869. * policy may further restrict whether the template is successfully loaded.
  21870. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  21871. * access on some browsers.
  21872. *
  21873. * @animations
  21874. * enter - animation is used to bring new content into the browser.
  21875. * leave - animation is used to animate existing content away.
  21876. *
  21877. * The enter and leave animation occur concurrently.
  21878. *
  21879. * @scope
  21880. * @priority 400
  21881. *
  21882. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  21883. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  21884. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  21885. *
  21886. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  21887. * $anchorScroll} to scroll the viewport after the content is loaded.
  21888. *
  21889. * - If the attribute is not set, disable scrolling.
  21890. * - If the attribute is set without value, enable scrolling.
  21891. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  21892. *
  21893. * @example
  21894. <example module="includeExample" deps="angular-animate.js" animations="true">
  21895. <file name="index.html">
  21896. <div ng-controller="ExampleController">
  21897. <select ng-model="template" ng-options="t.name for t in templates">
  21898. <option value="">(blank)</option>
  21899. </select>
  21900. url of the template: <code>{{template.url}}</code>
  21901. <hr/>
  21902. <div class="slide-animate-container">
  21903. <div class="slide-animate" ng-include="template.url"></div>
  21904. </div>
  21905. </div>
  21906. </file>
  21907. <file name="script.js">
  21908. angular.module('includeExample', ['ngAnimate'])
  21909. .controller('ExampleController', ['$scope', function($scope) {
  21910. $scope.templates =
  21911. [ { name: 'template1.html', url: 'template1.html'},
  21912. { name: 'template2.html', url: 'template2.html'} ];
  21913. $scope.template = $scope.templates[0];
  21914. }]);
  21915. </file>
  21916. <file name="template1.html">
  21917. Content of template1.html
  21918. </file>
  21919. <file name="template2.html">
  21920. Content of template2.html
  21921. </file>
  21922. <file name="animations.css">
  21923. .slide-animate-container {
  21924. position:relative;
  21925. background:white;
  21926. border:1px solid black;
  21927. height:40px;
  21928. overflow:hidden;
  21929. }
  21930. .slide-animate {
  21931. padding:10px;
  21932. }
  21933. .slide-animate.ng-enter, .slide-animate.ng-leave {
  21934. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21935. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21936. position:absolute;
  21937. top:0;
  21938. left:0;
  21939. right:0;
  21940. bottom:0;
  21941. display:block;
  21942. padding:10px;
  21943. }
  21944. .slide-animate.ng-enter {
  21945. top:-50px;
  21946. }
  21947. .slide-animate.ng-enter.ng-enter-active {
  21948. top:0;
  21949. }
  21950. .slide-animate.ng-leave {
  21951. top:0;
  21952. }
  21953. .slide-animate.ng-leave.ng-leave-active {
  21954. top:50px;
  21955. }
  21956. </file>
  21957. <file name="protractor.js" type="protractor">
  21958. var templateSelect = element(by.model('template'));
  21959. var includeElem = element(by.css('[ng-include]'));
  21960. it('should load template1.html', function() {
  21961. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  21962. });
  21963. it('should load template2.html', function() {
  21964. if (browser.params.browser == 'firefox') {
  21965. // Firefox can't handle using selects
  21966. // See https://github.com/angular/protractor/issues/480
  21967. return;
  21968. }
  21969. templateSelect.click();
  21970. templateSelect.all(by.css('option')).get(2).click();
  21971. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  21972. });
  21973. it('should change to blank', function() {
  21974. if (browser.params.browser == 'firefox') {
  21975. // Firefox can't handle using selects
  21976. return;
  21977. }
  21978. templateSelect.click();
  21979. templateSelect.all(by.css('option')).get(0).click();
  21980. expect(includeElem.isPresent()).toBe(false);
  21981. });
  21982. </file>
  21983. </example>
  21984. */
  21985. /**
  21986. * @ngdoc event
  21987. * @name ngInclude#$includeContentRequested
  21988. * @eventType emit on the scope ngInclude was declared in
  21989. * @description
  21990. * Emitted every time the ngInclude content is requested.
  21991. *
  21992. * @param {Object} angularEvent Synthetic event object.
  21993. * @param {String} src URL of content to load.
  21994. */
  21995. /**
  21996. * @ngdoc event
  21997. * @name ngInclude#$includeContentLoaded
  21998. * @eventType emit on the current ngInclude scope
  21999. * @description
  22000. * Emitted every time the ngInclude content is reloaded.
  22001. *
  22002. * @param {Object} angularEvent Synthetic event object.
  22003. * @param {String} src URL of content to load.
  22004. */
  22005. /**
  22006. * @ngdoc event
  22007. * @name ngInclude#$includeContentError
  22008. * @eventType emit on the scope ngInclude was declared in
  22009. * @description
  22010. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  22011. *
  22012. * @param {Object} angularEvent Synthetic event object.
  22013. * @param {String} src URL of content to load.
  22014. */
  22015. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  22016. function($templateRequest, $anchorScroll, $animate) {
  22017. return {
  22018. restrict: 'ECA',
  22019. priority: 400,
  22020. terminal: true,
  22021. transclude: 'element',
  22022. controller: angular.noop,
  22023. compile: function(element, attr) {
  22024. var srcExp = attr.ngInclude || attr.src,
  22025. onloadExp = attr.onload || '',
  22026. autoScrollExp = attr.autoscroll;
  22027. return function(scope, $element, $attr, ctrl, $transclude) {
  22028. var changeCounter = 0,
  22029. currentScope,
  22030. previousElement,
  22031. currentElement;
  22032. var cleanupLastIncludeContent = function() {
  22033. if (previousElement) {
  22034. previousElement.remove();
  22035. previousElement = null;
  22036. }
  22037. if (currentScope) {
  22038. currentScope.$destroy();
  22039. currentScope = null;
  22040. }
  22041. if (currentElement) {
  22042. $animate.leave(currentElement).then(function() {
  22043. previousElement = null;
  22044. });
  22045. previousElement = currentElement;
  22046. currentElement = null;
  22047. }
  22048. };
  22049. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  22050. var afterAnimation = function() {
  22051. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  22052. $anchorScroll();
  22053. }
  22054. };
  22055. var thisChangeId = ++changeCounter;
  22056. if (src) {
  22057. //set the 2nd param to true to ignore the template request error so that the inner
  22058. //contents and scope can be cleaned up.
  22059. $templateRequest(src, true).then(function(response) {
  22060. if (thisChangeId !== changeCounter) return;
  22061. var newScope = scope.$new();
  22062. ctrl.template = response;
  22063. // Note: This will also link all children of ng-include that were contained in the original
  22064. // html. If that content contains controllers, ... they could pollute/change the scope.
  22065. // However, using ng-include on an element with additional content does not make sense...
  22066. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  22067. // function is called before linking the content, which would apply child
  22068. // directives to non existing elements.
  22069. var clone = $transclude(newScope, function(clone) {
  22070. cleanupLastIncludeContent();
  22071. $animate.enter(clone, null, $element).then(afterAnimation);
  22072. });
  22073. currentScope = newScope;
  22074. currentElement = clone;
  22075. currentScope.$emit('$includeContentLoaded', src);
  22076. scope.$eval(onloadExp);
  22077. }, function() {
  22078. if (thisChangeId === changeCounter) {
  22079. cleanupLastIncludeContent();
  22080. scope.$emit('$includeContentError', src);
  22081. }
  22082. });
  22083. scope.$emit('$includeContentRequested', src);
  22084. } else {
  22085. cleanupLastIncludeContent();
  22086. ctrl.template = null;
  22087. }
  22088. });
  22089. };
  22090. }
  22091. };
  22092. }];
  22093. // This directive is called during the $transclude call of the first `ngInclude` directive.
  22094. // It will replace and compile the content of the element with the loaded template.
  22095. // We need this directive so that the element content is already filled when
  22096. // the link function of another directive on the same element as ngInclude
  22097. // is called.
  22098. var ngIncludeFillContentDirective = ['$compile',
  22099. function($compile) {
  22100. return {
  22101. restrict: 'ECA',
  22102. priority: -400,
  22103. require: 'ngInclude',
  22104. link: function(scope, $element, $attr, ctrl) {
  22105. if (/SVG/.test($element[0].toString())) {
  22106. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  22107. // support innerHTML, so detect this here and try to generate the contents
  22108. // specially.
  22109. $element.empty();
  22110. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  22111. function namespaceAdaptedClone(clone) {
  22112. $element.append(clone);
  22113. }, {futureParentElement: $element});
  22114. return;
  22115. }
  22116. $element.html(ctrl.template);
  22117. $compile($element.contents())(scope);
  22118. }
  22119. };
  22120. }];
  22121. /**
  22122. * @ngdoc directive
  22123. * @name ngInit
  22124. * @restrict AC
  22125. *
  22126. * @description
  22127. * The `ngInit` directive allows you to evaluate an expression in the
  22128. * current scope.
  22129. *
  22130. * <div class="alert alert-danger">
  22131. * The only appropriate use of `ngInit` is for aliasing special properties of
  22132. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  22133. * should use {@link guide/controller controllers} rather than `ngInit`
  22134. * to initialize values on a scope.
  22135. * </div>
  22136. * <div class="alert alert-warning">
  22137. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  22138. * sure you have parenthesis for correct precedence:
  22139. * <pre class="prettyprint">
  22140. * `<div ng-init="test1 = (data | orderBy:'name')"></div>`
  22141. * </pre>
  22142. * </div>
  22143. *
  22144. * @priority 450
  22145. *
  22146. * @element ANY
  22147. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  22148. *
  22149. * @example
  22150. <example module="initExample">
  22151. <file name="index.html">
  22152. <script>
  22153. angular.module('initExample', [])
  22154. .controller('ExampleController', ['$scope', function($scope) {
  22155. $scope.list = [['a', 'b'], ['c', 'd']];
  22156. }]);
  22157. </script>
  22158. <div ng-controller="ExampleController">
  22159. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  22160. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  22161. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  22162. </div>
  22163. </div>
  22164. </div>
  22165. </file>
  22166. <file name="protractor.js" type="protractor">
  22167. it('should alias index positions', function() {
  22168. var elements = element.all(by.css('.example-init'));
  22169. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  22170. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  22171. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  22172. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  22173. });
  22174. </file>
  22175. </example>
  22176. */
  22177. var ngInitDirective = ngDirective({
  22178. priority: 450,
  22179. compile: function() {
  22180. return {
  22181. pre: function(scope, element, attrs) {
  22182. scope.$eval(attrs.ngInit);
  22183. }
  22184. };
  22185. }
  22186. });
  22187. /**
  22188. * @ngdoc directive
  22189. * @name ngList
  22190. *
  22191. * @description
  22192. * Text input that converts between a delimited string and an array of strings. The default
  22193. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  22194. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  22195. *
  22196. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  22197. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  22198. * list item is respected. This implies that the user of the directive is responsible for
  22199. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  22200. * tab or newline character.
  22201. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  22202. * when joining the list items back together) and whitespace around each list item is stripped
  22203. * before it is added to the model.
  22204. *
  22205. * ### Example with Validation
  22206. *
  22207. * <example name="ngList-directive" module="listExample">
  22208. * <file name="app.js">
  22209. * angular.module('listExample', [])
  22210. * .controller('ExampleController', ['$scope', function($scope) {
  22211. * $scope.names = ['morpheus', 'neo', 'trinity'];
  22212. * }]);
  22213. * </file>
  22214. * <file name="index.html">
  22215. * <form name="myForm" ng-controller="ExampleController">
  22216. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  22217. * <span role="alert">
  22218. * <span class="error" ng-show="myForm.namesInput.$error.required">
  22219. * Required!</span>
  22220. * </span>
  22221. * <br>
  22222. * <tt>names = {{names}}</tt><br/>
  22223. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  22224. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  22225. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22226. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22227. * </form>
  22228. * </file>
  22229. * <file name="protractor.js" type="protractor">
  22230. * var listInput = element(by.model('names'));
  22231. * var names = element(by.exactBinding('names'));
  22232. * var valid = element(by.binding('myForm.namesInput.$valid'));
  22233. * var error = element(by.css('span.error'));
  22234. *
  22235. * it('should initialize to model', function() {
  22236. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  22237. * expect(valid.getText()).toContain('true');
  22238. * expect(error.getCssValue('display')).toBe('none');
  22239. * });
  22240. *
  22241. * it('should be invalid if empty', function() {
  22242. * listInput.clear();
  22243. * listInput.sendKeys('');
  22244. *
  22245. * expect(names.getText()).toContain('');
  22246. * expect(valid.getText()).toContain('false');
  22247. * expect(error.getCssValue('display')).not.toBe('none');
  22248. * });
  22249. * </file>
  22250. * </example>
  22251. *
  22252. * ### Example - splitting on whitespace
  22253. * <example name="ngList-directive-newlines">
  22254. * <file name="index.html">
  22255. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  22256. * <pre>{{ list | json }}</pre>
  22257. * </file>
  22258. * <file name="protractor.js" type="protractor">
  22259. * it("should split the text by newlines", function() {
  22260. * var listInput = element(by.model('list'));
  22261. * var output = element(by.binding('list | json'));
  22262. * listInput.sendKeys('abc\ndef\nghi');
  22263. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  22264. * });
  22265. * </file>
  22266. * </example>
  22267. *
  22268. * @element input
  22269. * @param {string=} ngList optional delimiter that should be used to split the value.
  22270. */
  22271. var ngListDirective = function() {
  22272. return {
  22273. restrict: 'A',
  22274. priority: 100,
  22275. require: 'ngModel',
  22276. link: function(scope, element, attr, ctrl) {
  22277. // We want to control whitespace trimming so we use this convoluted approach
  22278. // to access the ngList attribute, which doesn't pre-trim the attribute
  22279. var ngList = element.attr(attr.$attr.ngList) || ', ';
  22280. var trimValues = attr.ngTrim !== 'false';
  22281. var separator = trimValues ? trim(ngList) : ngList;
  22282. var parse = function(viewValue) {
  22283. // If the viewValue is invalid (say required but empty) it will be `undefined`
  22284. if (isUndefined(viewValue)) return;
  22285. var list = [];
  22286. if (viewValue) {
  22287. forEach(viewValue.split(separator), function(value) {
  22288. if (value) list.push(trimValues ? trim(value) : value);
  22289. });
  22290. }
  22291. return list;
  22292. };
  22293. ctrl.$parsers.push(parse);
  22294. ctrl.$formatters.push(function(value) {
  22295. if (isArray(value)) {
  22296. return value.join(ngList);
  22297. }
  22298. return undefined;
  22299. });
  22300. // Override the standard $isEmpty because an empty array means the input is empty.
  22301. ctrl.$isEmpty = function(value) {
  22302. return !value || !value.length;
  22303. };
  22304. }
  22305. };
  22306. };
  22307. /* global VALID_CLASS: true,
  22308. INVALID_CLASS: true,
  22309. PRISTINE_CLASS: true,
  22310. DIRTY_CLASS: true,
  22311. UNTOUCHED_CLASS: true,
  22312. TOUCHED_CLASS: true,
  22313. */
  22314. var VALID_CLASS = 'ng-valid',
  22315. INVALID_CLASS = 'ng-invalid',
  22316. PRISTINE_CLASS = 'ng-pristine',
  22317. DIRTY_CLASS = 'ng-dirty',
  22318. UNTOUCHED_CLASS = 'ng-untouched',
  22319. TOUCHED_CLASS = 'ng-touched',
  22320. PENDING_CLASS = 'ng-pending';
  22321. var ngModelMinErr = minErr('ngModel');
  22322. /**
  22323. * @ngdoc type
  22324. * @name ngModel.NgModelController
  22325. *
  22326. * @property {string} $viewValue Actual string value in the view.
  22327. * @property {*} $modelValue The value in the model that the control is bound to.
  22328. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  22329. the control reads value from the DOM. The functions are called in array order, each passing
  22330. its return value through to the next. The last return value is forwarded to the
  22331. {@link ngModel.NgModelController#$validators `$validators`} collection.
  22332. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  22333. `$viewValue`}.
  22334. Returning `undefined` from a parser means a parse error occurred. In that case,
  22335. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  22336. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  22337. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  22338. *
  22339. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  22340. the model value changes. The functions are called in reverse array order, each passing the value through to the
  22341. next. The last return value is used as the actual DOM value.
  22342. Used to format / convert values for display in the control.
  22343. * ```js
  22344. * function formatter(value) {
  22345. * if (value) {
  22346. * return value.toUpperCase();
  22347. * }
  22348. * }
  22349. * ngModel.$formatters.push(formatter);
  22350. * ```
  22351. *
  22352. * @property {Object.<string, function>} $validators A collection of validators that are applied
  22353. * whenever the model value changes. The key value within the object refers to the name of the
  22354. * validator while the function refers to the validation operation. The validation operation is
  22355. * provided with the model value as an argument and must return a true or false value depending
  22356. * on the response of that validation.
  22357. *
  22358. * ```js
  22359. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  22360. * var value = modelValue || viewValue;
  22361. * return /[0-9]+/.test(value) &&
  22362. * /[a-z]+/.test(value) &&
  22363. * /[A-Z]+/.test(value) &&
  22364. * /\W+/.test(value);
  22365. * };
  22366. * ```
  22367. *
  22368. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  22369. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  22370. * is expected to return a promise when it is run during the model validation process. Once the promise
  22371. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  22372. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  22373. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  22374. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  22375. * will only run once all synchronous validators have passed.
  22376. *
  22377. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  22378. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  22379. *
  22380. * ```js
  22381. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  22382. * var value = modelValue || viewValue;
  22383. *
  22384. * // Lookup user by username
  22385. * return $http.get('/api/users/' + value).
  22386. * then(function resolved() {
  22387. * //username exists, this means validation fails
  22388. * return $q.reject('exists');
  22389. * }, function rejected() {
  22390. * //username does not exist, therefore this validation passes
  22391. * return true;
  22392. * });
  22393. * };
  22394. * ```
  22395. *
  22396. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  22397. * view value has changed. It is called with no arguments, and its return value is ignored.
  22398. * This can be used in place of additional $watches against the model value.
  22399. *
  22400. * @property {Object} $error An object hash with all failing validator ids as keys.
  22401. * @property {Object} $pending An object hash with all pending validator ids as keys.
  22402. *
  22403. * @property {boolean} $untouched True if control has not lost focus yet.
  22404. * @property {boolean} $touched True if control has lost focus.
  22405. * @property {boolean} $pristine True if user has not interacted with the control yet.
  22406. * @property {boolean} $dirty True if user has already interacted with the control.
  22407. * @property {boolean} $valid True if there is no error.
  22408. * @property {boolean} $invalid True if at least one error on the control.
  22409. * @property {string} $name The name attribute of the control.
  22410. *
  22411. * @description
  22412. *
  22413. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  22414. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  22415. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  22416. * listening to DOM events.
  22417. * Such DOM related logic should be provided by other directives which make use of
  22418. * `NgModelController` for data-binding to control elements.
  22419. * Angular provides this DOM logic for most {@link input `input`} elements.
  22420. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  22421. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  22422. *
  22423. * @example
  22424. * ### Custom Control Example
  22425. * This example shows how to use `NgModelController` with a custom control to achieve
  22426. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  22427. * collaborate together to achieve the desired result.
  22428. *
  22429. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  22430. * contents be edited in place by the user.
  22431. *
  22432. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  22433. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  22434. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  22435. * that content using the `$sce` service.
  22436. *
  22437. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  22438. <file name="style.css">
  22439. [contenteditable] {
  22440. border: 1px solid black;
  22441. background-color: white;
  22442. min-height: 20px;
  22443. }
  22444. .ng-invalid {
  22445. border: 1px solid red;
  22446. }
  22447. </file>
  22448. <file name="script.js">
  22449. angular.module('customControl', ['ngSanitize']).
  22450. directive('contenteditable', ['$sce', function($sce) {
  22451. return {
  22452. restrict: 'A', // only activate on element attribute
  22453. require: '?ngModel', // get a hold of NgModelController
  22454. link: function(scope, element, attrs, ngModel) {
  22455. if (!ngModel) return; // do nothing if no ng-model
  22456. // Specify how UI should be updated
  22457. ngModel.$render = function() {
  22458. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  22459. };
  22460. // Listen for change events to enable binding
  22461. element.on('blur keyup change', function() {
  22462. scope.$evalAsync(read);
  22463. });
  22464. read(); // initialize
  22465. // Write data to the model
  22466. function read() {
  22467. var html = element.html();
  22468. // When we clear the content editable the browser leaves a <br> behind
  22469. // If strip-br attribute is provided then we strip this out
  22470. if ( attrs.stripBr && html == '<br>' ) {
  22471. html = '';
  22472. }
  22473. ngModel.$setViewValue(html);
  22474. }
  22475. }
  22476. };
  22477. }]);
  22478. </file>
  22479. <file name="index.html">
  22480. <form name="myForm">
  22481. <div contenteditable
  22482. name="myWidget" ng-model="userContent"
  22483. strip-br="true"
  22484. required>Change me!</div>
  22485. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  22486. <hr>
  22487. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  22488. </form>
  22489. </file>
  22490. <file name="protractor.js" type="protractor">
  22491. it('should data-bind and become invalid', function() {
  22492. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  22493. // SafariDriver can't handle contenteditable
  22494. // and Firefox driver can't clear contenteditables very well
  22495. return;
  22496. }
  22497. var contentEditable = element(by.css('[contenteditable]'));
  22498. var content = 'Change me!';
  22499. expect(contentEditable.getText()).toEqual(content);
  22500. contentEditable.clear();
  22501. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  22502. expect(contentEditable.getText()).toEqual('');
  22503. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  22504. });
  22505. </file>
  22506. * </example>
  22507. *
  22508. *
  22509. */
  22510. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  22511. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  22512. this.$viewValue = Number.NaN;
  22513. this.$modelValue = Number.NaN;
  22514. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  22515. this.$validators = {};
  22516. this.$asyncValidators = {};
  22517. this.$parsers = [];
  22518. this.$formatters = [];
  22519. this.$viewChangeListeners = [];
  22520. this.$untouched = true;
  22521. this.$touched = false;
  22522. this.$pristine = true;
  22523. this.$dirty = false;
  22524. this.$valid = true;
  22525. this.$invalid = false;
  22526. this.$error = {}; // keep invalid keys here
  22527. this.$$success = {}; // keep valid keys here
  22528. this.$pending = undefined; // keep pending keys here
  22529. this.$name = $interpolate($attr.name || '', false)($scope);
  22530. var parsedNgModel = $parse($attr.ngModel),
  22531. parsedNgModelAssign = parsedNgModel.assign,
  22532. ngModelGet = parsedNgModel,
  22533. ngModelSet = parsedNgModelAssign,
  22534. pendingDebounce = null,
  22535. parserValid,
  22536. ctrl = this;
  22537. this.$$setOptions = function(options) {
  22538. ctrl.$options = options;
  22539. if (options && options.getterSetter) {
  22540. var invokeModelGetter = $parse($attr.ngModel + '()'),
  22541. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  22542. ngModelGet = function($scope) {
  22543. var modelValue = parsedNgModel($scope);
  22544. if (isFunction(modelValue)) {
  22545. modelValue = invokeModelGetter($scope);
  22546. }
  22547. return modelValue;
  22548. };
  22549. ngModelSet = function($scope, newValue) {
  22550. if (isFunction(parsedNgModel($scope))) {
  22551. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  22552. } else {
  22553. parsedNgModelAssign($scope, ctrl.$modelValue);
  22554. }
  22555. };
  22556. } else if (!parsedNgModel.assign) {
  22557. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  22558. $attr.ngModel, startingTag($element));
  22559. }
  22560. };
  22561. /**
  22562. * @ngdoc method
  22563. * @name ngModel.NgModelController#$render
  22564. *
  22565. * @description
  22566. * Called when the view needs to be updated. It is expected that the user of the ng-model
  22567. * directive will implement this method.
  22568. *
  22569. * The `$render()` method is invoked in the following situations:
  22570. *
  22571. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  22572. * committed value then `$render()` is called to update the input control.
  22573. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  22574. * the `$viewValue` are different from last time.
  22575. *
  22576. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  22577. * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
  22578. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  22579. * invoked if you only change a property on the objects.
  22580. */
  22581. this.$render = noop;
  22582. /**
  22583. * @ngdoc method
  22584. * @name ngModel.NgModelController#$isEmpty
  22585. *
  22586. * @description
  22587. * This is called when we need to determine if the value of an input is empty.
  22588. *
  22589. * For instance, the required directive does this to work out if the input has data or not.
  22590. *
  22591. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  22592. *
  22593. * You can override this for input directives whose concept of being empty is different from the
  22594. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  22595. * implies empty.
  22596. *
  22597. * @param {*} value The value of the input to check for emptiness.
  22598. * @returns {boolean} True if `value` is "empty".
  22599. */
  22600. this.$isEmpty = function(value) {
  22601. return isUndefined(value) || value === '' || value === null || value !== value;
  22602. };
  22603. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  22604. currentValidationRunId = 0;
  22605. /**
  22606. * @ngdoc method
  22607. * @name ngModel.NgModelController#$setValidity
  22608. *
  22609. * @description
  22610. * Change the validity state, and notify the form.
  22611. *
  22612. * This method can be called within $parsers/$formatters or a custom validation implementation.
  22613. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  22614. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  22615. *
  22616. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  22617. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  22618. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  22619. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  22620. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  22621. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  22622. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  22623. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  22624. * Skipped is used by Angular when validators do not run because of parse errors and
  22625. * when `$asyncValidators` do not run because any of the `$validators` failed.
  22626. */
  22627. addSetValidityMethod({
  22628. ctrl: this,
  22629. $element: $element,
  22630. set: function(object, property) {
  22631. object[property] = true;
  22632. },
  22633. unset: function(object, property) {
  22634. delete object[property];
  22635. },
  22636. parentForm: parentForm,
  22637. $animate: $animate
  22638. });
  22639. /**
  22640. * @ngdoc method
  22641. * @name ngModel.NgModelController#$setPristine
  22642. *
  22643. * @description
  22644. * Sets the control to its pristine state.
  22645. *
  22646. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  22647. * state (`ng-pristine` class). A model is considered to be pristine when the control
  22648. * has not been changed from when first compiled.
  22649. */
  22650. this.$setPristine = function() {
  22651. ctrl.$dirty = false;
  22652. ctrl.$pristine = true;
  22653. $animate.removeClass($element, DIRTY_CLASS);
  22654. $animate.addClass($element, PRISTINE_CLASS);
  22655. };
  22656. /**
  22657. * @ngdoc method
  22658. * @name ngModel.NgModelController#$setDirty
  22659. *
  22660. * @description
  22661. * Sets the control to its dirty state.
  22662. *
  22663. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  22664. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  22665. * from when first compiled.
  22666. */
  22667. this.$setDirty = function() {
  22668. ctrl.$dirty = true;
  22669. ctrl.$pristine = false;
  22670. $animate.removeClass($element, PRISTINE_CLASS);
  22671. $animate.addClass($element, DIRTY_CLASS);
  22672. parentForm.$setDirty();
  22673. };
  22674. /**
  22675. * @ngdoc method
  22676. * @name ngModel.NgModelController#$setUntouched
  22677. *
  22678. * @description
  22679. * Sets the control to its untouched state.
  22680. *
  22681. * This method can be called to remove the `ng-touched` class and set the control to its
  22682. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  22683. * by default, however this function can be used to restore that state if the model has
  22684. * already been touched by the user.
  22685. */
  22686. this.$setUntouched = function() {
  22687. ctrl.$touched = false;
  22688. ctrl.$untouched = true;
  22689. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  22690. };
  22691. /**
  22692. * @ngdoc method
  22693. * @name ngModel.NgModelController#$setTouched
  22694. *
  22695. * @description
  22696. * Sets the control to its touched state.
  22697. *
  22698. * This method can be called to remove the `ng-untouched` class and set the control to its
  22699. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  22700. * first focused the control element and then shifted focus away from the control (blur event).
  22701. */
  22702. this.$setTouched = function() {
  22703. ctrl.$touched = true;
  22704. ctrl.$untouched = false;
  22705. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  22706. };
  22707. /**
  22708. * @ngdoc method
  22709. * @name ngModel.NgModelController#$rollbackViewValue
  22710. *
  22711. * @description
  22712. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  22713. * which may be caused by a pending debounced event or because the input is waiting for a some
  22714. * future event.
  22715. *
  22716. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  22717. * as blur you can have a situation where there is a period when the `$viewValue`
  22718. * is out of synch with the ngModel's `$modelValue`.
  22719. *
  22720. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  22721. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  22722. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  22723. *
  22724. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  22725. * input which may have such events pending. This is important in order to make sure that the
  22726. * input field will be updated with the new model value and any pending operations are cancelled.
  22727. *
  22728. * <example name="ng-model-cancel-update" module="cancel-update-example">
  22729. * <file name="app.js">
  22730. * angular.module('cancel-update-example', [])
  22731. *
  22732. * .controller('CancelUpdateController', ['$scope', function($scope) {
  22733. * $scope.resetWithCancel = function(e) {
  22734. * if (e.keyCode == 27) {
  22735. * $scope.myForm.myInput1.$rollbackViewValue();
  22736. * $scope.myValue = '';
  22737. * }
  22738. * };
  22739. * $scope.resetWithoutCancel = function(e) {
  22740. * if (e.keyCode == 27) {
  22741. * $scope.myValue = '';
  22742. * }
  22743. * };
  22744. * }]);
  22745. * </file>
  22746. * <file name="index.html">
  22747. * <div ng-controller="CancelUpdateController">
  22748. * <p>Try typing something in each input. See that the model only updates when you
  22749. * blur off the input.
  22750. * </p>
  22751. * <p>Now see what happens if you start typing then press the Escape key</p>
  22752. *
  22753. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  22754. * <p id="inputDescription1">With $rollbackViewValue()</p>
  22755. * <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
  22756. * ng-keydown="resetWithCancel($event)"><br/>
  22757. * myValue: "{{ myValue }}"
  22758. *
  22759. * <p id="inputDescription2">Without $rollbackViewValue()</p>
  22760. * <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
  22761. * ng-keydown="resetWithoutCancel($event)"><br/>
  22762. * myValue: "{{ myValue }}"
  22763. * </form>
  22764. * </div>
  22765. * </file>
  22766. * </example>
  22767. */
  22768. this.$rollbackViewValue = function() {
  22769. $timeout.cancel(pendingDebounce);
  22770. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  22771. ctrl.$render();
  22772. };
  22773. /**
  22774. * @ngdoc method
  22775. * @name ngModel.NgModelController#$validate
  22776. *
  22777. * @description
  22778. * Runs each of the registered validators (first synchronous validators and then
  22779. * asynchronous validators).
  22780. * If the validity changes to invalid, the model will be set to `undefined`,
  22781. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  22782. * If the validity changes to valid, it will set the model to the last available valid
  22783. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  22784. */
  22785. this.$validate = function() {
  22786. // ignore $validate before model is initialized
  22787. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22788. return;
  22789. }
  22790. var viewValue = ctrl.$$lastCommittedViewValue;
  22791. // Note: we use the $$rawModelValue as $modelValue might have been
  22792. // set to undefined during a view -> model update that found validation
  22793. // errors. We can't parse the view here, since that could change
  22794. // the model although neither viewValue nor the model on the scope changed
  22795. var modelValue = ctrl.$$rawModelValue;
  22796. var prevValid = ctrl.$valid;
  22797. var prevModelValue = ctrl.$modelValue;
  22798. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22799. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  22800. // If there was no change in validity, don't update the model
  22801. // This prevents changing an invalid modelValue to undefined
  22802. if (!allowInvalid && prevValid !== allValid) {
  22803. // Note: Don't check ctrl.$valid here, as we could have
  22804. // external validators (e.g. calculated on the server),
  22805. // that just call $setValidity and need the model value
  22806. // to calculate their validity.
  22807. ctrl.$modelValue = allValid ? modelValue : undefined;
  22808. if (ctrl.$modelValue !== prevModelValue) {
  22809. ctrl.$$writeModelToScope();
  22810. }
  22811. }
  22812. });
  22813. };
  22814. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  22815. currentValidationRunId++;
  22816. var localValidationRunId = currentValidationRunId;
  22817. // check parser error
  22818. if (!processParseErrors()) {
  22819. validationDone(false);
  22820. return;
  22821. }
  22822. if (!processSyncValidators()) {
  22823. validationDone(false);
  22824. return;
  22825. }
  22826. processAsyncValidators();
  22827. function processParseErrors() {
  22828. var errorKey = ctrl.$$parserName || 'parse';
  22829. if (parserValid === undefined) {
  22830. setValidity(errorKey, null);
  22831. } else {
  22832. if (!parserValid) {
  22833. forEach(ctrl.$validators, function(v, name) {
  22834. setValidity(name, null);
  22835. });
  22836. forEach(ctrl.$asyncValidators, function(v, name) {
  22837. setValidity(name, null);
  22838. });
  22839. }
  22840. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  22841. setValidity(errorKey, parserValid);
  22842. return parserValid;
  22843. }
  22844. return true;
  22845. }
  22846. function processSyncValidators() {
  22847. var syncValidatorsValid = true;
  22848. forEach(ctrl.$validators, function(validator, name) {
  22849. var result = validator(modelValue, viewValue);
  22850. syncValidatorsValid = syncValidatorsValid && result;
  22851. setValidity(name, result);
  22852. });
  22853. if (!syncValidatorsValid) {
  22854. forEach(ctrl.$asyncValidators, function(v, name) {
  22855. setValidity(name, null);
  22856. });
  22857. return false;
  22858. }
  22859. return true;
  22860. }
  22861. function processAsyncValidators() {
  22862. var validatorPromises = [];
  22863. var allValid = true;
  22864. forEach(ctrl.$asyncValidators, function(validator, name) {
  22865. var promise = validator(modelValue, viewValue);
  22866. if (!isPromiseLike(promise)) {
  22867. throw ngModelMinErr("$asyncValidators",
  22868. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  22869. }
  22870. setValidity(name, undefined);
  22871. validatorPromises.push(promise.then(function() {
  22872. setValidity(name, true);
  22873. }, function(error) {
  22874. allValid = false;
  22875. setValidity(name, false);
  22876. }));
  22877. });
  22878. if (!validatorPromises.length) {
  22879. validationDone(true);
  22880. } else {
  22881. $q.all(validatorPromises).then(function() {
  22882. validationDone(allValid);
  22883. }, noop);
  22884. }
  22885. }
  22886. function setValidity(name, isValid) {
  22887. if (localValidationRunId === currentValidationRunId) {
  22888. ctrl.$setValidity(name, isValid);
  22889. }
  22890. }
  22891. function validationDone(allValid) {
  22892. if (localValidationRunId === currentValidationRunId) {
  22893. doneCallback(allValid);
  22894. }
  22895. }
  22896. };
  22897. /**
  22898. * @ngdoc method
  22899. * @name ngModel.NgModelController#$commitViewValue
  22900. *
  22901. * @description
  22902. * Commit a pending update to the `$modelValue`.
  22903. *
  22904. * Updates may be pending by a debounced event or because the input is waiting for a some future
  22905. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  22906. * usually handles calling this in response to input events.
  22907. */
  22908. this.$commitViewValue = function() {
  22909. var viewValue = ctrl.$viewValue;
  22910. $timeout.cancel(pendingDebounce);
  22911. // If the view value has not changed then we should just exit, except in the case where there is
  22912. // a native validator on the element. In this case the validation state may have changed even though
  22913. // the viewValue has stayed empty.
  22914. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  22915. return;
  22916. }
  22917. ctrl.$$lastCommittedViewValue = viewValue;
  22918. // change to dirty
  22919. if (ctrl.$pristine) {
  22920. this.$setDirty();
  22921. }
  22922. this.$$parseAndValidate();
  22923. };
  22924. this.$$parseAndValidate = function() {
  22925. var viewValue = ctrl.$$lastCommittedViewValue;
  22926. var modelValue = viewValue;
  22927. parserValid = isUndefined(modelValue) ? undefined : true;
  22928. if (parserValid) {
  22929. for (var i = 0; i < ctrl.$parsers.length; i++) {
  22930. modelValue = ctrl.$parsers[i](modelValue);
  22931. if (isUndefined(modelValue)) {
  22932. parserValid = false;
  22933. break;
  22934. }
  22935. }
  22936. }
  22937. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22938. // ctrl.$modelValue has not been touched yet...
  22939. ctrl.$modelValue = ngModelGet($scope);
  22940. }
  22941. var prevModelValue = ctrl.$modelValue;
  22942. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22943. ctrl.$$rawModelValue = modelValue;
  22944. if (allowInvalid) {
  22945. ctrl.$modelValue = modelValue;
  22946. writeToModelIfNeeded();
  22947. }
  22948. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  22949. // This can happen if e.g. $setViewValue is called from inside a parser
  22950. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  22951. if (!allowInvalid) {
  22952. // Note: Don't check ctrl.$valid here, as we could have
  22953. // external validators (e.g. calculated on the server),
  22954. // that just call $setValidity and need the model value
  22955. // to calculate their validity.
  22956. ctrl.$modelValue = allValid ? modelValue : undefined;
  22957. writeToModelIfNeeded();
  22958. }
  22959. });
  22960. function writeToModelIfNeeded() {
  22961. if (ctrl.$modelValue !== prevModelValue) {
  22962. ctrl.$$writeModelToScope();
  22963. }
  22964. }
  22965. };
  22966. this.$$writeModelToScope = function() {
  22967. ngModelSet($scope, ctrl.$modelValue);
  22968. forEach(ctrl.$viewChangeListeners, function(listener) {
  22969. try {
  22970. listener();
  22971. } catch (e) {
  22972. $exceptionHandler(e);
  22973. }
  22974. });
  22975. };
  22976. /**
  22977. * @ngdoc method
  22978. * @name ngModel.NgModelController#$setViewValue
  22979. *
  22980. * @description
  22981. * Update the view value.
  22982. *
  22983. * This method should be called when an input directive want to change the view value; typically,
  22984. * this is done from within a DOM event handler.
  22985. *
  22986. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  22987. * {@link ng.directive:select select} calls it when an option is selected.
  22988. *
  22989. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  22990. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  22991. * watch of objects, it only looks for a change of identity. If you only change the property of
  22992. * the object then ngModel will not realise that the object has changed and will not invoke the
  22993. * `$parsers` and `$validators` pipelines.
  22994. *
  22995. * For this reason, you should not change properties of the copy once it has been passed to
  22996. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  22997. *
  22998. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  22999. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  23000. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  23001. * **expression** specified in the `ng-model` attribute.
  23002. *
  23003. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  23004. *
  23005. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  23006. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  23007. * `updateOn` events is triggered on the DOM element.
  23008. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  23009. * directive is used with a custom debounce for this particular event.
  23010. *
  23011. * Note that calling this function does not trigger a `$digest`.
  23012. *
  23013. * @param {string} value Value from the view.
  23014. * @param {string} trigger Event that triggered the update.
  23015. */
  23016. this.$setViewValue = function(value, trigger) {
  23017. ctrl.$viewValue = value;
  23018. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  23019. ctrl.$$debounceViewValueCommit(trigger);
  23020. }
  23021. };
  23022. this.$$debounceViewValueCommit = function(trigger) {
  23023. var debounceDelay = 0,
  23024. options = ctrl.$options,
  23025. debounce;
  23026. if (options && isDefined(options.debounce)) {
  23027. debounce = options.debounce;
  23028. if (isNumber(debounce)) {
  23029. debounceDelay = debounce;
  23030. } else if (isNumber(debounce[trigger])) {
  23031. debounceDelay = debounce[trigger];
  23032. } else if (isNumber(debounce['default'])) {
  23033. debounceDelay = debounce['default'];
  23034. }
  23035. }
  23036. $timeout.cancel(pendingDebounce);
  23037. if (debounceDelay) {
  23038. pendingDebounce = $timeout(function() {
  23039. ctrl.$commitViewValue();
  23040. }, debounceDelay);
  23041. } else if ($rootScope.$$phase) {
  23042. ctrl.$commitViewValue();
  23043. } else {
  23044. $scope.$apply(function() {
  23045. ctrl.$commitViewValue();
  23046. });
  23047. }
  23048. };
  23049. // model -> value
  23050. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  23051. // 1. scope value is 'a'
  23052. // 2. user enters 'b'
  23053. // 3. ng-change kicks in and reverts scope value to 'a'
  23054. // -> scope value did not change since the last digest as
  23055. // ng-change executes in apply phase
  23056. // 4. view should be changed back to 'a'
  23057. $scope.$watch(function ngModelWatch() {
  23058. var modelValue = ngModelGet($scope);
  23059. // if scope model value and ngModel value are out of sync
  23060. // TODO(perf): why not move this to the action fn?
  23061. if (modelValue !== ctrl.$modelValue &&
  23062. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  23063. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  23064. ) {
  23065. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  23066. parserValid = undefined;
  23067. var formatters = ctrl.$formatters,
  23068. idx = formatters.length;
  23069. var viewValue = modelValue;
  23070. while (idx--) {
  23071. viewValue = formatters[idx](viewValue);
  23072. }
  23073. if (ctrl.$viewValue !== viewValue) {
  23074. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  23075. ctrl.$render();
  23076. ctrl.$$runValidators(modelValue, viewValue, noop);
  23077. }
  23078. }
  23079. return modelValue;
  23080. });
  23081. }];
  23082. /**
  23083. * @ngdoc directive
  23084. * @name ngModel
  23085. *
  23086. * @element input
  23087. * @priority 1
  23088. *
  23089. * @description
  23090. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  23091. * property on the scope using {@link ngModel.NgModelController NgModelController},
  23092. * which is created and exposed by this directive.
  23093. *
  23094. * `ngModel` is responsible for:
  23095. *
  23096. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  23097. * require.
  23098. * - Providing validation behavior (i.e. required, number, email, url).
  23099. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  23100. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  23101. * - Registering the control with its parent {@link ng.directive:form form}.
  23102. *
  23103. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  23104. * current scope. If the property doesn't already exist on this scope, it will be created
  23105. * implicitly and added to the scope.
  23106. *
  23107. * For best practices on using `ngModel`, see:
  23108. *
  23109. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  23110. *
  23111. * For basic examples, how to use `ngModel`, see:
  23112. *
  23113. * - {@link ng.directive:input input}
  23114. * - {@link input[text] text}
  23115. * - {@link input[checkbox] checkbox}
  23116. * - {@link input[radio] radio}
  23117. * - {@link input[number] number}
  23118. * - {@link input[email] email}
  23119. * - {@link input[url] url}
  23120. * - {@link input[date] date}
  23121. * - {@link input[datetime-local] datetime-local}
  23122. * - {@link input[time] time}
  23123. * - {@link input[month] month}
  23124. * - {@link input[week] week}
  23125. * - {@link ng.directive:select select}
  23126. * - {@link ng.directive:textarea textarea}
  23127. *
  23128. * # CSS classes
  23129. * The following CSS classes are added and removed on the associated input/select/textarea element
  23130. * depending on the validity of the model.
  23131. *
  23132. * - `ng-valid`: the model is valid
  23133. * - `ng-invalid`: the model is invalid
  23134. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  23135. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  23136. * - `ng-pristine`: the control hasn't been interacted with yet
  23137. * - `ng-dirty`: the control has been interacted with
  23138. * - `ng-touched`: the control has been blurred
  23139. * - `ng-untouched`: the control hasn't been blurred
  23140. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  23141. *
  23142. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  23143. *
  23144. * ## Animation Hooks
  23145. *
  23146. * Animations within models are triggered when any of the associated CSS classes are added and removed
  23147. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  23148. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  23149. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  23150. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  23151. *
  23152. * The following example shows a simple way to utilize CSS transitions to style an input element
  23153. * that has been rendered as invalid after it has been validated:
  23154. *
  23155. * <pre>
  23156. * //be sure to include ngAnimate as a module to hook into more
  23157. * //advanced animations
  23158. * .my-input {
  23159. * transition:0.5s linear all;
  23160. * background: white;
  23161. * }
  23162. * .my-input.ng-invalid {
  23163. * background: red;
  23164. * color:white;
  23165. * }
  23166. * </pre>
  23167. *
  23168. * @example
  23169. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  23170. <file name="index.html">
  23171. <script>
  23172. angular.module('inputExample', [])
  23173. .controller('ExampleController', ['$scope', function($scope) {
  23174. $scope.val = '1';
  23175. }]);
  23176. </script>
  23177. <style>
  23178. .my-input {
  23179. -webkit-transition:all linear 0.5s;
  23180. transition:all linear 0.5s;
  23181. background: transparent;
  23182. }
  23183. .my-input.ng-invalid {
  23184. color:white;
  23185. background: red;
  23186. }
  23187. </style>
  23188. <p id="inputDescription">
  23189. Update input to see transitions when valid/invalid.
  23190. Integer is a valid value.
  23191. </p>
  23192. <form name="testForm" ng-controller="ExampleController">
  23193. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  23194. aria-describedby="inputDescription" />
  23195. </form>
  23196. </file>
  23197. * </example>
  23198. *
  23199. * ## Binding to a getter/setter
  23200. *
  23201. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  23202. * function that returns a representation of the model when called with zero arguments, and sets
  23203. * the internal state of a model when called with an argument. It's sometimes useful to use this
  23204. * for models that have an internal representation that's different from what the model exposes
  23205. * to the view.
  23206. *
  23207. * <div class="alert alert-success">
  23208. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  23209. * frequently than other parts of your code.
  23210. * </div>
  23211. *
  23212. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  23213. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  23214. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  23215. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  23216. *
  23217. * The following example shows how to use `ngModel` with a getter/setter:
  23218. *
  23219. * @example
  23220. * <example name="ngModel-getter-setter" module="getterSetterExample">
  23221. <file name="index.html">
  23222. <div ng-controller="ExampleController">
  23223. <form name="userForm">
  23224. <label>Name:
  23225. <input type="text" name="userName"
  23226. ng-model="user.name"
  23227. ng-model-options="{ getterSetter: true }" />
  23228. </label>
  23229. </form>
  23230. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23231. </div>
  23232. </file>
  23233. <file name="app.js">
  23234. angular.module('getterSetterExample', [])
  23235. .controller('ExampleController', ['$scope', function($scope) {
  23236. var _name = 'Brian';
  23237. $scope.user = {
  23238. name: function(newName) {
  23239. // Note that newName can be undefined for two reasons:
  23240. // 1. Because it is called as a getter and thus called with no arguments
  23241. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23242. // input is invalid
  23243. return arguments.length ? (_name = newName) : _name;
  23244. }
  23245. };
  23246. }]);
  23247. </file>
  23248. * </example>
  23249. */
  23250. var ngModelDirective = ['$rootScope', function($rootScope) {
  23251. return {
  23252. restrict: 'A',
  23253. require: ['ngModel', '^?form', '^?ngModelOptions'],
  23254. controller: NgModelController,
  23255. // Prelink needs to run before any input directive
  23256. // so that we can set the NgModelOptions in NgModelController
  23257. // before anyone else uses it.
  23258. priority: 1,
  23259. compile: function ngModelCompile(element) {
  23260. // Setup initial state of the control
  23261. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  23262. return {
  23263. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  23264. var modelCtrl = ctrls[0],
  23265. formCtrl = ctrls[1] || nullFormCtrl;
  23266. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  23267. // notify others, especially parent forms
  23268. formCtrl.$addControl(modelCtrl);
  23269. attr.$observe('name', function(newValue) {
  23270. if (modelCtrl.$name !== newValue) {
  23271. formCtrl.$$renameControl(modelCtrl, newValue);
  23272. }
  23273. });
  23274. scope.$on('$destroy', function() {
  23275. formCtrl.$removeControl(modelCtrl);
  23276. });
  23277. },
  23278. post: function ngModelPostLink(scope, element, attr, ctrls) {
  23279. var modelCtrl = ctrls[0];
  23280. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  23281. element.on(modelCtrl.$options.updateOn, function(ev) {
  23282. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  23283. });
  23284. }
  23285. element.on('blur', function(ev) {
  23286. if (modelCtrl.$touched) return;
  23287. if ($rootScope.$$phase) {
  23288. scope.$evalAsync(modelCtrl.$setTouched);
  23289. } else {
  23290. scope.$apply(modelCtrl.$setTouched);
  23291. }
  23292. });
  23293. }
  23294. };
  23295. }
  23296. };
  23297. }];
  23298. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  23299. /**
  23300. * @ngdoc directive
  23301. * @name ngModelOptions
  23302. *
  23303. * @description
  23304. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  23305. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  23306. * takes place when a timer expires; this timer will be reset after another change takes place.
  23307. *
  23308. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  23309. * be different from the value in the actual model. This means that if you update the model you
  23310. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  23311. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  23312. *
  23313. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  23314. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  23315. * important because `form` controllers are published to the related scope under the name in their
  23316. * `name` attribute.
  23317. *
  23318. * Any pending changes will take place immediately when an enclosing form is submitted via the
  23319. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  23320. * to have access to the updated model.
  23321. *
  23322. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  23323. *
  23324. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  23325. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  23326. * events using an space delimited list. There is a special event called `default` that
  23327. * matches the default events belonging of the control.
  23328. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  23329. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  23330. * custom value for each event. For example:
  23331. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  23332. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  23333. * not validate correctly instead of the default behavior of setting the model to undefined.
  23334. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  23335. `ngModel` as getters/setters.
  23336. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  23337. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  23338. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  23339. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  23340. * If not specified, the timezone of the browser will be used.
  23341. *
  23342. * @example
  23343. The following example shows how to override immediate updates. Changes on the inputs within the
  23344. form will update the model only when the control loses focus (blur event). If `escape` key is
  23345. pressed while the input field is focused, the value is reset to the value in the current model.
  23346. <example name="ngModelOptions-directive-blur" module="optionsExample">
  23347. <file name="index.html">
  23348. <div ng-controller="ExampleController">
  23349. <form name="userForm">
  23350. <label>Name:
  23351. <input type="text" name="userName"
  23352. ng-model="user.name"
  23353. ng-model-options="{ updateOn: 'blur' }"
  23354. ng-keyup="cancel($event)" />
  23355. </label><br />
  23356. <label>Other data:
  23357. <input type="text" ng-model="user.data" />
  23358. </label><br />
  23359. </form>
  23360. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23361. </div>
  23362. </file>
  23363. <file name="app.js">
  23364. angular.module('optionsExample', [])
  23365. .controller('ExampleController', ['$scope', function($scope) {
  23366. $scope.user = { name: 'say', data: '' };
  23367. $scope.cancel = function(e) {
  23368. if (e.keyCode == 27) {
  23369. $scope.userForm.userName.$rollbackViewValue();
  23370. }
  23371. };
  23372. }]);
  23373. </file>
  23374. <file name="protractor.js" type="protractor">
  23375. var model = element(by.binding('user.name'));
  23376. var input = element(by.model('user.name'));
  23377. var other = element(by.model('user.data'));
  23378. it('should allow custom events', function() {
  23379. input.sendKeys(' hello');
  23380. input.click();
  23381. expect(model.getText()).toEqual('say');
  23382. other.click();
  23383. expect(model.getText()).toEqual('say hello');
  23384. });
  23385. it('should $rollbackViewValue when model changes', function() {
  23386. input.sendKeys(' hello');
  23387. expect(input.getAttribute('value')).toEqual('say hello');
  23388. input.sendKeys(protractor.Key.ESCAPE);
  23389. expect(input.getAttribute('value')).toEqual('say');
  23390. other.click();
  23391. expect(model.getText()).toEqual('say');
  23392. });
  23393. </file>
  23394. </example>
  23395. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  23396. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  23397. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  23398. <file name="index.html">
  23399. <div ng-controller="ExampleController">
  23400. <form name="userForm">
  23401. <label>Name:
  23402. <input type="text" name="userName"
  23403. ng-model="user.name"
  23404. ng-model-options="{ debounce: 1000 }" />
  23405. </label>
  23406. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  23407. <br />
  23408. </form>
  23409. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23410. </div>
  23411. </file>
  23412. <file name="app.js">
  23413. angular.module('optionsExample', [])
  23414. .controller('ExampleController', ['$scope', function($scope) {
  23415. $scope.user = { name: 'say' };
  23416. }]);
  23417. </file>
  23418. </example>
  23419. This one shows how to bind to getter/setters:
  23420. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  23421. <file name="index.html">
  23422. <div ng-controller="ExampleController">
  23423. <form name="userForm">
  23424. <label>Name:
  23425. <input type="text" name="userName"
  23426. ng-model="user.name"
  23427. ng-model-options="{ getterSetter: true }" />
  23428. </label>
  23429. </form>
  23430. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23431. </div>
  23432. </file>
  23433. <file name="app.js">
  23434. angular.module('getterSetterExample', [])
  23435. .controller('ExampleController', ['$scope', function($scope) {
  23436. var _name = 'Brian';
  23437. $scope.user = {
  23438. name: function(newName) {
  23439. // Note that newName can be undefined for two reasons:
  23440. // 1. Because it is called as a getter and thus called with no arguments
  23441. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23442. // input is invalid
  23443. return arguments.length ? (_name = newName) : _name;
  23444. }
  23445. };
  23446. }]);
  23447. </file>
  23448. </example>
  23449. */
  23450. var ngModelOptionsDirective = function() {
  23451. return {
  23452. restrict: 'A',
  23453. controller: ['$scope', '$attrs', function($scope, $attrs) {
  23454. var that = this;
  23455. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  23456. // Allow adding/overriding bound events
  23457. if (this.$options.updateOn !== undefined) {
  23458. this.$options.updateOnDefault = false;
  23459. // extract "default" pseudo-event from list of events that can trigger a model update
  23460. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  23461. that.$options.updateOnDefault = true;
  23462. return ' ';
  23463. }));
  23464. } else {
  23465. this.$options.updateOnDefault = true;
  23466. }
  23467. }]
  23468. };
  23469. };
  23470. // helper methods
  23471. function addSetValidityMethod(context) {
  23472. var ctrl = context.ctrl,
  23473. $element = context.$element,
  23474. classCache = {},
  23475. set = context.set,
  23476. unset = context.unset,
  23477. parentForm = context.parentForm,
  23478. $animate = context.$animate;
  23479. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  23480. ctrl.$setValidity = setValidity;
  23481. function setValidity(validationErrorKey, state, controller) {
  23482. if (state === undefined) {
  23483. createAndSet('$pending', validationErrorKey, controller);
  23484. } else {
  23485. unsetAndCleanup('$pending', validationErrorKey, controller);
  23486. }
  23487. if (!isBoolean(state)) {
  23488. unset(ctrl.$error, validationErrorKey, controller);
  23489. unset(ctrl.$$success, validationErrorKey, controller);
  23490. } else {
  23491. if (state) {
  23492. unset(ctrl.$error, validationErrorKey, controller);
  23493. set(ctrl.$$success, validationErrorKey, controller);
  23494. } else {
  23495. set(ctrl.$error, validationErrorKey, controller);
  23496. unset(ctrl.$$success, validationErrorKey, controller);
  23497. }
  23498. }
  23499. if (ctrl.$pending) {
  23500. cachedToggleClass(PENDING_CLASS, true);
  23501. ctrl.$valid = ctrl.$invalid = undefined;
  23502. toggleValidationCss('', null);
  23503. } else {
  23504. cachedToggleClass(PENDING_CLASS, false);
  23505. ctrl.$valid = isObjectEmpty(ctrl.$error);
  23506. ctrl.$invalid = !ctrl.$valid;
  23507. toggleValidationCss('', ctrl.$valid);
  23508. }
  23509. // re-read the state as the set/unset methods could have
  23510. // combined state in ctrl.$error[validationError] (used for forms),
  23511. // where setting/unsetting only increments/decrements the value,
  23512. // and does not replace it.
  23513. var combinedState;
  23514. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  23515. combinedState = undefined;
  23516. } else if (ctrl.$error[validationErrorKey]) {
  23517. combinedState = false;
  23518. } else if (ctrl.$$success[validationErrorKey]) {
  23519. combinedState = true;
  23520. } else {
  23521. combinedState = null;
  23522. }
  23523. toggleValidationCss(validationErrorKey, combinedState);
  23524. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  23525. }
  23526. function createAndSet(name, value, controller) {
  23527. if (!ctrl[name]) {
  23528. ctrl[name] = {};
  23529. }
  23530. set(ctrl[name], value, controller);
  23531. }
  23532. function unsetAndCleanup(name, value, controller) {
  23533. if (ctrl[name]) {
  23534. unset(ctrl[name], value, controller);
  23535. }
  23536. if (isObjectEmpty(ctrl[name])) {
  23537. ctrl[name] = undefined;
  23538. }
  23539. }
  23540. function cachedToggleClass(className, switchValue) {
  23541. if (switchValue && !classCache[className]) {
  23542. $animate.addClass($element, className);
  23543. classCache[className] = true;
  23544. } else if (!switchValue && classCache[className]) {
  23545. $animate.removeClass($element, className);
  23546. classCache[className] = false;
  23547. }
  23548. }
  23549. function toggleValidationCss(validationErrorKey, isValid) {
  23550. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  23551. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  23552. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  23553. }
  23554. }
  23555. function isObjectEmpty(obj) {
  23556. if (obj) {
  23557. for (var prop in obj) {
  23558. if (obj.hasOwnProperty(prop)) {
  23559. return false;
  23560. }
  23561. }
  23562. }
  23563. return true;
  23564. }
  23565. /**
  23566. * @ngdoc directive
  23567. * @name ngNonBindable
  23568. * @restrict AC
  23569. * @priority 1000
  23570. *
  23571. * @description
  23572. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  23573. * DOM element. This is useful if the element contains what appears to be Angular directives and
  23574. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  23575. * displays snippets of code, for instance.
  23576. *
  23577. * @element ANY
  23578. *
  23579. * @example
  23580. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  23581. * but the one wrapped in `ngNonBindable` is left alone.
  23582. *
  23583. * @example
  23584. <example>
  23585. <file name="index.html">
  23586. <div>Normal: {{1 + 2}}</div>
  23587. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  23588. </file>
  23589. <file name="protractor.js" type="protractor">
  23590. it('should check ng-non-bindable', function() {
  23591. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  23592. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  23593. });
  23594. </file>
  23595. </example>
  23596. */
  23597. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  23598. /* global jqLiteRemove */
  23599. var ngOptionsMinErr = minErr('ngOptions');
  23600. /**
  23601. * @ngdoc directive
  23602. * @name ngOptions
  23603. * @restrict A
  23604. *
  23605. * @description
  23606. *
  23607. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23608. * elements for the `<select>` element using the array or object obtained by evaluating the
  23609. * `ngOptions` comprehension expression.
  23610. *
  23611. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23612. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23613. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23614. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23615. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23616. * to a non-string value. This is because an option element can only be bound to string values at
  23617. * present.
  23618. *
  23619. * When an item in the `<select>` menu is selected, the array element or object property
  23620. * represented by the selected option will be bound to the model identified by the `ngModel`
  23621. * directive.
  23622. *
  23623. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23624. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23625. * option. See example below for demonstration.
  23626. *
  23627. * ## Complex Models (objects or collections)
  23628. *
  23629. * **Note:** By default, `ngModel` watches the model by reference, not value. This is important when
  23630. * binding any input directive to a model that is an object or a collection.
  23631. *
  23632. * Since this is a common situation for `ngOptions` the directive additionally watches the model using
  23633. * `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in
  23634. * the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual
  23635. * object/collection has not changed identity but only a property on the object or an item in the collection
  23636. * changes.
  23637. *
  23638. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  23639. * if the model is an array). This means that changing a property deeper inside the object/collection that the
  23640. * first level will not trigger a re-rendering.
  23641. *
  23642. *
  23643. * ## `select` **`as`**
  23644. *
  23645. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23646. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23647. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23648. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23649. *
  23650. *
  23651. * ### `select` **`as`** and **`track by`**
  23652. *
  23653. * <div class="alert alert-warning">
  23654. * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
  23655. * </div>
  23656. *
  23657. * Consider the following example:
  23658. *
  23659. * ```html
  23660. * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"></select>
  23661. * ```
  23662. *
  23663. * ```js
  23664. * $scope.values = [{
  23665. * id: 1,
  23666. * label: 'aLabel',
  23667. * subItem: { name: 'aSubItem' }
  23668. * }, {
  23669. * id: 2,
  23670. * label: 'bLabel',
  23671. * subItem: { name: 'bSubItem' }
  23672. * }];
  23673. *
  23674. * $scope.selected = { name: 'aSubItem' };
  23675. * ```
  23676. *
  23677. * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
  23678. * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
  23679. * following:
  23680. *
  23681. * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
  23682. * 2. Apply **`track by`** to the already selected value in `ngModel`.
  23683. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
  23684. * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
  23685. * a wrong object, the selected element can't be found, `<select>` is always reset to the "not
  23686. * selected" option.
  23687. *
  23688. *
  23689. * @param {string} ngModel Assignable angular expression to data-bind to.
  23690. * @param {string=} name Property name of the form under which the control is published.
  23691. * @param {string=} required The control is considered valid only if value is entered.
  23692. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23693. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23694. * `required` when you want to data-bind to the `required` attribute.
  23695. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23696. *
  23697. * * for array data sources:
  23698. * * `label` **`for`** `value` **`in`** `array`
  23699. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23700. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23701. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  23702. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23703. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23704. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23705. * (for including a filter with `track by`)
  23706. * * for object data sources:
  23707. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23708. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23709. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23710. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23711. * * `select` **`as`** `label` **`group by`** `group`
  23712. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23713. * * `select` **`as`** `label` **`disable when`** `disable`
  23714. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23715. *
  23716. * Where:
  23717. *
  23718. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23719. * * `value`: local variable which will refer to each item in the `array` or each property value
  23720. * of `object` during iteration.
  23721. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23722. * * `label`: The result of this expression will be the label for `<option>` element. The
  23723. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23724. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23725. * element. If not specified, `select` expression will default to `value`.
  23726. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23727. * DOM element.
  23728. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  23729. * element. Return `true` to disable.
  23730. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23731. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23732. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23733. * even when the options are recreated (e.g. reloaded from the server).
  23734. *
  23735. * @example
  23736. <example module="selectExample">
  23737. <file name="index.html">
  23738. <script>
  23739. angular.module('selectExample', [])
  23740. .controller('ExampleController', ['$scope', function($scope) {
  23741. $scope.colors = [
  23742. {name:'black', shade:'dark'},
  23743. {name:'white', shade:'light', notAnOption: true},
  23744. {name:'red', shade:'dark'},
  23745. {name:'blue', shade:'dark', notAnOption: true},
  23746. {name:'yellow', shade:'light', notAnOption: false}
  23747. ];
  23748. $scope.myColor = $scope.colors[2]; // red
  23749. }]);
  23750. </script>
  23751. <div ng-controller="ExampleController">
  23752. <ul>
  23753. <li ng-repeat="color in colors">
  23754. <label>Name: <input ng-model="color.name"></label>
  23755. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  23756. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  23757. </li>
  23758. <li>
  23759. <button ng-click="colors.push({})">add</button>
  23760. </li>
  23761. </ul>
  23762. <hr/>
  23763. <label>Color (null not allowed):
  23764. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  23765. </label><br/>
  23766. <label>Color (null allowed):
  23767. <span class="nullable">
  23768. <select ng-model="myColor" ng-options="color.name for color in colors">
  23769. <option value="">-- choose color --</option>
  23770. </select>
  23771. </span></label><br/>
  23772. <label>Color grouped by shade:
  23773. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23774. </select>
  23775. </label><br/>
  23776. <label>Color grouped by shade, with some disabled:
  23777. <select ng-model="myColor"
  23778. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  23779. </select>
  23780. </label><br/>
  23781. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  23782. <br/>
  23783. <hr/>
  23784. Currently selected: {{ {selected_color:myColor} }}
  23785. <div style="border:solid 1px black; height:20px"
  23786. ng-style="{'background-color':myColor.name}">
  23787. </div>
  23788. </div>
  23789. </file>
  23790. <file name="protractor.js" type="protractor">
  23791. it('should check ng-options', function() {
  23792. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23793. element.all(by.model('myColor')).first().click();
  23794. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23795. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23796. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23797. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23798. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23799. });
  23800. </file>
  23801. </example>
  23802. */
  23803. // jshint maxlen: false
  23804. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  23805. var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
  23806. // 1: value expression (valueFn)
  23807. // 2: label expression (displayFn)
  23808. // 3: group by expression (groupByFn)
  23809. // 4: disable when expression (disableWhenFn)
  23810. // 5: array item variable name
  23811. // 6: object item key variable name
  23812. // 7: object item value variable name
  23813. // 8: collection expression
  23814. // 9: track by expression
  23815. // jshint maxlen: 100
  23816. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  23817. function parseOptionsExpression(optionsExp, selectElement, scope) {
  23818. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  23819. if (!(match)) {
  23820. throw ngOptionsMinErr('iexp',
  23821. "Expected expression in form of " +
  23822. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23823. " but got '{0}'. Element: {1}",
  23824. optionsExp, startingTag(selectElement));
  23825. }
  23826. // Extract the parts from the ngOptions expression
  23827. // The variable name for the value of the item in the collection
  23828. var valueName = match[5] || match[7];
  23829. // The variable name for the key of the item in the collection
  23830. var keyName = match[6];
  23831. // An expression that generates the viewValue for an option if there is a label expression
  23832. var selectAs = / as /.test(match[0]) && match[1];
  23833. // An expression that is used to track the id of each object in the options collection
  23834. var trackBy = match[9];
  23835. // An expression that generates the viewValue for an option if there is no label expression
  23836. var valueFn = $parse(match[2] ? match[1] : valueName);
  23837. var selectAsFn = selectAs && $parse(selectAs);
  23838. var viewValueFn = selectAsFn || valueFn;
  23839. var trackByFn = trackBy && $parse(trackBy);
  23840. // Get the value by which we are going to track the option
  23841. // if we have a trackFn then use that (passing scope and locals)
  23842. // otherwise just hash the given viewValue
  23843. var getTrackByValueFn = trackBy ?
  23844. function(value, locals) { return trackByFn(scope, locals); } :
  23845. function getHashOfValue(value) { return hashKey(value); };
  23846. var getTrackByValue = function(value, key) {
  23847. return getTrackByValueFn(value, getLocals(value, key));
  23848. };
  23849. var displayFn = $parse(match[2] || match[1]);
  23850. var groupByFn = $parse(match[3] || '');
  23851. var disableWhenFn = $parse(match[4] || '');
  23852. var valuesFn = $parse(match[8]);
  23853. var locals = {};
  23854. var getLocals = keyName ? function(value, key) {
  23855. locals[keyName] = key;
  23856. locals[valueName] = value;
  23857. return locals;
  23858. } : function(value) {
  23859. locals[valueName] = value;
  23860. return locals;
  23861. };
  23862. function Option(selectValue, viewValue, label, group, disabled) {
  23863. this.selectValue = selectValue;
  23864. this.viewValue = viewValue;
  23865. this.label = label;
  23866. this.group = group;
  23867. this.disabled = disabled;
  23868. }
  23869. function getOptionValuesKeys(optionValues) {
  23870. var optionValuesKeys;
  23871. if (!keyName && isArrayLike(optionValues)) {
  23872. optionValuesKeys = optionValues;
  23873. } else {
  23874. // if object, extract keys, in enumeration order, unsorted
  23875. optionValuesKeys = [];
  23876. for (var itemKey in optionValues) {
  23877. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  23878. optionValuesKeys.push(itemKey);
  23879. }
  23880. }
  23881. }
  23882. return optionValuesKeys;
  23883. }
  23884. return {
  23885. trackBy: trackBy,
  23886. getTrackByValue: getTrackByValue,
  23887. getWatchables: $parse(valuesFn, function(optionValues) {
  23888. // Create a collection of things that we would like to watch (watchedArray)
  23889. // so that they can all be watched using a single $watchCollection
  23890. // that only runs the handler once if anything changes
  23891. var watchedArray = [];
  23892. optionValues = optionValues || [];
  23893. var optionValuesKeys = getOptionValuesKeys(optionValues);
  23894. var optionValuesLength = optionValuesKeys.length;
  23895. for (var index = 0; index < optionValuesLength; index++) {
  23896. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  23897. var value = optionValues[key];
  23898. var locals = getLocals(optionValues[key], key);
  23899. var selectValue = getTrackByValueFn(optionValues[key], locals);
  23900. watchedArray.push(selectValue);
  23901. // Only need to watch the displayFn if there is a specific label expression
  23902. if (match[2] || match[1]) {
  23903. var label = displayFn(scope, locals);
  23904. watchedArray.push(label);
  23905. }
  23906. // Only need to watch the disableWhenFn if there is a specific disable expression
  23907. if (match[4]) {
  23908. var disableWhen = disableWhenFn(scope, locals);
  23909. watchedArray.push(disableWhen);
  23910. }
  23911. }
  23912. return watchedArray;
  23913. }),
  23914. getOptions: function() {
  23915. var optionItems = [];
  23916. var selectValueMap = {};
  23917. // The option values were already computed in the `getWatchables` fn,
  23918. // which must have been called to trigger `getOptions`
  23919. var optionValues = valuesFn(scope) || [];
  23920. var optionValuesKeys = getOptionValuesKeys(optionValues);
  23921. var optionValuesLength = optionValuesKeys.length;
  23922. for (var index = 0; index < optionValuesLength; index++) {
  23923. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  23924. var value = optionValues[key];
  23925. var locals = getLocals(value, key);
  23926. var viewValue = viewValueFn(scope, locals);
  23927. var selectValue = getTrackByValueFn(viewValue, locals);
  23928. var label = displayFn(scope, locals);
  23929. var group = groupByFn(scope, locals);
  23930. var disabled = disableWhenFn(scope, locals);
  23931. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  23932. optionItems.push(optionItem);
  23933. selectValueMap[selectValue] = optionItem;
  23934. }
  23935. return {
  23936. items: optionItems,
  23937. selectValueMap: selectValueMap,
  23938. getOptionFromViewValue: function(value) {
  23939. return selectValueMap[getTrackByValue(value)];
  23940. },
  23941. getViewValueFromOption: function(option) {
  23942. // If the viewValue could be an object that may be mutated by the application,
  23943. // we need to make a copy and not return the reference to the value on the option.
  23944. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  23945. }
  23946. };
  23947. }
  23948. };
  23949. }
  23950. // we can't just jqLite('<option>') since jqLite is not smart enough
  23951. // to create it in <select> and IE barfs otherwise.
  23952. var optionTemplate = document.createElement('option'),
  23953. optGroupTemplate = document.createElement('optgroup');
  23954. return {
  23955. restrict: 'A',
  23956. terminal: true,
  23957. require: ['select', '?ngModel'],
  23958. link: function(scope, selectElement, attr, ctrls) {
  23959. // if ngModel is not defined, we don't need to do anything
  23960. var ngModelCtrl = ctrls[1];
  23961. if (!ngModelCtrl) return;
  23962. var selectCtrl = ctrls[0];
  23963. var multiple = attr.multiple;
  23964. // The emptyOption allows the application developer to provide their own custom "empty"
  23965. // option when the viewValue does not match any of the option values.
  23966. var emptyOption;
  23967. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  23968. if (children[i].value === '') {
  23969. emptyOption = children.eq(i);
  23970. break;
  23971. }
  23972. }
  23973. var providedEmptyOption = !!emptyOption;
  23974. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  23975. unknownOption.val('?');
  23976. var options;
  23977. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  23978. var renderEmptyOption = function() {
  23979. if (!providedEmptyOption) {
  23980. selectElement.prepend(emptyOption);
  23981. }
  23982. selectElement.val('');
  23983. emptyOption.prop('selected', true); // needed for IE
  23984. emptyOption.attr('selected', true);
  23985. };
  23986. var removeEmptyOption = function() {
  23987. if (!providedEmptyOption) {
  23988. emptyOption.remove();
  23989. }
  23990. };
  23991. var renderUnknownOption = function() {
  23992. selectElement.prepend(unknownOption);
  23993. selectElement.val('?');
  23994. unknownOption.prop('selected', true); // needed for IE
  23995. unknownOption.attr('selected', true);
  23996. };
  23997. var removeUnknownOption = function() {
  23998. unknownOption.remove();
  23999. };
  24000. // Update the controller methods for multiple selectable options
  24001. if (!multiple) {
  24002. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  24003. var option = options.getOptionFromViewValue(value);
  24004. if (option && !option.disabled) {
  24005. if (selectElement[0].value !== option.selectValue) {
  24006. removeUnknownOption();
  24007. removeEmptyOption();
  24008. selectElement[0].value = option.selectValue;
  24009. option.element.selected = true;
  24010. option.element.setAttribute('selected', 'selected');
  24011. }
  24012. } else {
  24013. if (value === null || providedEmptyOption) {
  24014. removeUnknownOption();
  24015. renderEmptyOption();
  24016. } else {
  24017. removeEmptyOption();
  24018. renderUnknownOption();
  24019. }
  24020. }
  24021. };
  24022. selectCtrl.readValue = function readNgOptionsValue() {
  24023. var selectedOption = options.selectValueMap[selectElement.val()];
  24024. if (selectedOption && !selectedOption.disabled) {
  24025. removeEmptyOption();
  24026. removeUnknownOption();
  24027. return options.getViewValueFromOption(selectedOption);
  24028. }
  24029. return null;
  24030. };
  24031. // If we are using `track by` then we must watch the tracked value on the model
  24032. // since ngModel only watches for object identity change
  24033. if (ngOptions.trackBy) {
  24034. scope.$watch(
  24035. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  24036. function() { ngModelCtrl.$render(); }
  24037. );
  24038. }
  24039. } else {
  24040. ngModelCtrl.$isEmpty = function(value) {
  24041. return !value || value.length === 0;
  24042. };
  24043. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  24044. options.items.forEach(function(option) {
  24045. option.element.selected = false;
  24046. });
  24047. if (value) {
  24048. value.forEach(function(item) {
  24049. var option = options.getOptionFromViewValue(item);
  24050. if (option && !option.disabled) option.element.selected = true;
  24051. });
  24052. }
  24053. };
  24054. selectCtrl.readValue = function readNgOptionsMultiple() {
  24055. var selectedValues = selectElement.val() || [],
  24056. selections = [];
  24057. forEach(selectedValues, function(value) {
  24058. var option = options.selectValueMap[value];
  24059. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  24060. });
  24061. return selections;
  24062. };
  24063. // If we are using `track by` then we must watch these tracked values on the model
  24064. // since ngModel only watches for object identity change
  24065. if (ngOptions.trackBy) {
  24066. scope.$watchCollection(function() {
  24067. if (isArray(ngModelCtrl.$viewValue)) {
  24068. return ngModelCtrl.$viewValue.map(function(value) {
  24069. return ngOptions.getTrackByValue(value);
  24070. });
  24071. }
  24072. }, function() {
  24073. ngModelCtrl.$render();
  24074. });
  24075. }
  24076. }
  24077. if (providedEmptyOption) {
  24078. // we need to remove it before calling selectElement.empty() because otherwise IE will
  24079. // remove the label from the element. wtf?
  24080. emptyOption.remove();
  24081. // compile the element since there might be bindings in it
  24082. $compile(emptyOption)(scope);
  24083. // remove the class, which is added automatically because we recompile the element and it
  24084. // becomes the compilation root
  24085. emptyOption.removeClass('ng-scope');
  24086. } else {
  24087. emptyOption = jqLite(optionTemplate.cloneNode(false));
  24088. }
  24089. // We need to do this here to ensure that the options object is defined
  24090. // when we first hit it in writeNgOptionsValue
  24091. updateOptions();
  24092. // We will re-render the option elements if the option values or labels change
  24093. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  24094. // ------------------------------------------------------------------ //
  24095. function updateOptionElement(option, element) {
  24096. option.element = element;
  24097. element.disabled = option.disabled;
  24098. if (option.value !== element.value) element.value = option.selectValue;
  24099. if (option.label !== element.label) {
  24100. element.label = option.label;
  24101. element.textContent = option.label;
  24102. }
  24103. }
  24104. function addOrReuseElement(parent, current, type, templateElement) {
  24105. var element;
  24106. // Check whether we can reuse the next element
  24107. if (current && lowercase(current.nodeName) === type) {
  24108. // The next element is the right type so reuse it
  24109. element = current;
  24110. } else {
  24111. // The next element is not the right type so create a new one
  24112. element = templateElement.cloneNode(false);
  24113. if (!current) {
  24114. // There are no more elements so just append it to the select
  24115. parent.appendChild(element);
  24116. } else {
  24117. // The next element is not a group so insert the new one
  24118. parent.insertBefore(element, current);
  24119. }
  24120. }
  24121. return element;
  24122. }
  24123. function removeExcessElements(current) {
  24124. var next;
  24125. while (current) {
  24126. next = current.nextSibling;
  24127. jqLiteRemove(current);
  24128. current = next;
  24129. }
  24130. }
  24131. function skipEmptyAndUnknownOptions(current) {
  24132. var emptyOption_ = emptyOption && emptyOption[0];
  24133. var unknownOption_ = unknownOption && unknownOption[0];
  24134. if (emptyOption_ || unknownOption_) {
  24135. while (current &&
  24136. (current === emptyOption_ ||
  24137. current === unknownOption_)) {
  24138. current = current.nextSibling;
  24139. }
  24140. }
  24141. return current;
  24142. }
  24143. function updateOptions() {
  24144. var previousValue = options && selectCtrl.readValue();
  24145. options = ngOptions.getOptions();
  24146. var groupMap = {};
  24147. var currentElement = selectElement[0].firstChild;
  24148. // Ensure that the empty option is always there if it was explicitly provided
  24149. if (providedEmptyOption) {
  24150. selectElement.prepend(emptyOption);
  24151. }
  24152. currentElement = skipEmptyAndUnknownOptions(currentElement);
  24153. options.items.forEach(function updateOption(option) {
  24154. var group;
  24155. var groupElement;
  24156. var optionElement;
  24157. if (option.group) {
  24158. // This option is to live in a group
  24159. // See if we have already created this group
  24160. group = groupMap[option.group];
  24161. if (!group) {
  24162. // We have not already created this group
  24163. groupElement = addOrReuseElement(selectElement[0],
  24164. currentElement,
  24165. 'optgroup',
  24166. optGroupTemplate);
  24167. // Move to the next element
  24168. currentElement = groupElement.nextSibling;
  24169. // Update the label on the group element
  24170. groupElement.label = option.group;
  24171. // Store it for use later
  24172. group = groupMap[option.group] = {
  24173. groupElement: groupElement,
  24174. currentOptionElement: groupElement.firstChild
  24175. };
  24176. }
  24177. // So now we have a group for this option we add the option to the group
  24178. optionElement = addOrReuseElement(group.groupElement,
  24179. group.currentOptionElement,
  24180. 'option',
  24181. optionTemplate);
  24182. updateOptionElement(option, optionElement);
  24183. // Move to the next element
  24184. group.currentOptionElement = optionElement.nextSibling;
  24185. } else {
  24186. // This option is not in a group
  24187. optionElement = addOrReuseElement(selectElement[0],
  24188. currentElement,
  24189. 'option',
  24190. optionTemplate);
  24191. updateOptionElement(option, optionElement);
  24192. // Move to the next element
  24193. currentElement = optionElement.nextSibling;
  24194. }
  24195. });
  24196. // Now remove all excess options and group
  24197. Object.keys(groupMap).forEach(function(key) {
  24198. removeExcessElements(groupMap[key].currentOptionElement);
  24199. });
  24200. removeExcessElements(currentElement);
  24201. ngModelCtrl.$render();
  24202. // Check to see if the value has changed due to the update to the options
  24203. if (!ngModelCtrl.$isEmpty(previousValue)) {
  24204. var nextValue = selectCtrl.readValue();
  24205. if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  24206. ngModelCtrl.$setViewValue(nextValue);
  24207. ngModelCtrl.$render();
  24208. }
  24209. }
  24210. }
  24211. }
  24212. };
  24213. }];
  24214. /**
  24215. * @ngdoc directive
  24216. * @name ngPluralize
  24217. * @restrict EA
  24218. *
  24219. * @description
  24220. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  24221. * These rules are bundled with angular.js, but can be overridden
  24222. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  24223. * by specifying the mappings between
  24224. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24225. * and the strings to be displayed.
  24226. *
  24227. * # Plural categories and explicit number rules
  24228. * There are two
  24229. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24230. * in Angular's default en-US locale: "one" and "other".
  24231. *
  24232. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  24233. * any number that is not 1), an explicit number rule can only match one number. For example, the
  24234. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  24235. * and explicit number rules throughout the rest of this documentation.
  24236. *
  24237. * # Configuring ngPluralize
  24238. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  24239. * You can also provide an optional attribute, `offset`.
  24240. *
  24241. * The value of the `count` attribute can be either a string or an {@link guide/expression
  24242. * Angular expression}; these are evaluated on the current scope for its bound value.
  24243. *
  24244. * The `when` attribute specifies the mappings between plural categories and the actual
  24245. * string to be displayed. The value of the attribute should be a JSON object.
  24246. *
  24247. * The following example shows how to configure ngPluralize:
  24248. *
  24249. * ```html
  24250. * <ng-pluralize count="personCount"
  24251. when="{'0': 'Nobody is viewing.',
  24252. * 'one': '1 person is viewing.',
  24253. * 'other': '{} people are viewing.'}">
  24254. * </ng-pluralize>
  24255. *```
  24256. *
  24257. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  24258. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  24259. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  24260. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  24261. * show "a dozen people are viewing".
  24262. *
  24263. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  24264. * into pluralized strings. In the previous example, Angular will replace `{}` with
  24265. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  24266. * for <span ng-non-bindable>{{numberExpression}}</span>.
  24267. *
  24268. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  24269. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  24270. *
  24271. * # Configuring ngPluralize with offset
  24272. * The `offset` attribute allows further customization of pluralized text, which can result in
  24273. * a better user experience. For example, instead of the message "4 people are viewing this document",
  24274. * you might display "John, Kate and 2 others are viewing this document".
  24275. * The offset attribute allows you to offset a number by any desired value.
  24276. * Let's take a look at an example:
  24277. *
  24278. * ```html
  24279. * <ng-pluralize count="personCount" offset=2
  24280. * when="{'0': 'Nobody is viewing.',
  24281. * '1': '{{person1}} is viewing.',
  24282. * '2': '{{person1}} and {{person2}} are viewing.',
  24283. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24284. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24285. * </ng-pluralize>
  24286. * ```
  24287. *
  24288. * Notice that we are still using two plural categories(one, other), but we added
  24289. * three explicit number rules 0, 1 and 2.
  24290. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  24291. * When three people view the document, no explicit number rule is found, so
  24292. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  24293. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  24294. * is shown.
  24295. *
  24296. * Note that when you specify offsets, you must provide explicit number rules for
  24297. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  24298. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  24299. * plural categories "one" and "other".
  24300. *
  24301. * @param {string|expression} count The variable to be bound to.
  24302. * @param {string} when The mapping between plural category to its corresponding strings.
  24303. * @param {number=} offset Offset to deduct from the total number.
  24304. *
  24305. * @example
  24306. <example module="pluralizeExample">
  24307. <file name="index.html">
  24308. <script>
  24309. angular.module('pluralizeExample', [])
  24310. .controller('ExampleController', ['$scope', function($scope) {
  24311. $scope.person1 = 'Igor';
  24312. $scope.person2 = 'Misko';
  24313. $scope.personCount = 1;
  24314. }]);
  24315. </script>
  24316. <div ng-controller="ExampleController">
  24317. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  24318. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  24319. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  24320. <!--- Example with simple pluralization rules for en locale --->
  24321. Without Offset:
  24322. <ng-pluralize count="personCount"
  24323. when="{'0': 'Nobody is viewing.',
  24324. 'one': '1 person is viewing.',
  24325. 'other': '{} people are viewing.'}">
  24326. </ng-pluralize><br>
  24327. <!--- Example with offset --->
  24328. With Offset(2):
  24329. <ng-pluralize count="personCount" offset=2
  24330. when="{'0': 'Nobody is viewing.',
  24331. '1': '{{person1}} is viewing.',
  24332. '2': '{{person1}} and {{person2}} are viewing.',
  24333. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24334. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24335. </ng-pluralize>
  24336. </div>
  24337. </file>
  24338. <file name="protractor.js" type="protractor">
  24339. it('should show correct pluralized string', function() {
  24340. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  24341. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24342. var countInput = element(by.model('personCount'));
  24343. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  24344. expect(withOffset.getText()).toEqual('Igor is viewing.');
  24345. countInput.clear();
  24346. countInput.sendKeys('0');
  24347. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  24348. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  24349. countInput.clear();
  24350. countInput.sendKeys('2');
  24351. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  24352. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  24353. countInput.clear();
  24354. countInput.sendKeys('3');
  24355. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  24356. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  24357. countInput.clear();
  24358. countInput.sendKeys('4');
  24359. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  24360. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  24361. });
  24362. it('should show data-bound names', function() {
  24363. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24364. var personCount = element(by.model('personCount'));
  24365. var person1 = element(by.model('person1'));
  24366. var person2 = element(by.model('person2'));
  24367. personCount.clear();
  24368. personCount.sendKeys('4');
  24369. person1.clear();
  24370. person1.sendKeys('Di');
  24371. person2.clear();
  24372. person2.sendKeys('Vojta');
  24373. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  24374. });
  24375. </file>
  24376. </example>
  24377. */
  24378. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  24379. var BRACE = /{}/g,
  24380. IS_WHEN = /^when(Minus)?(.+)$/;
  24381. return {
  24382. link: function(scope, element, attr) {
  24383. var numberExp = attr.count,
  24384. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  24385. offset = attr.offset || 0,
  24386. whens = scope.$eval(whenExp) || {},
  24387. whensExpFns = {},
  24388. startSymbol = $interpolate.startSymbol(),
  24389. endSymbol = $interpolate.endSymbol(),
  24390. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  24391. watchRemover = angular.noop,
  24392. lastCount;
  24393. forEach(attr, function(expression, attributeName) {
  24394. var tmpMatch = IS_WHEN.exec(attributeName);
  24395. if (tmpMatch) {
  24396. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  24397. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  24398. }
  24399. });
  24400. forEach(whens, function(expression, key) {
  24401. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  24402. });
  24403. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  24404. var count = parseFloat(newVal);
  24405. var countIsNaN = isNaN(count);
  24406. if (!countIsNaN && !(count in whens)) {
  24407. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  24408. // Otherwise, check it against pluralization rules in $locale service.
  24409. count = $locale.pluralCat(count - offset);
  24410. }
  24411. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  24412. // In JS `NaN !== NaN`, so we have to exlicitly check.
  24413. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  24414. watchRemover();
  24415. var whenExpFn = whensExpFns[count];
  24416. if (isUndefined(whenExpFn)) {
  24417. if (newVal != null) {
  24418. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  24419. }
  24420. watchRemover = noop;
  24421. updateElementText();
  24422. } else {
  24423. watchRemover = scope.$watch(whenExpFn, updateElementText);
  24424. }
  24425. lastCount = count;
  24426. }
  24427. });
  24428. function updateElementText(newText) {
  24429. element.text(newText || '');
  24430. }
  24431. }
  24432. };
  24433. }];
  24434. /**
  24435. * @ngdoc directive
  24436. * @name ngRepeat
  24437. * @multiElement
  24438. *
  24439. * @description
  24440. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  24441. * instance gets its own scope, where the given loop variable is set to the current collection item,
  24442. * and `$index` is set to the item index or key.
  24443. *
  24444. * Special properties are exposed on the local scope of each template instance, including:
  24445. *
  24446. * | Variable | Type | Details |
  24447. * |-----------|-----------------|-----------------------------------------------------------------------------|
  24448. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  24449. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  24450. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  24451. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  24452. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  24453. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  24454. *
  24455. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  24456. * This may be useful when, for instance, nesting ngRepeats.
  24457. *
  24458. *
  24459. * # Iterating over object properties
  24460. *
  24461. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  24462. * syntax:
  24463. *
  24464. * ```js
  24465. * <div ng-repeat="(key, value) in myObj"> ... </div>
  24466. * ```
  24467. *
  24468. * You need to be aware that the JavaScript specification does not define the order of keys
  24469. * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
  24470. * used to sort the keys alphabetically.)
  24471. *
  24472. * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
  24473. * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
  24474. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  24475. * and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
  24476. *
  24477. * If this is not desired, the recommended workaround is to convert your object into an array
  24478. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  24479. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  24480. * or implement a `$watch` on the object yourself.
  24481. *
  24482. *
  24483. * # Tracking and Duplicates
  24484. *
  24485. * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
  24486. *
  24487. * * When an item is added, a new instance of the template is added to the DOM.
  24488. * * When an item is removed, its template instance is removed from the DOM.
  24489. * * When items are reordered, their respective templates are reordered in the DOM.
  24490. *
  24491. * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
  24492. * there are duplicates, it is not possible to maintain a one-to-one mapping between collection
  24493. * items and DOM elements.
  24494. *
  24495. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  24496. * with your own using the `track by` expression.
  24497. *
  24498. * For example, you may track items by the index of each item in the collection, using the
  24499. * special scope property `$index`:
  24500. * ```html
  24501. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  24502. * {{n}}
  24503. * </div>
  24504. * ```
  24505. *
  24506. * You may use arbitrary expressions in `track by`, including references to custom functions
  24507. * on the scope:
  24508. * ```html
  24509. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  24510. * {{n}}
  24511. * </div>
  24512. * ```
  24513. *
  24514. * If you are working with objects that have an identifier property, you can track
  24515. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  24516. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  24517. * JavaScript objects in the collection have been substituted for new ones:
  24518. * ```html
  24519. * <div ng-repeat="model in collection track by model.id">
  24520. * {{model.name}}
  24521. * </div>
  24522. * ```
  24523. *
  24524. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  24525. * `$id` function, which tracks items by their identity:
  24526. * ```html
  24527. * <div ng-repeat="obj in collection track by $id(obj)">
  24528. * {{obj.prop}}
  24529. * </div>
  24530. * ```
  24531. *
  24532. * <div class="alert alert-warning">
  24533. * **Note:** `track by` must always be the last expression:
  24534. * </div>
  24535. * ```
  24536. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  24537. * {{model.name}}
  24538. * </div>
  24539. * ```
  24540. *
  24541. * # Special repeat start and end points
  24542. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  24543. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  24544. * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
  24545. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  24546. *
  24547. * The example below makes use of this feature:
  24548. * ```html
  24549. * <header ng-repeat-start="item in items">
  24550. * Header {{ item }}
  24551. * </header>
  24552. * <div class="body">
  24553. * Body {{ item }}
  24554. * </div>
  24555. * <footer ng-repeat-end>
  24556. * Footer {{ item }}
  24557. * </footer>
  24558. * ```
  24559. *
  24560. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  24561. * ```html
  24562. * <header>
  24563. * Header A
  24564. * </header>
  24565. * <div class="body">
  24566. * Body A
  24567. * </div>
  24568. * <footer>
  24569. * Footer A
  24570. * </footer>
  24571. * <header>
  24572. * Header B
  24573. * </header>
  24574. * <div class="body">
  24575. * Body B
  24576. * </div>
  24577. * <footer>
  24578. * Footer B
  24579. * </footer>
  24580. * ```
  24581. *
  24582. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  24583. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  24584. *
  24585. * @animations
  24586. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  24587. *
  24588. * **.leave** - when an item is removed from the list or when an item is filtered out
  24589. *
  24590. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  24591. *
  24592. * @element ANY
  24593. * @scope
  24594. * @priority 1000
  24595. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  24596. * formats are currently supported:
  24597. *
  24598. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  24599. * is a scope expression giving the collection to enumerate.
  24600. *
  24601. * For example: `album in artist.albums`.
  24602. *
  24603. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  24604. * and `expression` is the scope expression giving the collection to enumerate.
  24605. *
  24606. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  24607. *
  24608. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  24609. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  24610. * is specified, ng-repeat associates elements by identity. It is an error to have
  24611. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  24612. * mapped to the same DOM element, which is not possible.)
  24613. *
  24614. * Note that the tracking expression must come last, after any filters, and the alias expression.
  24615. *
  24616. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  24617. * will be associated by item identity in the array.
  24618. *
  24619. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  24620. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  24621. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  24622. * element in the same way in the DOM.
  24623. *
  24624. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  24625. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  24626. * property is same.
  24627. *
  24628. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  24629. * to items in conjunction with a tracking expression.
  24630. *
  24631. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  24632. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  24633. * when a filter is active on the repeater, but the filtered result set is empty.
  24634. *
  24635. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  24636. * the items have been processed through the filter.
  24637. *
  24638. * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
  24639. * (and not as operator, inside an expression).
  24640. *
  24641. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  24642. *
  24643. * @example
  24644. * This example initializes the scope to a list of names and
  24645. * then uses `ngRepeat` to display every person:
  24646. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24647. <file name="index.html">
  24648. <div ng-init="friends = [
  24649. {name:'John', age:25, gender:'boy'},
  24650. {name:'Jessie', age:30, gender:'girl'},
  24651. {name:'Johanna', age:28, gender:'girl'},
  24652. {name:'Joy', age:15, gender:'girl'},
  24653. {name:'Mary', age:28, gender:'girl'},
  24654. {name:'Peter', age:95, gender:'boy'},
  24655. {name:'Sebastian', age:50, gender:'boy'},
  24656. {name:'Erika', age:27, gender:'girl'},
  24657. {name:'Patrick', age:40, gender:'boy'},
  24658. {name:'Samantha', age:60, gender:'girl'}
  24659. ]">
  24660. I have {{friends.length}} friends. They are:
  24661. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  24662. <ul class="example-animate-container">
  24663. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  24664. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  24665. </li>
  24666. <li class="animate-repeat" ng-if="results.length == 0">
  24667. <strong>No results found...</strong>
  24668. </li>
  24669. </ul>
  24670. </div>
  24671. </file>
  24672. <file name="animations.css">
  24673. .example-animate-container {
  24674. background:white;
  24675. border:1px solid black;
  24676. list-style:none;
  24677. margin:0;
  24678. padding:0 10px;
  24679. }
  24680. .animate-repeat {
  24681. line-height:40px;
  24682. list-style:none;
  24683. box-sizing:border-box;
  24684. }
  24685. .animate-repeat.ng-move,
  24686. .animate-repeat.ng-enter,
  24687. .animate-repeat.ng-leave {
  24688. -webkit-transition:all linear 0.5s;
  24689. transition:all linear 0.5s;
  24690. }
  24691. .animate-repeat.ng-leave.ng-leave-active,
  24692. .animate-repeat.ng-move,
  24693. .animate-repeat.ng-enter {
  24694. opacity:0;
  24695. max-height:0;
  24696. }
  24697. .animate-repeat.ng-leave,
  24698. .animate-repeat.ng-move.ng-move-active,
  24699. .animate-repeat.ng-enter.ng-enter-active {
  24700. opacity:1;
  24701. max-height:40px;
  24702. }
  24703. </file>
  24704. <file name="protractor.js" type="protractor">
  24705. var friends = element.all(by.repeater('friend in friends'));
  24706. it('should render initial data set', function() {
  24707. expect(friends.count()).toBe(10);
  24708. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  24709. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  24710. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  24711. expect(element(by.binding('friends.length')).getText())
  24712. .toMatch("I have 10 friends. They are:");
  24713. });
  24714. it('should update repeater when filter predicate changes', function() {
  24715. expect(friends.count()).toBe(10);
  24716. element(by.model('q')).sendKeys('ma');
  24717. expect(friends.count()).toBe(2);
  24718. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  24719. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  24720. });
  24721. </file>
  24722. </example>
  24723. */
  24724. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  24725. var NG_REMOVED = '$$NG_REMOVED';
  24726. var ngRepeatMinErr = minErr('ngRepeat');
  24727. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  24728. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  24729. scope[valueIdentifier] = value;
  24730. if (keyIdentifier) scope[keyIdentifier] = key;
  24731. scope.$index = index;
  24732. scope.$first = (index === 0);
  24733. scope.$last = (index === (arrayLength - 1));
  24734. scope.$middle = !(scope.$first || scope.$last);
  24735. // jshint bitwise: false
  24736. scope.$odd = !(scope.$even = (index&1) === 0);
  24737. // jshint bitwise: true
  24738. };
  24739. var getBlockStart = function(block) {
  24740. return block.clone[0];
  24741. };
  24742. var getBlockEnd = function(block) {
  24743. return block.clone[block.clone.length - 1];
  24744. };
  24745. return {
  24746. restrict: 'A',
  24747. multiElement: true,
  24748. transclude: 'element',
  24749. priority: 1000,
  24750. terminal: true,
  24751. $$tlb: true,
  24752. compile: function ngRepeatCompile($element, $attr) {
  24753. var expression = $attr.ngRepeat;
  24754. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  24755. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
  24756. if (!match) {
  24757. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  24758. expression);
  24759. }
  24760. var lhs = match[1];
  24761. var rhs = match[2];
  24762. var aliasAs = match[3];
  24763. var trackByExp = match[4];
  24764. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  24765. if (!match) {
  24766. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  24767. lhs);
  24768. }
  24769. var valueIdentifier = match[3] || match[1];
  24770. var keyIdentifier = match[2];
  24771. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  24772. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  24773. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  24774. aliasAs);
  24775. }
  24776. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  24777. var hashFnLocals = {$id: hashKey};
  24778. if (trackByExp) {
  24779. trackByExpGetter = $parse(trackByExp);
  24780. } else {
  24781. trackByIdArrayFn = function(key, value) {
  24782. return hashKey(value);
  24783. };
  24784. trackByIdObjFn = function(key) {
  24785. return key;
  24786. };
  24787. }
  24788. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  24789. if (trackByExpGetter) {
  24790. trackByIdExpFn = function(key, value, index) {
  24791. // assign key, value, and $index to the locals so that they can be used in hash functions
  24792. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  24793. hashFnLocals[valueIdentifier] = value;
  24794. hashFnLocals.$index = index;
  24795. return trackByExpGetter($scope, hashFnLocals);
  24796. };
  24797. }
  24798. // Store a list of elements from previous run. This is a hash where key is the item from the
  24799. // iterator, and the value is objects with following properties.
  24800. // - scope: bound scope
  24801. // - element: previous element.
  24802. // - index: position
  24803. //
  24804. // We are using no-proto object so that we don't need to guard against inherited props via
  24805. // hasOwnProperty.
  24806. var lastBlockMap = createMap();
  24807. //watch props
  24808. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  24809. var index, length,
  24810. previousNode = $element[0], // node that cloned nodes should be inserted after
  24811. // initialized to the comment node anchor
  24812. nextNode,
  24813. // Same as lastBlockMap but it has the current state. It will become the
  24814. // lastBlockMap on the next iteration.
  24815. nextBlockMap = createMap(),
  24816. collectionLength,
  24817. key, value, // key/value of iteration
  24818. trackById,
  24819. trackByIdFn,
  24820. collectionKeys,
  24821. block, // last object information {scope, element, id}
  24822. nextBlockOrder,
  24823. elementsToRemove;
  24824. if (aliasAs) {
  24825. $scope[aliasAs] = collection;
  24826. }
  24827. if (isArrayLike(collection)) {
  24828. collectionKeys = collection;
  24829. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  24830. } else {
  24831. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  24832. // if object, extract keys, in enumeration order, unsorted
  24833. collectionKeys = [];
  24834. for (var itemKey in collection) {
  24835. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  24836. collectionKeys.push(itemKey);
  24837. }
  24838. }
  24839. }
  24840. collectionLength = collectionKeys.length;
  24841. nextBlockOrder = new Array(collectionLength);
  24842. // locate existing items
  24843. for (index = 0; index < collectionLength; index++) {
  24844. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24845. value = collection[key];
  24846. trackById = trackByIdFn(key, value, index);
  24847. if (lastBlockMap[trackById]) {
  24848. // found previously seen block
  24849. block = lastBlockMap[trackById];
  24850. delete lastBlockMap[trackById];
  24851. nextBlockMap[trackById] = block;
  24852. nextBlockOrder[index] = block;
  24853. } else if (nextBlockMap[trackById]) {
  24854. // if collision detected. restore lastBlockMap and throw an error
  24855. forEach(nextBlockOrder, function(block) {
  24856. if (block && block.scope) lastBlockMap[block.id] = block;
  24857. });
  24858. throw ngRepeatMinErr('dupes',
  24859. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  24860. expression, trackById, value);
  24861. } else {
  24862. // new never before seen block
  24863. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  24864. nextBlockMap[trackById] = true;
  24865. }
  24866. }
  24867. // remove leftover items
  24868. for (var blockKey in lastBlockMap) {
  24869. block = lastBlockMap[blockKey];
  24870. elementsToRemove = getBlockNodes(block.clone);
  24871. $animate.leave(elementsToRemove);
  24872. if (elementsToRemove[0].parentNode) {
  24873. // if the element was not removed yet because of pending animation, mark it as deleted
  24874. // so that we can ignore it later
  24875. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  24876. elementsToRemove[index][NG_REMOVED] = true;
  24877. }
  24878. }
  24879. block.scope.$destroy();
  24880. }
  24881. // we are not using forEach for perf reasons (trying to avoid #call)
  24882. for (index = 0; index < collectionLength; index++) {
  24883. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24884. value = collection[key];
  24885. block = nextBlockOrder[index];
  24886. if (block.scope) {
  24887. // if we have already seen this object, then we need to reuse the
  24888. // associated scope/element
  24889. nextNode = previousNode;
  24890. // skip nodes that are already pending removal via leave animation
  24891. do {
  24892. nextNode = nextNode.nextSibling;
  24893. } while (nextNode && nextNode[NG_REMOVED]);
  24894. if (getBlockStart(block) != nextNode) {
  24895. // existing item which got moved
  24896. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  24897. }
  24898. previousNode = getBlockEnd(block);
  24899. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24900. } else {
  24901. // new item which we don't know about
  24902. $transclude(function ngRepeatTransclude(clone, scope) {
  24903. block.scope = scope;
  24904. // http://jsperf.com/clone-vs-createcomment
  24905. var endNode = ngRepeatEndComment.cloneNode(false);
  24906. clone[clone.length++] = endNode;
  24907. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  24908. $animate.enter(clone, null, jqLite(previousNode));
  24909. previousNode = endNode;
  24910. // Note: We only need the first/last node of the cloned nodes.
  24911. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  24912. // by a directive with templateUrl when its template arrives.
  24913. block.clone = clone;
  24914. nextBlockMap[block.id] = block;
  24915. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24916. });
  24917. }
  24918. }
  24919. lastBlockMap = nextBlockMap;
  24920. });
  24921. };
  24922. }
  24923. };
  24924. }];
  24925. var NG_HIDE_CLASS = 'ng-hide';
  24926. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  24927. /**
  24928. * @ngdoc directive
  24929. * @name ngShow
  24930. * @multiElement
  24931. *
  24932. * @description
  24933. * The `ngShow` directive shows or hides the given HTML element based on the expression
  24934. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  24935. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  24936. * in AngularJS and sets the display style to none (using an !important flag).
  24937. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24938. *
  24939. * ```html
  24940. * <!-- when $scope.myValue is truthy (element is visible) -->
  24941. * <div ng-show="myValue"></div>
  24942. *
  24943. * <!-- when $scope.myValue is falsy (element is hidden) -->
  24944. * <div ng-show="myValue" class="ng-hide"></div>
  24945. * ```
  24946. *
  24947. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  24948. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  24949. * from the element causing the element not to appear hidden.
  24950. *
  24951. * ## Why is !important used?
  24952. *
  24953. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  24954. * can be easily overridden by heavier selectors. For example, something as simple
  24955. * as changing the display style on a HTML list item would make hidden elements appear visible.
  24956. * This also becomes a bigger issue when dealing with CSS frameworks.
  24957. *
  24958. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  24959. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  24960. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  24961. *
  24962. * ### Overriding `.ng-hide`
  24963. *
  24964. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  24965. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  24966. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  24967. * with extra animation classes that can be added.
  24968. *
  24969. * ```css
  24970. * .ng-hide:not(.ng-hide-animate) {
  24971. * /&#42; this is just another form of hiding an element &#42;/
  24972. * display: block!important;
  24973. * position: absolute;
  24974. * top: -9999px;
  24975. * left: -9999px;
  24976. * }
  24977. * ```
  24978. *
  24979. * By default you don't need to override in CSS anything and the animations will work around the display style.
  24980. *
  24981. * ## A note about animations with `ngShow`
  24982. *
  24983. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  24984. * is true and false. This system works like the animation system present with ngClass except that
  24985. * you must also include the !important flag to override the display property
  24986. * so that you can perform an animation when the element is hidden during the time of the animation.
  24987. *
  24988. * ```css
  24989. * //
  24990. * //a working example can be found at the bottom of this page
  24991. * //
  24992. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  24993. * /&#42; this is required as of 1.3x to properly
  24994. * apply all styling in a show/hide animation &#42;/
  24995. * transition: 0s linear all;
  24996. * }
  24997. *
  24998. * .my-element.ng-hide-add-active,
  24999. * .my-element.ng-hide-remove-active {
  25000. * /&#42; the transition is defined in the active class &#42;/
  25001. * transition: 1s linear all;
  25002. * }
  25003. *
  25004. * .my-element.ng-hide-add { ... }
  25005. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  25006. * .my-element.ng-hide-remove { ... }
  25007. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  25008. * ```
  25009. *
  25010. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  25011. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  25012. *
  25013. * @animations
  25014. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  25015. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  25016. *
  25017. * @element ANY
  25018. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  25019. * then the element is shown or hidden respectively.
  25020. *
  25021. * @example
  25022. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25023. <file name="index.html">
  25024. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  25025. <div>
  25026. Show:
  25027. <div class="check-element animate-show" ng-show="checked">
  25028. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  25029. </div>
  25030. </div>
  25031. <div>
  25032. Hide:
  25033. <div class="check-element animate-show" ng-hide="checked">
  25034. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25035. </div>
  25036. </div>
  25037. </file>
  25038. <file name="glyphicons.css">
  25039. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25040. </file>
  25041. <file name="animations.css">
  25042. .animate-show {
  25043. line-height: 20px;
  25044. opacity: 1;
  25045. padding: 10px;
  25046. border: 1px solid black;
  25047. background: white;
  25048. }
  25049. .animate-show.ng-hide-add.ng-hide-add-active,
  25050. .animate-show.ng-hide-remove.ng-hide-remove-active {
  25051. -webkit-transition: all linear 0.5s;
  25052. transition: all linear 0.5s;
  25053. }
  25054. .animate-show.ng-hide {
  25055. line-height: 0;
  25056. opacity: 0;
  25057. padding: 0 10px;
  25058. }
  25059. .check-element {
  25060. padding: 10px;
  25061. border: 1px solid black;
  25062. background: white;
  25063. }
  25064. </file>
  25065. <file name="protractor.js" type="protractor">
  25066. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25067. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25068. it('should check ng-show / ng-hide', function() {
  25069. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25070. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25071. element(by.model('checked')).click();
  25072. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25073. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25074. });
  25075. </file>
  25076. </example>
  25077. */
  25078. var ngShowDirective = ['$animate', function($animate) {
  25079. return {
  25080. restrict: 'A',
  25081. multiElement: true,
  25082. link: function(scope, element, attr) {
  25083. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  25084. // we're adding a temporary, animation-specific class for ng-hide since this way
  25085. // we can control when the element is actually displayed on screen without having
  25086. // to have a global/greedy CSS selector that breaks when other animations are run.
  25087. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  25088. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  25089. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25090. });
  25091. });
  25092. }
  25093. };
  25094. }];
  25095. /**
  25096. * @ngdoc directive
  25097. * @name ngHide
  25098. * @multiElement
  25099. *
  25100. * @description
  25101. * The `ngHide` directive shows or hides the given HTML element based on the expression
  25102. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  25103. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  25104. * in AngularJS and sets the display style to none (using an !important flag).
  25105. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  25106. *
  25107. * ```html
  25108. * <!-- when $scope.myValue is truthy (element is hidden) -->
  25109. * <div ng-hide="myValue" class="ng-hide"></div>
  25110. *
  25111. * <!-- when $scope.myValue is falsy (element is visible) -->
  25112. * <div ng-hide="myValue"></div>
  25113. * ```
  25114. *
  25115. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  25116. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  25117. * from the element causing the element not to appear hidden.
  25118. *
  25119. * ## Why is !important used?
  25120. *
  25121. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  25122. * can be easily overridden by heavier selectors. For example, something as simple
  25123. * as changing the display style on a HTML list item would make hidden elements appear visible.
  25124. * This also becomes a bigger issue when dealing with CSS frameworks.
  25125. *
  25126. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  25127. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  25128. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  25129. *
  25130. * ### Overriding `.ng-hide`
  25131. *
  25132. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  25133. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  25134. * class in CSS:
  25135. *
  25136. * ```css
  25137. * .ng-hide {
  25138. * /&#42; this is just another form of hiding an element &#42;/
  25139. * display: block!important;
  25140. * position: absolute;
  25141. * top: -9999px;
  25142. * left: -9999px;
  25143. * }
  25144. * ```
  25145. *
  25146. * By default you don't need to override in CSS anything and the animations will work around the display style.
  25147. *
  25148. * ## A note about animations with `ngHide`
  25149. *
  25150. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  25151. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  25152. * CSS class is added and removed for you instead of your own CSS class.
  25153. *
  25154. * ```css
  25155. * //
  25156. * //a working example can be found at the bottom of this page
  25157. * //
  25158. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  25159. * transition: 0.5s linear all;
  25160. * }
  25161. *
  25162. * .my-element.ng-hide-add { ... }
  25163. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  25164. * .my-element.ng-hide-remove { ... }
  25165. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  25166. * ```
  25167. *
  25168. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  25169. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  25170. *
  25171. * @animations
  25172. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  25173. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  25174. *
  25175. * @element ANY
  25176. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  25177. * the element is shown or hidden respectively.
  25178. *
  25179. * @example
  25180. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25181. <file name="index.html">
  25182. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  25183. <div>
  25184. Show:
  25185. <div class="check-element animate-hide" ng-show="checked">
  25186. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  25187. </div>
  25188. </div>
  25189. <div>
  25190. Hide:
  25191. <div class="check-element animate-hide" ng-hide="checked">
  25192. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25193. </div>
  25194. </div>
  25195. </file>
  25196. <file name="glyphicons.css">
  25197. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25198. </file>
  25199. <file name="animations.css">
  25200. .animate-hide {
  25201. -webkit-transition: all linear 0.5s;
  25202. transition: all linear 0.5s;
  25203. line-height: 20px;
  25204. opacity: 1;
  25205. padding: 10px;
  25206. border: 1px solid black;
  25207. background: white;
  25208. }
  25209. .animate-hide.ng-hide {
  25210. line-height: 0;
  25211. opacity: 0;
  25212. padding: 0 10px;
  25213. }
  25214. .check-element {
  25215. padding: 10px;
  25216. border: 1px solid black;
  25217. background: white;
  25218. }
  25219. </file>
  25220. <file name="protractor.js" type="protractor">
  25221. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25222. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25223. it('should check ng-show / ng-hide', function() {
  25224. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25225. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25226. element(by.model('checked')).click();
  25227. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25228. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25229. });
  25230. </file>
  25231. </example>
  25232. */
  25233. var ngHideDirective = ['$animate', function($animate) {
  25234. return {
  25235. restrict: 'A',
  25236. multiElement: true,
  25237. link: function(scope, element, attr) {
  25238. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  25239. // The comment inside of the ngShowDirective explains why we add and
  25240. // remove a temporary class for the show/hide animation
  25241. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  25242. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25243. });
  25244. });
  25245. }
  25246. };
  25247. }];
  25248. /**
  25249. * @ngdoc directive
  25250. * @name ngStyle
  25251. * @restrict AC
  25252. *
  25253. * @description
  25254. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  25255. *
  25256. * @element ANY
  25257. * @param {expression} ngStyle
  25258. *
  25259. * {@link guide/expression Expression} which evals to an
  25260. * object whose keys are CSS style names and values are corresponding values for those CSS
  25261. * keys.
  25262. *
  25263. * Since some CSS style names are not valid keys for an object, they must be quoted.
  25264. * See the 'background-color' style in the example below.
  25265. *
  25266. * @example
  25267. <example>
  25268. <file name="index.html">
  25269. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  25270. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  25271. <input type="button" value="clear" ng-click="myStyle={}">
  25272. <br/>
  25273. <span ng-style="myStyle">Sample Text</span>
  25274. <pre>myStyle={{myStyle}}</pre>
  25275. </file>
  25276. <file name="style.css">
  25277. span {
  25278. color: black;
  25279. }
  25280. </file>
  25281. <file name="protractor.js" type="protractor">
  25282. var colorSpan = element(by.css('span'));
  25283. it('should check ng-style', function() {
  25284. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25285. element(by.css('input[value=\'set color\']')).click();
  25286. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  25287. element(by.css('input[value=clear]')).click();
  25288. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25289. });
  25290. </file>
  25291. </example>
  25292. */
  25293. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  25294. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  25295. if (oldStyles && (newStyles !== oldStyles)) {
  25296. forEach(oldStyles, function(val, style) { element.css(style, '');});
  25297. }
  25298. if (newStyles) element.css(newStyles);
  25299. }, true);
  25300. });
  25301. /**
  25302. * @ngdoc directive
  25303. * @name ngSwitch
  25304. * @restrict EA
  25305. *
  25306. * @description
  25307. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  25308. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  25309. * as specified in the template.
  25310. *
  25311. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  25312. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  25313. * matches the value obtained from the evaluated expression. In other words, you define a container element
  25314. * (where you place the directive), place an expression on the **`on="..."` attribute**
  25315. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  25316. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  25317. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  25318. * attribute is displayed.
  25319. *
  25320. * <div class="alert alert-info">
  25321. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  25322. * as literal string values to match against.
  25323. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  25324. * value of the expression `$scope.someVal`.
  25325. * </div>
  25326. * @animations
  25327. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  25328. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  25329. *
  25330. * @usage
  25331. *
  25332. * ```
  25333. * <ANY ng-switch="expression">
  25334. * <ANY ng-switch-when="matchValue1">...</ANY>
  25335. * <ANY ng-switch-when="matchValue2">...</ANY>
  25336. * <ANY ng-switch-default>...</ANY>
  25337. * </ANY>
  25338. * ```
  25339. *
  25340. *
  25341. * @scope
  25342. * @priority 1200
  25343. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  25344. * On child elements add:
  25345. *
  25346. * * `ngSwitchWhen`: the case statement to match against. If match then this
  25347. * case will be displayed. If the same match appears multiple times, all the
  25348. * elements will be displayed.
  25349. * * `ngSwitchDefault`: the default case when no other case match. If there
  25350. * are multiple default cases, all of them will be displayed when no other
  25351. * case match.
  25352. *
  25353. *
  25354. * @example
  25355. <example module="switchExample" deps="angular-animate.js" animations="true">
  25356. <file name="index.html">
  25357. <div ng-controller="ExampleController">
  25358. <select ng-model="selection" ng-options="item for item in items">
  25359. </select>
  25360. <code>selection={{selection}}</code>
  25361. <hr/>
  25362. <div class="animate-switch-container"
  25363. ng-switch on="selection">
  25364. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  25365. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  25366. <div class="animate-switch" ng-switch-default>default</div>
  25367. </div>
  25368. </div>
  25369. </file>
  25370. <file name="script.js">
  25371. angular.module('switchExample', ['ngAnimate'])
  25372. .controller('ExampleController', ['$scope', function($scope) {
  25373. $scope.items = ['settings', 'home', 'other'];
  25374. $scope.selection = $scope.items[0];
  25375. }]);
  25376. </file>
  25377. <file name="animations.css">
  25378. .animate-switch-container {
  25379. position:relative;
  25380. background:white;
  25381. border:1px solid black;
  25382. height:40px;
  25383. overflow:hidden;
  25384. }
  25385. .animate-switch {
  25386. padding:10px;
  25387. }
  25388. .animate-switch.ng-animate {
  25389. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25390. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25391. position:absolute;
  25392. top:0;
  25393. left:0;
  25394. right:0;
  25395. bottom:0;
  25396. }
  25397. .animate-switch.ng-leave.ng-leave-active,
  25398. .animate-switch.ng-enter {
  25399. top:-50px;
  25400. }
  25401. .animate-switch.ng-leave,
  25402. .animate-switch.ng-enter.ng-enter-active {
  25403. top:0;
  25404. }
  25405. </file>
  25406. <file name="protractor.js" type="protractor">
  25407. var switchElem = element(by.css('[ng-switch]'));
  25408. var select = element(by.model('selection'));
  25409. it('should start in settings', function() {
  25410. expect(switchElem.getText()).toMatch(/Settings Div/);
  25411. });
  25412. it('should change to home', function() {
  25413. select.all(by.css('option')).get(1).click();
  25414. expect(switchElem.getText()).toMatch(/Home Span/);
  25415. });
  25416. it('should select default', function() {
  25417. select.all(by.css('option')).get(2).click();
  25418. expect(switchElem.getText()).toMatch(/default/);
  25419. });
  25420. </file>
  25421. </example>
  25422. */
  25423. var ngSwitchDirective = ['$animate', function($animate) {
  25424. return {
  25425. require: 'ngSwitch',
  25426. // asks for $scope to fool the BC controller module
  25427. controller: ['$scope', function ngSwitchController() {
  25428. this.cases = {};
  25429. }],
  25430. link: function(scope, element, attr, ngSwitchController) {
  25431. var watchExpr = attr.ngSwitch || attr.on,
  25432. selectedTranscludes = [],
  25433. selectedElements = [],
  25434. previousLeaveAnimations = [],
  25435. selectedScopes = [];
  25436. var spliceFactory = function(array, index) {
  25437. return function() { array.splice(index, 1); };
  25438. };
  25439. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  25440. var i, ii;
  25441. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  25442. $animate.cancel(previousLeaveAnimations[i]);
  25443. }
  25444. previousLeaveAnimations.length = 0;
  25445. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  25446. var selected = getBlockNodes(selectedElements[i].clone);
  25447. selectedScopes[i].$destroy();
  25448. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  25449. promise.then(spliceFactory(previousLeaveAnimations, i));
  25450. }
  25451. selectedElements.length = 0;
  25452. selectedScopes.length = 0;
  25453. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  25454. forEach(selectedTranscludes, function(selectedTransclude) {
  25455. selectedTransclude.transclude(function(caseElement, selectedScope) {
  25456. selectedScopes.push(selectedScope);
  25457. var anchor = selectedTransclude.element;
  25458. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  25459. var block = { clone: caseElement };
  25460. selectedElements.push(block);
  25461. $animate.enter(caseElement, anchor.parent(), anchor);
  25462. });
  25463. });
  25464. }
  25465. });
  25466. }
  25467. };
  25468. }];
  25469. var ngSwitchWhenDirective = ngDirective({
  25470. transclude: 'element',
  25471. priority: 1200,
  25472. require: '^ngSwitch',
  25473. multiElement: true,
  25474. link: function(scope, element, attrs, ctrl, $transclude) {
  25475. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  25476. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  25477. }
  25478. });
  25479. var ngSwitchDefaultDirective = ngDirective({
  25480. transclude: 'element',
  25481. priority: 1200,
  25482. require: '^ngSwitch',
  25483. multiElement: true,
  25484. link: function(scope, element, attr, ctrl, $transclude) {
  25485. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  25486. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  25487. }
  25488. });
  25489. /**
  25490. * @ngdoc directive
  25491. * @name ngTransclude
  25492. * @restrict EAC
  25493. *
  25494. * @description
  25495. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  25496. *
  25497. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  25498. *
  25499. * @element ANY
  25500. *
  25501. * @example
  25502. <example module="transcludeExample">
  25503. <file name="index.html">
  25504. <script>
  25505. angular.module('transcludeExample', [])
  25506. .directive('pane', function(){
  25507. return {
  25508. restrict: 'E',
  25509. transclude: true,
  25510. scope: { title:'@' },
  25511. template: '<div style="border: 1px solid black;">' +
  25512. '<div style="background-color: gray">{{title}}</div>' +
  25513. '<ng-transclude></ng-transclude>' +
  25514. '</div>'
  25515. };
  25516. })
  25517. .controller('ExampleController', ['$scope', function($scope) {
  25518. $scope.title = 'Lorem Ipsum';
  25519. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  25520. }]);
  25521. </script>
  25522. <div ng-controller="ExampleController">
  25523. <input ng-model="title" aria-label="title"> <br/>
  25524. <textarea ng-model="text" aria-label="text"></textarea> <br/>
  25525. <pane title="{{title}}">{{text}}</pane>
  25526. </div>
  25527. </file>
  25528. <file name="protractor.js" type="protractor">
  25529. it('should have transcluded', function() {
  25530. var titleElement = element(by.model('title'));
  25531. titleElement.clear();
  25532. titleElement.sendKeys('TITLE');
  25533. var textElement = element(by.model('text'));
  25534. textElement.clear();
  25535. textElement.sendKeys('TEXT');
  25536. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  25537. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  25538. });
  25539. </file>
  25540. </example>
  25541. *
  25542. */
  25543. var ngTranscludeDirective = ngDirective({
  25544. restrict: 'EAC',
  25545. link: function($scope, $element, $attrs, controller, $transclude) {
  25546. if (!$transclude) {
  25547. throw minErr('ngTransclude')('orphan',
  25548. 'Illegal use of ngTransclude directive in the template! ' +
  25549. 'No parent directive that requires a transclusion found. ' +
  25550. 'Element: {0}',
  25551. startingTag($element));
  25552. }
  25553. $transclude(function(clone) {
  25554. $element.empty();
  25555. $element.append(clone);
  25556. });
  25557. }
  25558. });
  25559. /**
  25560. * @ngdoc directive
  25561. * @name script
  25562. * @restrict E
  25563. *
  25564. * @description
  25565. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  25566. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  25567. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  25568. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  25569. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  25570. *
  25571. * @param {string} type Must be set to `'text/ng-template'`.
  25572. * @param {string} id Cache name of the template.
  25573. *
  25574. * @example
  25575. <example>
  25576. <file name="index.html">
  25577. <script type="text/ng-template" id="/tpl.html">
  25578. Content of the template.
  25579. </script>
  25580. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  25581. <div id="tpl-content" ng-include src="currentTpl"></div>
  25582. </file>
  25583. <file name="protractor.js" type="protractor">
  25584. it('should load template defined inside script tag', function() {
  25585. element(by.css('#tpl-link')).click();
  25586. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  25587. });
  25588. </file>
  25589. </example>
  25590. */
  25591. var scriptDirective = ['$templateCache', function($templateCache) {
  25592. return {
  25593. restrict: 'E',
  25594. terminal: true,
  25595. compile: function(element, attr) {
  25596. if (attr.type == 'text/ng-template') {
  25597. var templateUrl = attr.id,
  25598. text = element[0].text;
  25599. $templateCache.put(templateUrl, text);
  25600. }
  25601. }
  25602. };
  25603. }];
  25604. var noopNgModelController = { $setViewValue: noop, $render: noop };
  25605. /**
  25606. * @ngdoc type
  25607. * @name select.SelectController
  25608. * @description
  25609. * The controller for the `<select>` directive. This provides support for reading
  25610. * and writing the selected value(s) of the control and also coordinates dynamically
  25611. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  25612. */
  25613. var SelectController =
  25614. ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  25615. var self = this,
  25616. optionsMap = new HashMap();
  25617. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  25618. self.ngModelCtrl = noopNgModelController;
  25619. // The "unknown" option is one that is prepended to the list if the viewValue
  25620. // does not match any of the options. When it is rendered the value of the unknown
  25621. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  25622. //
  25623. // We can't just jqLite('<option>') since jqLite is not smart enough
  25624. // to create it in <select> and IE barfs otherwise.
  25625. self.unknownOption = jqLite(document.createElement('option'));
  25626. self.renderUnknownOption = function(val) {
  25627. var unknownVal = '? ' + hashKey(val) + ' ?';
  25628. self.unknownOption.val(unknownVal);
  25629. $element.prepend(self.unknownOption);
  25630. $element.val(unknownVal);
  25631. };
  25632. $scope.$on('$destroy', function() {
  25633. // disable unknown option so that we don't do work when the whole select is being destroyed
  25634. self.renderUnknownOption = noop;
  25635. });
  25636. self.removeUnknownOption = function() {
  25637. if (self.unknownOption.parent()) self.unknownOption.remove();
  25638. };
  25639. // Read the value of the select control, the implementation of this changes depending
  25640. // upon whether the select can have multiple values and whether ngOptions is at work.
  25641. self.readValue = function readSingleValue() {
  25642. self.removeUnknownOption();
  25643. return $element.val();
  25644. };
  25645. // Write the value to the select control, the implementation of this changes depending
  25646. // upon whether the select can have multiple values and whether ngOptions is at work.
  25647. self.writeValue = function writeSingleValue(value) {
  25648. if (self.hasOption(value)) {
  25649. self.removeUnknownOption();
  25650. $element.val(value);
  25651. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  25652. } else {
  25653. if (value == null && self.emptyOption) {
  25654. self.removeUnknownOption();
  25655. $element.val('');
  25656. } else {
  25657. self.renderUnknownOption(value);
  25658. }
  25659. }
  25660. };
  25661. // Tell the select control that an option, with the given value, has been added
  25662. self.addOption = function(value, element) {
  25663. assertNotHasOwnProperty(value, '"option value"');
  25664. if (value === '') {
  25665. self.emptyOption = element;
  25666. }
  25667. var count = optionsMap.get(value) || 0;
  25668. optionsMap.put(value, count + 1);
  25669. };
  25670. // Tell the select control that an option, with the given value, has been removed
  25671. self.removeOption = function(value) {
  25672. var count = optionsMap.get(value);
  25673. if (count) {
  25674. if (count === 1) {
  25675. optionsMap.remove(value);
  25676. if (value === '') {
  25677. self.emptyOption = undefined;
  25678. }
  25679. } else {
  25680. optionsMap.put(value, count - 1);
  25681. }
  25682. }
  25683. };
  25684. // Check whether the select control has an option matching the given value
  25685. self.hasOption = function(value) {
  25686. return !!optionsMap.get(value);
  25687. };
  25688. }];
  25689. /**
  25690. * @ngdoc directive
  25691. * @name select
  25692. * @restrict E
  25693. *
  25694. * @description
  25695. * HTML `SELECT` element with angular data-binding.
  25696. *
  25697. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  25698. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits such as reducing
  25699. * memory and increasing speed by not creating a new scope for each repeated instance, as well as providing
  25700. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  25701. * comprehension expression.
  25702. *
  25703. * When an item in the `<select>` menu is selected, the array element or object property
  25704. * represented by the selected option will be bound to the model identified by the `ngModel`
  25705. * directive.
  25706. *
  25707. * If the viewValue contains a value that doesn't match any of the options then the control
  25708. * will automatically add an "unknown" option, which it then removes when this is resolved.
  25709. *
  25710. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  25711. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  25712. * option. See example below for demonstration.
  25713. *
  25714. * <div class="alert alert-info">
  25715. * The value of a `select` directive used without `ngOptions` is always a string.
  25716. * When the model needs to be bound to a non-string value, you must either explictly convert it
  25717. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  25718. * This is because an option element can only be bound to string values at present.
  25719. * </div>
  25720. *
  25721. * ### Example (binding `select` to a non-string value)
  25722. *
  25723. * <example name="select-with-non-string-options" module="nonStringSelect">
  25724. * <file name="index.html">
  25725. * <select ng-model="model.id" convert-to-number>
  25726. * <option value="0">Zero</option>
  25727. * <option value="1">One</option>
  25728. * <option value="2">Two</option>
  25729. * </select>
  25730. * {{ model }}
  25731. * </file>
  25732. * <file name="app.js">
  25733. * angular.module('nonStringSelect', [])
  25734. * .run(function($rootScope) {
  25735. * $rootScope.model = { id: 2 };
  25736. * })
  25737. * .directive('convertToNumber', function() {
  25738. * return {
  25739. * require: 'ngModel',
  25740. * link: function(scope, element, attrs, ngModel) {
  25741. * ngModel.$parsers.push(function(val) {
  25742. * return parseInt(val, 10);
  25743. * });
  25744. * ngModel.$formatters.push(function(val) {
  25745. * return '' + val;
  25746. * });
  25747. * }
  25748. * };
  25749. * });
  25750. * </file>
  25751. * <file name="protractor.js" type="protractor">
  25752. * it('should initialize to model', function() {
  25753. * var select = element(by.css('select'));
  25754. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  25755. * });
  25756. * </file>
  25757. * </example>
  25758. *
  25759. */
  25760. var selectDirective = function() {
  25761. return {
  25762. restrict: 'E',
  25763. require: ['select', '?ngModel'],
  25764. controller: SelectController,
  25765. link: function(scope, element, attr, ctrls) {
  25766. // if ngModel is not defined, we don't need to do anything
  25767. var ngModelCtrl = ctrls[1];
  25768. if (!ngModelCtrl) return;
  25769. var selectCtrl = ctrls[0];
  25770. selectCtrl.ngModelCtrl = ngModelCtrl;
  25771. // We delegate rendering to the `writeValue` method, which can be changed
  25772. // if the select can have multiple selected values or if the options are being
  25773. // generated by `ngOptions`
  25774. ngModelCtrl.$render = function() {
  25775. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  25776. };
  25777. // When the selected item(s) changes we delegate getting the value of the select control
  25778. // to the `readValue` method, which can be changed if the select can have multiple
  25779. // selected values or if the options are being generated by `ngOptions`
  25780. element.on('change', function() {
  25781. scope.$apply(function() {
  25782. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  25783. });
  25784. });
  25785. // If the select allows multiple values then we need to modify how we read and write
  25786. // values from and to the control; also what it means for the value to be empty and
  25787. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  25788. // doesn't trigger rendering if only an item in the array changes.
  25789. if (attr.multiple) {
  25790. // Read value now needs to check each option to see if it is selected
  25791. selectCtrl.readValue = function readMultipleValue() {
  25792. var array = [];
  25793. forEach(element.find('option'), function(option) {
  25794. if (option.selected) {
  25795. array.push(option.value);
  25796. }
  25797. });
  25798. return array;
  25799. };
  25800. // Write value now needs to set the selected property of each matching option
  25801. selectCtrl.writeValue = function writeMultipleValue(value) {
  25802. var items = new HashMap(value);
  25803. forEach(element.find('option'), function(option) {
  25804. option.selected = isDefined(items.get(option.value));
  25805. });
  25806. };
  25807. // we have to do it on each watch since ngModel watches reference, but
  25808. // we need to work of an array, so we need to see if anything was inserted/removed
  25809. var lastView, lastViewRef = NaN;
  25810. scope.$watch(function selectMultipleWatch() {
  25811. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  25812. lastView = shallowCopy(ngModelCtrl.$viewValue);
  25813. ngModelCtrl.$render();
  25814. }
  25815. lastViewRef = ngModelCtrl.$viewValue;
  25816. });
  25817. // If we are a multiple select then value is now a collection
  25818. // so the meaning of $isEmpty changes
  25819. ngModelCtrl.$isEmpty = function(value) {
  25820. return !value || value.length === 0;
  25821. };
  25822. }
  25823. }
  25824. };
  25825. };
  25826. // The option directive is purely designed to communicate the existence (or lack of)
  25827. // of dynamically created (and destroyed) option elements to their containing select
  25828. // directive via its controller.
  25829. var optionDirective = ['$interpolate', function($interpolate) {
  25830. function chromeHack(optionElement) {
  25831. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  25832. // Adding an <option selected="selected"> element to a <select required="required"> should
  25833. // automatically select the new element
  25834. if (optionElement[0].hasAttribute('selected')) {
  25835. optionElement[0].selected = true;
  25836. }
  25837. }
  25838. return {
  25839. restrict: 'E',
  25840. priority: 100,
  25841. compile: function(element, attr) {
  25842. // If the value attribute is not defined then we fall back to the
  25843. // text content of the option element, which may be interpolated
  25844. if (isUndefined(attr.value)) {
  25845. var interpolateFn = $interpolate(element.text(), true);
  25846. if (!interpolateFn) {
  25847. attr.$set('value', element.text());
  25848. }
  25849. }
  25850. return function(scope, element, attr) {
  25851. // This is an optimization over using ^^ since we don't want to have to search
  25852. // all the way to the root of the DOM for every single option element
  25853. var selectCtrlName = '$selectController',
  25854. parent = element.parent(),
  25855. selectCtrl = parent.data(selectCtrlName) ||
  25856. parent.parent().data(selectCtrlName); // in case we are in optgroup
  25857. // Only update trigger option updates if this is an option within a `select`
  25858. // that also has `ngModel` attached
  25859. if (selectCtrl && selectCtrl.ngModelCtrl) {
  25860. if (interpolateFn) {
  25861. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  25862. attr.$set('value', newVal);
  25863. if (oldVal !== newVal) {
  25864. selectCtrl.removeOption(oldVal);
  25865. }
  25866. selectCtrl.addOption(newVal, element);
  25867. selectCtrl.ngModelCtrl.$render();
  25868. chromeHack(element);
  25869. });
  25870. } else {
  25871. selectCtrl.addOption(attr.value, element);
  25872. selectCtrl.ngModelCtrl.$render();
  25873. chromeHack(element);
  25874. }
  25875. element.on('$destroy', function() {
  25876. selectCtrl.removeOption(attr.value);
  25877. selectCtrl.ngModelCtrl.$render();
  25878. });
  25879. }
  25880. };
  25881. }
  25882. };
  25883. }];
  25884. var styleDirective = valueFn({
  25885. restrict: 'E',
  25886. terminal: false
  25887. });
  25888. var requiredDirective = function() {
  25889. return {
  25890. restrict: 'A',
  25891. require: '?ngModel',
  25892. link: function(scope, elm, attr, ctrl) {
  25893. if (!ctrl) return;
  25894. attr.required = true; // force truthy in case we are on non input element
  25895. ctrl.$validators.required = function(modelValue, viewValue) {
  25896. return !attr.required || !ctrl.$isEmpty(viewValue);
  25897. };
  25898. attr.$observe('required', function() {
  25899. ctrl.$validate();
  25900. });
  25901. }
  25902. };
  25903. };
  25904. var patternDirective = function() {
  25905. return {
  25906. restrict: 'A',
  25907. require: '?ngModel',
  25908. link: function(scope, elm, attr, ctrl) {
  25909. if (!ctrl) return;
  25910. var regexp, patternExp = attr.ngPattern || attr.pattern;
  25911. attr.$observe('pattern', function(regex) {
  25912. if (isString(regex) && regex.length > 0) {
  25913. regex = new RegExp('^' + regex + '$');
  25914. }
  25915. if (regex && !regex.test) {
  25916. throw minErr('ngPattern')('noregexp',
  25917. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  25918. regex, startingTag(elm));
  25919. }
  25920. regexp = regex || undefined;
  25921. ctrl.$validate();
  25922. });
  25923. ctrl.$validators.pattern = function(value) {
  25924. return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
  25925. };
  25926. }
  25927. };
  25928. };
  25929. var maxlengthDirective = function() {
  25930. return {
  25931. restrict: 'A',
  25932. require: '?ngModel',
  25933. link: function(scope, elm, attr, ctrl) {
  25934. if (!ctrl) return;
  25935. var maxlength = -1;
  25936. attr.$observe('maxlength', function(value) {
  25937. var intVal = toInt(value);
  25938. maxlength = isNaN(intVal) ? -1 : intVal;
  25939. ctrl.$validate();
  25940. });
  25941. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  25942. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  25943. };
  25944. }
  25945. };
  25946. };
  25947. var minlengthDirective = function() {
  25948. return {
  25949. restrict: 'A',
  25950. require: '?ngModel',
  25951. link: function(scope, elm, attr, ctrl) {
  25952. if (!ctrl) return;
  25953. var minlength = 0;
  25954. attr.$observe('minlength', function(value) {
  25955. minlength = toInt(value) || 0;
  25956. ctrl.$validate();
  25957. });
  25958. ctrl.$validators.minlength = function(modelValue, viewValue) {
  25959. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  25960. };
  25961. }
  25962. };
  25963. };
  25964. if (window.angular.bootstrap) {
  25965. //AngularJS is already loaded, so we can return here...
  25966. console.log('WARNING: Tried to load angular more than once.');
  25967. return;
  25968. }
  25969. //try to bind to jquery now so that one can write jqLite(document).ready()
  25970. //but we will rebind on bootstrap again.
  25971. bindJQuery();
  25972. publishExternalAPI(angular);
  25973. angular.module("ngLocale", [], ["$provide", function($provide) {
  25974. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  25975. function getDecimals(n) {
  25976. n = n + '';
  25977. var i = n.indexOf('.');
  25978. return (i == -1) ? 0 : n.length - i - 1;
  25979. }
  25980. function getVF(n, opt_precision) {
  25981. var v = opt_precision;
  25982. if (undefined === v) {
  25983. v = Math.min(getDecimals(n), 3);
  25984. }
  25985. var base = Math.pow(10, v);
  25986. var f = ((n * base) | 0) % base;
  25987. return {v: v, f: f};
  25988. }
  25989. $provide.value("$locale", {
  25990. "DATETIME_FORMATS": {
  25991. "AMPMS": [
  25992. "AM",
  25993. "PM"
  25994. ],
  25995. "DAY": [
  25996. "Sunday",
  25997. "Monday",
  25998. "Tuesday",
  25999. "Wednesday",
  26000. "Thursday",
  26001. "Friday",
  26002. "Saturday"
  26003. ],
  26004. "ERANAMES": [
  26005. "Before Christ",
  26006. "Anno Domini"
  26007. ],
  26008. "ERAS": [
  26009. "BC",
  26010. "AD"
  26011. ],
  26012. "FIRSTDAYOFWEEK": 6,
  26013. "MONTH": [
  26014. "January",
  26015. "February",
  26016. "March",
  26017. "April",
  26018. "May",
  26019. "June",
  26020. "July",
  26021. "August",
  26022. "September",
  26023. "October",
  26024. "November",
  26025. "December"
  26026. ],
  26027. "SHORTDAY": [
  26028. "Sun",
  26029. "Mon",
  26030. "Tue",
  26031. "Wed",
  26032. "Thu",
  26033. "Fri",
  26034. "Sat"
  26035. ],
  26036. "SHORTMONTH": [
  26037. "Jan",
  26038. "Feb",
  26039. "Mar",
  26040. "Apr",
  26041. "May",
  26042. "Jun",
  26043. "Jul",
  26044. "Aug",
  26045. "Sep",
  26046. "Oct",
  26047. "Nov",
  26048. "Dec"
  26049. ],
  26050. "WEEKENDRANGE": [
  26051. 5,
  26052. 6
  26053. ],
  26054. "fullDate": "EEEE, MMMM d, y",
  26055. "longDate": "MMMM d, y",
  26056. "medium": "MMM d, y h:mm:ss a",
  26057. "mediumDate": "MMM d, y",
  26058. "mediumTime": "h:mm:ss a",
  26059. "short": "M/d/yy h:mm a",
  26060. "shortDate": "M/d/yy",
  26061. "shortTime": "h:mm a"
  26062. },
  26063. "NUMBER_FORMATS": {
  26064. "CURRENCY_SYM": "$",
  26065. "DECIMAL_SEP": ".",
  26066. "GROUP_SEP": ",",
  26067. "PATTERNS": [
  26068. {
  26069. "gSize": 3,
  26070. "lgSize": 3,
  26071. "maxFrac": 3,
  26072. "minFrac": 0,
  26073. "minInt": 1,
  26074. "negPre": "-",
  26075. "negSuf": "",
  26076. "posPre": "",
  26077. "posSuf": ""
  26078. },
  26079. {
  26080. "gSize": 3,
  26081. "lgSize": 3,
  26082. "maxFrac": 2,
  26083. "minFrac": 2,
  26084. "minInt": 1,
  26085. "negPre": "-\u00a4",
  26086. "negSuf": "",
  26087. "posPre": "\u00a4",
  26088. "posSuf": ""
  26089. }
  26090. ]
  26091. },
  26092. "id": "en-us",
  26093. "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
  26094. });
  26095. }]);
  26096. jqLite(document).ready(function() {
  26097. angularInit(document, bootstrap);
  26098. });
  26099. })(window, document);
  26100. !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');