Keine Beschreibung

angular.js 1.2MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372
  1. /**
  2. * @license AngularJS v1.6.4
  3. * (c) 2010-2017 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window) {'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 code = arguments[0],
  40. template = arguments[1],
  41. message = '[' + (module ? module + ':' : '') + code + '] ',
  42. templateArgs = sliceArgs(arguments, 2).map(function(arg) {
  43. return toDebugString(arg, minErrConfig.objectMaxDepth);
  44. }),
  45. paramPrefix, i;
  46. message += template.replace(/\{\d+\}/g, function(match) {
  47. var index = +match.slice(1, -1);
  48. if (index < templateArgs.length) {
  49. return templateArgs[index];
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.6.4/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]);
  57. }
  58. return new ErrorConstructor(message);
  59. };
  60. }
  61. /* We need to tell ESLint what variables are being exported */
  62. /* exported
  63. angular,
  64. msie,
  65. jqLite,
  66. jQuery,
  67. slice,
  68. splice,
  69. push,
  70. toString,
  71. minErrConfig,
  72. errorHandlingConfig,
  73. isValidObjectMaxDepth,
  74. ngMinErr,
  75. angularModule,
  76. uid,
  77. REGEX_STRING_REGEXP,
  78. VALIDITY_STATE_PROPERTY,
  79. lowercase,
  80. uppercase,
  81. manualLowercase,
  82. manualUppercase,
  83. nodeName_,
  84. isArrayLike,
  85. forEach,
  86. forEachSorted,
  87. reverseParams,
  88. nextUid,
  89. setHashKey,
  90. extend,
  91. toInt,
  92. inherit,
  93. merge,
  94. noop,
  95. identity,
  96. valueFn,
  97. isUndefined,
  98. isDefined,
  99. isObject,
  100. isBlankObject,
  101. isString,
  102. isNumber,
  103. isNumberNaN,
  104. isDate,
  105. isArray,
  106. isFunction,
  107. isRegExp,
  108. isWindow,
  109. isScope,
  110. isFile,
  111. isFormData,
  112. isBlob,
  113. isBoolean,
  114. isPromiseLike,
  115. trim,
  116. escapeForRegexp,
  117. isElement,
  118. makeMap,
  119. includes,
  120. arrayRemove,
  121. copy,
  122. simpleCompare,
  123. equals,
  124. csp,
  125. jq,
  126. concat,
  127. sliceArgs,
  128. bind,
  129. toJsonReplacer,
  130. toJson,
  131. fromJson,
  132. convertTimezoneToLocal,
  133. timezoneToOffset,
  134. startingTag,
  135. tryDecodeURIComponent,
  136. parseKeyValue,
  137. toKeyValue,
  138. encodeUriSegment,
  139. encodeUriQuery,
  140. angularInit,
  141. bootstrap,
  142. getTestability,
  143. snake_case,
  144. bindJQuery,
  145. assertArg,
  146. assertArgFn,
  147. assertNotHasOwnProperty,
  148. getter,
  149. getBlockNodes,
  150. hasOwnProperty,
  151. createMap,
  152. stringify,
  153. NODE_TYPE_ELEMENT,
  154. NODE_TYPE_ATTRIBUTE,
  155. NODE_TYPE_TEXT,
  156. NODE_TYPE_COMMENT,
  157. NODE_TYPE_DOCUMENT,
  158. NODE_TYPE_DOCUMENT_FRAGMENT
  159. */
  160. ////////////////////////////////////
  161. /**
  162. * @ngdoc module
  163. * @name ng
  164. * @module ng
  165. * @installation
  166. * @description
  167. *
  168. * # ng (core module)
  169. * The ng module is loaded by default when an AngularJS application is started. The module itself
  170. * contains the essential components for an AngularJS application to function. The table below
  171. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  172. * components available within this core module.
  173. *
  174. * <div doc-module-components="ng"></div>
  175. */
  176. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  177. // The name of a form control's ValidityState property.
  178. // This is used so that it's possible for internal tests to create mock ValidityStates.
  179. var VALIDITY_STATE_PROPERTY = 'validity';
  180. var hasOwnProperty = Object.prototype.hasOwnProperty;
  181. var minErrConfig = {
  182. objectMaxDepth: 5
  183. };
  184. /**
  185. * @ngdoc function
  186. * @name angular.errorHandlingConfig
  187. * @module ng
  188. * @kind function
  189. *
  190. * @description
  191. * Configure several aspects of error handling in AngularJS if used as a setter or return the
  192. * current configuration if used as a getter. The following options are supported:
  193. *
  194. * - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages.
  195. *
  196. * Omitted or undefined options will leave the corresponding configuration values unchanged.
  197. *
  198. * @param {Object=} config - The configuration object. May only contain the options that need to be
  199. * updated. Supported keys:
  200. *
  201. * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a
  202. * non-positive or non-numeric value, removes the max depth limit.
  203. * Default: 5
  204. */
  205. function errorHandlingConfig(config) {
  206. if (isObject(config)) {
  207. if (isDefined(config.objectMaxDepth)) {
  208. minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN;
  209. }
  210. } else {
  211. return minErrConfig;
  212. }
  213. }
  214. /**
  215. * @private
  216. * @param {Number} maxDepth
  217. * @return {boolean}
  218. */
  219. function isValidObjectMaxDepth(maxDepth) {
  220. return isNumber(maxDepth) && maxDepth > 0;
  221. }
  222. /**
  223. * @ngdoc function
  224. * @name angular.lowercase
  225. * @module ng
  226. * @kind function
  227. *
  228. * @deprecated
  229. * sinceVersion="1.5.0"
  230. * removeVersion="1.7.0"
  231. * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead.
  232. *
  233. * @description Converts the specified string to lowercase.
  234. * @param {string} string String to be converted to lowercase.
  235. * @returns {string} Lowercased string.
  236. */
  237. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  238. /**
  239. * @ngdoc function
  240. * @name angular.uppercase
  241. * @module ng
  242. * @kind function
  243. *
  244. * @deprecated
  245. * sinceVersion="1.5.0"
  246. * removeVersion="1.7.0"
  247. * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead.
  248. *
  249. * @description Converts the specified string to uppercase.
  250. * @param {string} string String to be converted to uppercase.
  251. * @returns {string} Uppercased string.
  252. */
  253. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  254. var manualLowercase = function(s) {
  255. /* eslint-disable no-bitwise */
  256. return isString(s)
  257. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  258. : s;
  259. /* eslint-enable */
  260. };
  261. var manualUppercase = function(s) {
  262. /* eslint-disable no-bitwise */
  263. return isString(s)
  264. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  265. : s;
  266. /* eslint-enable */
  267. };
  268. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  269. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  270. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  271. if ('i' !== 'I'.toLowerCase()) {
  272. lowercase = manualLowercase;
  273. uppercase = manualUppercase;
  274. }
  275. var
  276. msie, // holds major version number for IE, or NaN if UA is not IE.
  277. jqLite, // delay binding since jQuery could be loaded after us.
  278. jQuery, // delay binding
  279. slice = [].slice,
  280. splice = [].splice,
  281. push = [].push,
  282. toString = Object.prototype.toString,
  283. getPrototypeOf = Object.getPrototypeOf,
  284. ngMinErr = minErr('ng'),
  285. /** @name angular */
  286. angular = window.angular || (window.angular = {}),
  287. angularModule,
  288. uid = 0;
  289. // Support: IE 9-11 only
  290. /**
  291. * documentMode is an IE-only property
  292. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  293. */
  294. msie = window.document.documentMode;
  295. /**
  296. * @private
  297. * @param {*} obj
  298. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  299. * String ...)
  300. */
  301. function isArrayLike(obj) {
  302. // `null`, `undefined` and `window` are not array-like
  303. if (obj == null || isWindow(obj)) return false;
  304. // arrays, strings and jQuery/jqLite objects are array like
  305. // * jqLite is either the jQuery or jqLite constructor function
  306. // * we have to check the existence of jqLite first as this method is called
  307. // via the forEach method when constructing the jqLite object in the first place
  308. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  309. // Support: iOS 8.2 (not reproducible in simulator)
  310. // "length" in obj used to prevent JIT error (gh-11508)
  311. var length = 'length' in Object(obj) && obj.length;
  312. // NodeList objects (with `item` method) and
  313. // other objects with suitable length characteristics are array-like
  314. return isNumber(length) &&
  315. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');
  316. }
  317. /**
  318. * @ngdoc function
  319. * @name angular.forEach
  320. * @module ng
  321. * @kind function
  322. *
  323. * @description
  324. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  325. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  326. * is the value of an object property or an array element, `key` is the object property key or
  327. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  328. *
  329. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  330. * using the `hasOwnProperty` method.
  331. *
  332. * Unlike ES262's
  333. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  334. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  335. * return the value provided.
  336. *
  337. ```js
  338. var values = {name: 'misko', gender: 'male'};
  339. var log = [];
  340. angular.forEach(values, function(value, key) {
  341. this.push(key + ': ' + value);
  342. }, log);
  343. expect(log).toEqual(['name: misko', 'gender: male']);
  344. ```
  345. *
  346. * @param {Object|Array} obj Object to iterate over.
  347. * @param {Function} iterator Iterator function.
  348. * @param {Object=} context Object to become context (`this`) for the iterator function.
  349. * @returns {Object|Array} Reference to `obj`.
  350. */
  351. function forEach(obj, iterator, context) {
  352. var key, length;
  353. if (obj) {
  354. if (isFunction(obj)) {
  355. for (key in obj) {
  356. if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
  357. iterator.call(context, obj[key], key, obj);
  358. }
  359. }
  360. } else if (isArray(obj) || isArrayLike(obj)) {
  361. var isPrimitive = typeof obj !== 'object';
  362. for (key = 0, length = obj.length; key < length; key++) {
  363. if (isPrimitive || key in obj) {
  364. iterator.call(context, obj[key], key, obj);
  365. }
  366. }
  367. } else if (obj.forEach && obj.forEach !== forEach) {
  368. obj.forEach(iterator, context, obj);
  369. } else if (isBlankObject(obj)) {
  370. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  371. for (key in obj) {
  372. iterator.call(context, obj[key], key, obj);
  373. }
  374. } else if (typeof obj.hasOwnProperty === 'function') {
  375. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  376. for (key in obj) {
  377. if (obj.hasOwnProperty(key)) {
  378. iterator.call(context, obj[key], key, obj);
  379. }
  380. }
  381. } else {
  382. // Slow path for objects which do not have a method `hasOwnProperty`
  383. for (key in obj) {
  384. if (hasOwnProperty.call(obj, key)) {
  385. iterator.call(context, obj[key], key, obj);
  386. }
  387. }
  388. }
  389. }
  390. return obj;
  391. }
  392. function forEachSorted(obj, iterator, context) {
  393. var keys = Object.keys(obj).sort();
  394. for (var i = 0; i < keys.length; i++) {
  395. iterator.call(context, obj[keys[i]], keys[i]);
  396. }
  397. return keys;
  398. }
  399. /**
  400. * when using forEach the params are value, key, but it is often useful to have key, value.
  401. * @param {function(string, *)} iteratorFn
  402. * @returns {function(*, string)}
  403. */
  404. function reverseParams(iteratorFn) {
  405. return function(value, key) {iteratorFn(key, value);};
  406. }
  407. /**
  408. * A consistent way of creating unique IDs in angular.
  409. *
  410. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  411. * we hit number precision issues in JavaScript.
  412. *
  413. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  414. *
  415. * @returns {number} an unique alpha-numeric string
  416. */
  417. function nextUid() {
  418. return ++uid;
  419. }
  420. /**
  421. * Set or clear the hashkey for an object.
  422. * @param obj object
  423. * @param h the hashkey (!truthy to delete the hashkey)
  424. */
  425. function setHashKey(obj, h) {
  426. if (h) {
  427. obj.$$hashKey = h;
  428. } else {
  429. delete obj.$$hashKey;
  430. }
  431. }
  432. function baseExtend(dst, objs, deep) {
  433. var h = dst.$$hashKey;
  434. for (var i = 0, ii = objs.length; i < ii; ++i) {
  435. var obj = objs[i];
  436. if (!isObject(obj) && !isFunction(obj)) continue;
  437. var keys = Object.keys(obj);
  438. for (var j = 0, jj = keys.length; j < jj; j++) {
  439. var key = keys[j];
  440. var src = obj[key];
  441. if (deep && isObject(src)) {
  442. if (isDate(src)) {
  443. dst[key] = new Date(src.valueOf());
  444. } else if (isRegExp(src)) {
  445. dst[key] = new RegExp(src);
  446. } else if (src.nodeName) {
  447. dst[key] = src.cloneNode(true);
  448. } else if (isElement(src)) {
  449. dst[key] = src.clone();
  450. } else {
  451. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  452. baseExtend(dst[key], [src], true);
  453. }
  454. } else {
  455. dst[key] = src;
  456. }
  457. }
  458. }
  459. setHashKey(dst, h);
  460. return dst;
  461. }
  462. /**
  463. * @ngdoc function
  464. * @name angular.extend
  465. * @module ng
  466. * @kind function
  467. *
  468. * @description
  469. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  470. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  471. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  472. *
  473. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  474. * {@link angular.merge} for this.
  475. *
  476. * @param {Object} dst Destination object.
  477. * @param {...Object} src Source object(s).
  478. * @returns {Object} Reference to `dst`.
  479. */
  480. function extend(dst) {
  481. return baseExtend(dst, slice.call(arguments, 1), false);
  482. }
  483. /**
  484. * @ngdoc function
  485. * @name angular.merge
  486. * @module ng
  487. * @kind function
  488. *
  489. * @description
  490. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  491. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  492. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  493. *
  494. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  495. * objects, performing a deep copy.
  496. *
  497. * @param {Object} dst Destination object.
  498. * @param {...Object} src Source object(s).
  499. * @returns {Object} Reference to `dst`.
  500. */
  501. function merge(dst) {
  502. return baseExtend(dst, slice.call(arguments, 1), true);
  503. }
  504. function toInt(str) {
  505. return parseInt(str, 10);
  506. }
  507. var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
  508. // eslint-disable-next-line no-self-compare
  509. return num !== num;
  510. };
  511. function inherit(parent, extra) {
  512. return extend(Object.create(parent), extra);
  513. }
  514. /**
  515. * @ngdoc function
  516. * @name angular.noop
  517. * @module ng
  518. * @kind function
  519. *
  520. * @description
  521. * A function that performs no operations. This function can be useful when writing code in the
  522. * functional style.
  523. ```js
  524. function foo(callback) {
  525. var result = calculateResult();
  526. (callback || angular.noop)(result);
  527. }
  528. ```
  529. */
  530. function noop() {}
  531. noop.$inject = [];
  532. /**
  533. * @ngdoc function
  534. * @name angular.identity
  535. * @module ng
  536. * @kind function
  537. *
  538. * @description
  539. * A function that returns its first argument. This function is useful when writing code in the
  540. * functional style.
  541. *
  542. ```js
  543. function transformer(transformationFn, value) {
  544. return (transformationFn || angular.identity)(value);
  545. };
  546. // E.g.
  547. function getResult(fn, input) {
  548. return (fn || angular.identity)(input);
  549. };
  550. getResult(function(n) { return n * 2; }, 21); // returns 42
  551. getResult(null, 21); // returns 21
  552. getResult(undefined, 21); // returns 21
  553. ```
  554. *
  555. * @param {*} value to be returned.
  556. * @returns {*} the value passed in.
  557. */
  558. function identity($) {return $;}
  559. identity.$inject = [];
  560. function valueFn(value) {return function valueRef() {return value;};}
  561. function hasCustomToString(obj) {
  562. return isFunction(obj.toString) && obj.toString !== toString;
  563. }
  564. /**
  565. * @ngdoc function
  566. * @name angular.isUndefined
  567. * @module ng
  568. * @kind function
  569. *
  570. * @description
  571. * Determines if a reference is undefined.
  572. *
  573. * @param {*} value Reference to check.
  574. * @returns {boolean} True if `value` is undefined.
  575. */
  576. function isUndefined(value) {return typeof value === 'undefined';}
  577. /**
  578. * @ngdoc function
  579. * @name angular.isDefined
  580. * @module ng
  581. * @kind function
  582. *
  583. * @description
  584. * Determines if a reference is defined.
  585. *
  586. * @param {*} value Reference to check.
  587. * @returns {boolean} True if `value` is defined.
  588. */
  589. function isDefined(value) {return typeof value !== 'undefined';}
  590. /**
  591. * @ngdoc function
  592. * @name angular.isObject
  593. * @module ng
  594. * @kind function
  595. *
  596. * @description
  597. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  598. * considered to be objects. Note that JavaScript arrays are objects.
  599. *
  600. * @param {*} value Reference to check.
  601. * @returns {boolean} True if `value` is an `Object` but not `null`.
  602. */
  603. function isObject(value) {
  604. // http://jsperf.com/isobject4
  605. return value !== null && typeof value === 'object';
  606. }
  607. /**
  608. * Determine if a value is an object with a null prototype
  609. *
  610. * @returns {boolean} True if `value` is an `Object` with a null prototype
  611. */
  612. function isBlankObject(value) {
  613. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  614. }
  615. /**
  616. * @ngdoc function
  617. * @name angular.isString
  618. * @module ng
  619. * @kind function
  620. *
  621. * @description
  622. * Determines if a reference is a `String`.
  623. *
  624. * @param {*} value Reference to check.
  625. * @returns {boolean} True if `value` is a `String`.
  626. */
  627. function isString(value) {return typeof value === 'string';}
  628. /**
  629. * @ngdoc function
  630. * @name angular.isNumber
  631. * @module ng
  632. * @kind function
  633. *
  634. * @description
  635. * Determines if a reference is a `Number`.
  636. *
  637. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  638. *
  639. * If you wish to exclude these then you can use the native
  640. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  641. * method.
  642. *
  643. * @param {*} value Reference to check.
  644. * @returns {boolean} True if `value` is a `Number`.
  645. */
  646. function isNumber(value) {return typeof value === 'number';}
  647. /**
  648. * @ngdoc function
  649. * @name angular.isDate
  650. * @module ng
  651. * @kind function
  652. *
  653. * @description
  654. * Determines if a value is a date.
  655. *
  656. * @param {*} value Reference to check.
  657. * @returns {boolean} True if `value` is a `Date`.
  658. */
  659. function isDate(value) {
  660. return toString.call(value) === '[object Date]';
  661. }
  662. /**
  663. * @ngdoc function
  664. * @name angular.isArray
  665. * @module ng
  666. * @kind function
  667. *
  668. * @description
  669. * Determines if a reference is an `Array`. Alias of Array.isArray.
  670. *
  671. * @param {*} value Reference to check.
  672. * @returns {boolean} True if `value` is an `Array`.
  673. */
  674. var isArray = Array.isArray;
  675. /**
  676. * @ngdoc function
  677. * @name angular.isFunction
  678. * @module ng
  679. * @kind function
  680. *
  681. * @description
  682. * Determines if a reference is a `Function`.
  683. *
  684. * @param {*} value Reference to check.
  685. * @returns {boolean} True if `value` is a `Function`.
  686. */
  687. function isFunction(value) {return typeof value === 'function';}
  688. /**
  689. * Determines if a value is a regular expression object.
  690. *
  691. * @private
  692. * @param {*} value Reference to check.
  693. * @returns {boolean} True if `value` is a `RegExp`.
  694. */
  695. function isRegExp(value) {
  696. return toString.call(value) === '[object RegExp]';
  697. }
  698. /**
  699. * Checks if `obj` is a window object.
  700. *
  701. * @private
  702. * @param {*} obj Object to check
  703. * @returns {boolean} True if `obj` is a window obj.
  704. */
  705. function isWindow(obj) {
  706. return obj && obj.window === obj;
  707. }
  708. function isScope(obj) {
  709. return obj && obj.$evalAsync && obj.$watch;
  710. }
  711. function isFile(obj) {
  712. return toString.call(obj) === '[object File]';
  713. }
  714. function isFormData(obj) {
  715. return toString.call(obj) === '[object FormData]';
  716. }
  717. function isBlob(obj) {
  718. return toString.call(obj) === '[object Blob]';
  719. }
  720. function isBoolean(value) {
  721. return typeof value === 'boolean';
  722. }
  723. function isPromiseLike(obj) {
  724. return obj && isFunction(obj.then);
  725. }
  726. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
  727. function isTypedArray(value) {
  728. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  729. }
  730. function isArrayBuffer(obj) {
  731. return toString.call(obj) === '[object ArrayBuffer]';
  732. }
  733. var trim = function(value) {
  734. return isString(value) ? value.trim() : value;
  735. };
  736. // Copied from:
  737. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  738. // Prereq: s is a string.
  739. var escapeForRegexp = function(s) {
  740. return s
  741. .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
  742. // eslint-disable-next-line no-control-regex
  743. .replace(/\x08/g, '\\x08');
  744. };
  745. /**
  746. * @ngdoc function
  747. * @name angular.isElement
  748. * @module ng
  749. * @kind function
  750. *
  751. * @description
  752. * Determines if a reference is a DOM element (or wrapped jQuery element).
  753. *
  754. * @param {*} value Reference to check.
  755. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  756. */
  757. function isElement(node) {
  758. return !!(node &&
  759. (node.nodeName // We are a direct element.
  760. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  761. }
  762. /**
  763. * @param str 'key1,key2,...'
  764. * @returns {object} in the form of {key1:true, key2:true, ...}
  765. */
  766. function makeMap(str) {
  767. var obj = {}, items = str.split(','), i;
  768. for (i = 0; i < items.length; i++) {
  769. obj[items[i]] = true;
  770. }
  771. return obj;
  772. }
  773. function nodeName_(element) {
  774. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  775. }
  776. function includes(array, obj) {
  777. return Array.prototype.indexOf.call(array, obj) !== -1;
  778. }
  779. function arrayRemove(array, value) {
  780. var index = array.indexOf(value);
  781. if (index >= 0) {
  782. array.splice(index, 1);
  783. }
  784. return index;
  785. }
  786. /**
  787. * @ngdoc function
  788. * @name angular.copy
  789. * @module ng
  790. * @kind function
  791. *
  792. * @description
  793. * Creates a deep copy of `source`, which should be an object or an array.
  794. *
  795. * * If no destination is supplied, a copy of the object or array is created.
  796. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  797. * are deleted and then all elements/properties from the source are copied to it.
  798. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  799. * * If `source` is identical to `destination` an exception will be thrown.
  800. *
  801. * <br />
  802. * <div class="alert alert-warning">
  803. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  804. * and on `destination`) will be ignored.
  805. * </div>
  806. *
  807. * @param {*} source The source that will be used to make a copy.
  808. * Can be any type, including primitives, `null`, and `undefined`.
  809. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  810. * provided, must be of the same type as `source`.
  811. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  812. *
  813. * @example
  814. <example module="copyExample" name="angular-copy">
  815. <file name="index.html">
  816. <div ng-controller="ExampleController">
  817. <form novalidate class="simple-form">
  818. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  819. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  820. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  821. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  822. <button ng-click="reset()">RESET</button>
  823. <button ng-click="update(user)">SAVE</button>
  824. </form>
  825. <pre>form = {{user | json}}</pre>
  826. <pre>master = {{master | json}}</pre>
  827. </div>
  828. </file>
  829. <file name="script.js">
  830. // Module: copyExample
  831. angular.
  832. module('copyExample', []).
  833. controller('ExampleController', ['$scope', function($scope) {
  834. $scope.master = {};
  835. $scope.reset = function() {
  836. // Example with 1 argument
  837. $scope.user = angular.copy($scope.master);
  838. };
  839. $scope.update = function(user) {
  840. // Example with 2 arguments
  841. angular.copy(user, $scope.master);
  842. };
  843. $scope.reset();
  844. }]);
  845. </file>
  846. </example>
  847. */
  848. function copy(source, destination, maxDepth) {
  849. var stackSource = [];
  850. var stackDest = [];
  851. maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN;
  852. if (destination) {
  853. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  854. throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
  855. }
  856. if (source === destination) {
  857. throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
  858. }
  859. // Empty the destination object
  860. if (isArray(destination)) {
  861. destination.length = 0;
  862. } else {
  863. forEach(destination, function(value, key) {
  864. if (key !== '$$hashKey') {
  865. delete destination[key];
  866. }
  867. });
  868. }
  869. stackSource.push(source);
  870. stackDest.push(destination);
  871. return copyRecurse(source, destination, maxDepth);
  872. }
  873. return copyElement(source, maxDepth);
  874. function copyRecurse(source, destination, maxDepth) {
  875. maxDepth--;
  876. if (maxDepth < 0) {
  877. return '...';
  878. }
  879. var h = destination.$$hashKey;
  880. var key;
  881. if (isArray(source)) {
  882. for (var i = 0, ii = source.length; i < ii; i++) {
  883. destination.push(copyElement(source[i], maxDepth));
  884. }
  885. } else if (isBlankObject(source)) {
  886. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  887. for (key in source) {
  888. destination[key] = copyElement(source[key], maxDepth);
  889. }
  890. } else if (source && typeof source.hasOwnProperty === 'function') {
  891. // Slow path, which must rely on hasOwnProperty
  892. for (key in source) {
  893. if (source.hasOwnProperty(key)) {
  894. destination[key] = copyElement(source[key], maxDepth);
  895. }
  896. }
  897. } else {
  898. // Slowest path --- hasOwnProperty can't be called as a method
  899. for (key in source) {
  900. if (hasOwnProperty.call(source, key)) {
  901. destination[key] = copyElement(source[key], maxDepth);
  902. }
  903. }
  904. }
  905. setHashKey(destination, h);
  906. return destination;
  907. }
  908. function copyElement(source, maxDepth) {
  909. // Simple values
  910. if (!isObject(source)) {
  911. return source;
  912. }
  913. // Already copied values
  914. var index = stackSource.indexOf(source);
  915. if (index !== -1) {
  916. return stackDest[index];
  917. }
  918. if (isWindow(source) || isScope(source)) {
  919. throw ngMinErr('cpws',
  920. 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
  921. }
  922. var needsRecurse = false;
  923. var destination = copyType(source);
  924. if (destination === undefined) {
  925. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  926. needsRecurse = true;
  927. }
  928. stackSource.push(source);
  929. stackDest.push(destination);
  930. return needsRecurse
  931. ? copyRecurse(source, destination, maxDepth)
  932. : destination;
  933. }
  934. function copyType(source) {
  935. switch (toString.call(source)) {
  936. case '[object Int8Array]':
  937. case '[object Int16Array]':
  938. case '[object Int32Array]':
  939. case '[object Float32Array]':
  940. case '[object Float64Array]':
  941. case '[object Uint8Array]':
  942. case '[object Uint8ClampedArray]':
  943. case '[object Uint16Array]':
  944. case '[object Uint32Array]':
  945. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  946. case '[object ArrayBuffer]':
  947. // Support: IE10
  948. if (!source.slice) {
  949. // If we're in this case we know the environment supports ArrayBuffer
  950. /* eslint-disable no-undef */
  951. var copied = new ArrayBuffer(source.byteLength);
  952. new Uint8Array(copied).set(new Uint8Array(source));
  953. /* eslint-enable */
  954. return copied;
  955. }
  956. return source.slice(0);
  957. case '[object Boolean]':
  958. case '[object Number]':
  959. case '[object String]':
  960. case '[object Date]':
  961. return new source.constructor(source.valueOf());
  962. case '[object RegExp]':
  963. var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
  964. re.lastIndex = source.lastIndex;
  965. return re;
  966. case '[object Blob]':
  967. return new source.constructor([source], {type: source.type});
  968. }
  969. if (isFunction(source.cloneNode)) {
  970. return source.cloneNode(true);
  971. }
  972. }
  973. }
  974. // eslint-disable-next-line no-self-compare
  975. function simpleCompare(a, b) { return a === b || (a !== a && b !== b); }
  976. /**
  977. * @ngdoc function
  978. * @name angular.equals
  979. * @module ng
  980. * @kind function
  981. *
  982. * @description
  983. * Determines if two objects or two values are equivalent. Supports value types, regular
  984. * expressions, arrays and objects.
  985. *
  986. * Two objects or values are considered equivalent if at least one of the following is true:
  987. *
  988. * * Both objects or values pass `===` comparison.
  989. * * Both objects or values are of the same type and all of their properties are equal by
  990. * comparing them with `angular.equals`.
  991. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  992. * * Both values represent the same regular expression (In JavaScript,
  993. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  994. * representation matches).
  995. *
  996. * During a property comparison, properties of `function` type and properties with names
  997. * that begin with `$` are ignored.
  998. *
  999. * Scope and DOMWindow objects are being compared only by identify (`===`).
  1000. *
  1001. * @param {*} o1 Object or value to compare.
  1002. * @param {*} o2 Object or value to compare.
  1003. * @returns {boolean} True if arguments are equal.
  1004. *
  1005. * @example
  1006. <example module="equalsExample" name="equalsExample">
  1007. <file name="index.html">
  1008. <div ng-controller="ExampleController">
  1009. <form novalidate>
  1010. <h3>User 1</h3>
  1011. Name: <input type="text" ng-model="user1.name">
  1012. Age: <input type="number" ng-model="user1.age">
  1013. <h3>User 2</h3>
  1014. Name: <input type="text" ng-model="user2.name">
  1015. Age: <input type="number" ng-model="user2.age">
  1016. <div>
  1017. <br/>
  1018. <input type="button" value="Compare" ng-click="compare()">
  1019. </div>
  1020. User 1: <pre>{{user1 | json}}</pre>
  1021. User 2: <pre>{{user2 | json}}</pre>
  1022. Equal: <pre>{{result}}</pre>
  1023. </form>
  1024. </div>
  1025. </file>
  1026. <file name="script.js">
  1027. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  1028. $scope.user1 = {};
  1029. $scope.user2 = {};
  1030. $scope.compare = function() {
  1031. $scope.result = angular.equals($scope.user1, $scope.user2);
  1032. };
  1033. }]);
  1034. </file>
  1035. </example>
  1036. */
  1037. function equals(o1, o2) {
  1038. if (o1 === o2) return true;
  1039. if (o1 === null || o2 === null) return false;
  1040. // eslint-disable-next-line no-self-compare
  1041. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  1042. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  1043. if (t1 === t2 && t1 === 'object') {
  1044. if (isArray(o1)) {
  1045. if (!isArray(o2)) return false;
  1046. if ((length = o1.length) === o2.length) {
  1047. for (key = 0; key < length; key++) {
  1048. if (!equals(o1[key], o2[key])) return false;
  1049. }
  1050. return true;
  1051. }
  1052. } else if (isDate(o1)) {
  1053. if (!isDate(o2)) return false;
  1054. return simpleCompare(o1.getTime(), o2.getTime());
  1055. } else if (isRegExp(o1)) {
  1056. if (!isRegExp(o2)) return false;
  1057. return o1.toString() === o2.toString();
  1058. } else {
  1059. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  1060. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  1061. keySet = createMap();
  1062. for (key in o1) {
  1063. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  1064. if (!equals(o1[key], o2[key])) return false;
  1065. keySet[key] = true;
  1066. }
  1067. for (key in o2) {
  1068. if (!(key in keySet) &&
  1069. key.charAt(0) !== '$' &&
  1070. isDefined(o2[key]) &&
  1071. !isFunction(o2[key])) return false;
  1072. }
  1073. return true;
  1074. }
  1075. }
  1076. return false;
  1077. }
  1078. var csp = function() {
  1079. if (!isDefined(csp.rules)) {
  1080. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  1081. window.document.querySelector('[data-ng-csp]'));
  1082. if (ngCspElement) {
  1083. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  1084. ngCspElement.getAttribute('data-ng-csp');
  1085. csp.rules = {
  1086. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  1087. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  1088. };
  1089. } else {
  1090. csp.rules = {
  1091. noUnsafeEval: noUnsafeEval(),
  1092. noInlineStyle: false
  1093. };
  1094. }
  1095. }
  1096. return csp.rules;
  1097. function noUnsafeEval() {
  1098. try {
  1099. // eslint-disable-next-line no-new, no-new-func
  1100. new Function('');
  1101. return false;
  1102. } catch (e) {
  1103. return true;
  1104. }
  1105. }
  1106. };
  1107. /**
  1108. * @ngdoc directive
  1109. * @module ng
  1110. * @name ngJq
  1111. *
  1112. * @element ANY
  1113. * @param {string=} ngJq the name of the library available under `window`
  1114. * to be used for angular.element
  1115. * @description
  1116. * Use this directive to force the angular.element library. This should be
  1117. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1118. * the jquery variable under window (eg. jQuery).
  1119. *
  1120. * Since angular looks for this directive when it is loaded (doesn't wait for the
  1121. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1122. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1123. * others ignored.
  1124. *
  1125. * @example
  1126. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1127. ```html
  1128. <!doctype html>
  1129. <html ng-app ng-jq>
  1130. ...
  1131. ...
  1132. </html>
  1133. ```
  1134. * @example
  1135. * This example shows how to use a jQuery based library of a different name.
  1136. * The library name must be available at the top most 'window'.
  1137. ```html
  1138. <!doctype html>
  1139. <html ng-app ng-jq="jQueryLib">
  1140. ...
  1141. ...
  1142. </html>
  1143. ```
  1144. */
  1145. var jq = function() {
  1146. if (isDefined(jq.name_)) return jq.name_;
  1147. var el;
  1148. var i, ii = ngAttrPrefixes.length, prefix, name;
  1149. for (i = 0; i < ii; ++i) {
  1150. prefix = ngAttrPrefixes[i];
  1151. el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
  1152. if (el) {
  1153. name = el.getAttribute(prefix + 'jq');
  1154. break;
  1155. }
  1156. }
  1157. return (jq.name_ = name);
  1158. };
  1159. function concat(array1, array2, index) {
  1160. return array1.concat(slice.call(array2, index));
  1161. }
  1162. function sliceArgs(args, startIndex) {
  1163. return slice.call(args, startIndex || 0);
  1164. }
  1165. /**
  1166. * @ngdoc function
  1167. * @name angular.bind
  1168. * @module ng
  1169. * @kind function
  1170. *
  1171. * @description
  1172. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1173. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1174. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1175. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1176. *
  1177. * @param {Object} self Context which `fn` should be evaluated in.
  1178. * @param {function()} fn Function to be bound.
  1179. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1180. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1181. */
  1182. function bind(self, fn) {
  1183. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1184. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1185. return curryArgs.length
  1186. ? function() {
  1187. return arguments.length
  1188. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1189. : fn.apply(self, curryArgs);
  1190. }
  1191. : function() {
  1192. return arguments.length
  1193. ? fn.apply(self, arguments)
  1194. : fn.call(self);
  1195. };
  1196. } else {
  1197. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1198. return fn;
  1199. }
  1200. }
  1201. function toJsonReplacer(key, value) {
  1202. var val = value;
  1203. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1204. val = undefined;
  1205. } else if (isWindow(value)) {
  1206. val = '$WINDOW';
  1207. } else if (value && window.document === value) {
  1208. val = '$DOCUMENT';
  1209. } else if (isScope(value)) {
  1210. val = '$SCOPE';
  1211. }
  1212. return val;
  1213. }
  1214. /**
  1215. * @ngdoc function
  1216. * @name angular.toJson
  1217. * @module ng
  1218. * @kind function
  1219. *
  1220. * @description
  1221. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1222. * stripped since angular uses this notation internally.
  1223. *
  1224. * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
  1225. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1226. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1227. * @returns {string|undefined} JSON-ified string representing `obj`.
  1228. * @knownIssue
  1229. *
  1230. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1231. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1232. * `Date.prototype.toJSON` method as follows:
  1233. *
  1234. * ```
  1235. * var _DatetoJSON = Date.prototype.toJSON;
  1236. * Date.prototype.toJSON = function() {
  1237. * try {
  1238. * return _DatetoJSON.call(this);
  1239. * } catch(e) {
  1240. * if (e instanceof RangeError) {
  1241. * return null;
  1242. * }
  1243. * throw e;
  1244. * }
  1245. * };
  1246. * ```
  1247. *
  1248. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1249. */
  1250. function toJson(obj, pretty) {
  1251. if (isUndefined(obj)) return undefined;
  1252. if (!isNumber(pretty)) {
  1253. pretty = pretty ? 2 : null;
  1254. }
  1255. return JSON.stringify(obj, toJsonReplacer, pretty);
  1256. }
  1257. /**
  1258. * @ngdoc function
  1259. * @name angular.fromJson
  1260. * @module ng
  1261. * @kind function
  1262. *
  1263. * @description
  1264. * Deserializes a JSON string.
  1265. *
  1266. * @param {string} json JSON string to deserialize.
  1267. * @returns {Object|Array|string|number} Deserialized JSON string.
  1268. */
  1269. function fromJson(json) {
  1270. return isString(json)
  1271. ? JSON.parse(json)
  1272. : json;
  1273. }
  1274. var ALL_COLONS = /:/g;
  1275. function timezoneToOffset(timezone, fallback) {
  1276. // Support: IE 9-11 only, Edge 13-14+
  1277. // IE/Edge do not "understand" colon (`:`) in timezone
  1278. timezone = timezone.replace(ALL_COLONS, '');
  1279. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1280. return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1281. }
  1282. function addDateMinutes(date, minutes) {
  1283. date = new Date(date.getTime());
  1284. date.setMinutes(date.getMinutes() + minutes);
  1285. return date;
  1286. }
  1287. function convertTimezoneToLocal(date, timezone, reverse) {
  1288. reverse = reverse ? -1 : 1;
  1289. var dateTimezoneOffset = date.getTimezoneOffset();
  1290. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1291. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1292. }
  1293. /**
  1294. * @returns {string} Returns the string representation of the element.
  1295. */
  1296. function startingTag(element) {
  1297. element = jqLite(element).clone();
  1298. try {
  1299. // turns out IE does not let you set .html() on elements which
  1300. // are not allowed to have children. So we just ignore it.
  1301. element.empty();
  1302. } catch (e) { /* empty */ }
  1303. var elemHtml = jqLite('<div>').append(element).html();
  1304. try {
  1305. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1306. elemHtml.
  1307. match(/^(<[^>]+>)/)[1].
  1308. replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1309. } catch (e) {
  1310. return lowercase(elemHtml);
  1311. }
  1312. }
  1313. /////////////////////////////////////////////////
  1314. /**
  1315. * Tries to decode the URI component without throwing an exception.
  1316. *
  1317. * @private
  1318. * @param str value potential URI component to check.
  1319. * @returns {boolean} True if `value` can be decoded
  1320. * with the decodeURIComponent function.
  1321. */
  1322. function tryDecodeURIComponent(value) {
  1323. try {
  1324. return decodeURIComponent(value);
  1325. } catch (e) {
  1326. // Ignore any invalid uri component.
  1327. }
  1328. }
  1329. /**
  1330. * Parses an escaped url query string into key-value pairs.
  1331. * @returns {Object.<string,boolean|Array>}
  1332. */
  1333. function parseKeyValue(/**string*/keyValue) {
  1334. var obj = {};
  1335. forEach((keyValue || '').split('&'), function(keyValue) {
  1336. var splitPoint, key, val;
  1337. if (keyValue) {
  1338. key = keyValue = keyValue.replace(/\+/g,'%20');
  1339. splitPoint = keyValue.indexOf('=');
  1340. if (splitPoint !== -1) {
  1341. key = keyValue.substring(0, splitPoint);
  1342. val = keyValue.substring(splitPoint + 1);
  1343. }
  1344. key = tryDecodeURIComponent(key);
  1345. if (isDefined(key)) {
  1346. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1347. if (!hasOwnProperty.call(obj, key)) {
  1348. obj[key] = val;
  1349. } else if (isArray(obj[key])) {
  1350. obj[key].push(val);
  1351. } else {
  1352. obj[key] = [obj[key],val];
  1353. }
  1354. }
  1355. }
  1356. });
  1357. return obj;
  1358. }
  1359. function toKeyValue(obj) {
  1360. var parts = [];
  1361. forEach(obj, function(value, key) {
  1362. if (isArray(value)) {
  1363. forEach(value, function(arrayValue) {
  1364. parts.push(encodeUriQuery(key, true) +
  1365. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1366. });
  1367. } else {
  1368. parts.push(encodeUriQuery(key, true) +
  1369. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1370. }
  1371. });
  1372. return parts.length ? parts.join('&') : '';
  1373. }
  1374. /**
  1375. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1376. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1377. * segments:
  1378. * segment = *pchar
  1379. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1380. * pct-encoded = "%" HEXDIG HEXDIG
  1381. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1382. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1383. * / "*" / "+" / "," / ";" / "="
  1384. */
  1385. function encodeUriSegment(val) {
  1386. return encodeUriQuery(val, true).
  1387. replace(/%26/gi, '&').
  1388. replace(/%3D/gi, '=').
  1389. replace(/%2B/gi, '+');
  1390. }
  1391. /**
  1392. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1393. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1394. * encoded per http://tools.ietf.org/html/rfc3986:
  1395. * query = *( pchar / "/" / "?" )
  1396. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1397. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1398. * pct-encoded = "%" HEXDIG HEXDIG
  1399. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1400. * / "*" / "+" / "," / ";" / "="
  1401. */
  1402. function encodeUriQuery(val, pctEncodeSpaces) {
  1403. return encodeURIComponent(val).
  1404. replace(/%40/gi, '@').
  1405. replace(/%3A/gi, ':').
  1406. replace(/%24/g, '$').
  1407. replace(/%2C/gi, ',').
  1408. replace(/%3B/gi, ';').
  1409. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1410. }
  1411. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1412. function getNgAttribute(element, ngAttr) {
  1413. var attr, i, ii = ngAttrPrefixes.length;
  1414. for (i = 0; i < ii; ++i) {
  1415. attr = ngAttrPrefixes[i] + ngAttr;
  1416. if (isString(attr = element.getAttribute(attr))) {
  1417. return attr;
  1418. }
  1419. }
  1420. return null;
  1421. }
  1422. function allowAutoBootstrap(document) {
  1423. var script = document.currentScript;
  1424. if (!script) {
  1425. // IE does not have `document.currentScript`
  1426. return true;
  1427. }
  1428. // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack
  1429. if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) {
  1430. return false;
  1431. }
  1432. var attributes = script.attributes;
  1433. var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')];
  1434. return srcs.every(function(src) {
  1435. if (!src) {
  1436. return true;
  1437. }
  1438. if (!src.value) {
  1439. return false;
  1440. }
  1441. var link = document.createElement('a');
  1442. link.href = src.value;
  1443. if (document.location.origin === link.origin) {
  1444. // Same-origin resources are always allowed, even for non-whitelisted schemes.
  1445. return true;
  1446. }
  1447. // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
  1448. // This is to prevent angular.js bundled with browser extensions from being used to bypass the
  1449. // content security policy in web pages and other browser extensions.
  1450. switch (link.protocol) {
  1451. case 'http:':
  1452. case 'https:':
  1453. case 'ftp:':
  1454. case 'blob:':
  1455. case 'file:':
  1456. case 'data:':
  1457. return true;
  1458. default:
  1459. return false;
  1460. }
  1461. });
  1462. }
  1463. // Cached as it has to run during loading so that document.currentScript is available.
  1464. var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
  1465. /**
  1466. * @ngdoc directive
  1467. * @name ngApp
  1468. * @module ng
  1469. *
  1470. * @element ANY
  1471. * @param {angular.Module} ngApp an optional application
  1472. * {@link angular.module module} name to load.
  1473. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1474. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1475. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1476. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1477. * tracking down the root of these bugs.
  1478. *
  1479. * @description
  1480. *
  1481. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1482. * designates the **root element** of the application and is typically placed near the root element
  1483. * of the page - e.g. on the `<body>` or `<html>` tags.
  1484. *
  1485. * There are a few things to keep in mind when using `ngApp`:
  1486. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1487. * found in the document will be used to define the root element to auto-bootstrap as an
  1488. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1489. * {@link angular.bootstrap} instead.
  1490. * - AngularJS applications cannot be nested within each other.
  1491. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1492. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1493. * {@link ngRoute.ngView `ngView`}.
  1494. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1495. * causing animations to stop working and making the injector inaccessible from outside the app.
  1496. *
  1497. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1498. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1499. * should contain the application code needed or have dependencies on other modules that will
  1500. * contain the code. See {@link angular.module} for more information.
  1501. *
  1502. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1503. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1504. * would not be resolved to `3`.
  1505. *
  1506. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1507. *
  1508. <example module="ngAppDemo" name="ng-app">
  1509. <file name="index.html">
  1510. <div ng-controller="ngAppDemoController">
  1511. I can add: {{a}} + {{b}} = {{ a+b }}
  1512. </div>
  1513. </file>
  1514. <file name="script.js">
  1515. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1516. $scope.a = 1;
  1517. $scope.b = 2;
  1518. });
  1519. </file>
  1520. </example>
  1521. *
  1522. * Using `ngStrictDi`, you would see something like this:
  1523. *
  1524. <example ng-app-included="true" name="strict-di">
  1525. <file name="index.html">
  1526. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1527. <div ng-controller="GoodController1">
  1528. I can add: {{a}} + {{b}} = {{ a+b }}
  1529. <p>This renders because the controller does not fail to
  1530. instantiate, by using explicit annotation style (see
  1531. script.js for details)
  1532. </p>
  1533. </div>
  1534. <div ng-controller="GoodController2">
  1535. Name: <input ng-model="name"><br />
  1536. Hello, {{name}}!
  1537. <p>This renders because the controller does not fail to
  1538. instantiate, by using explicit annotation style
  1539. (see script.js for details)
  1540. </p>
  1541. </div>
  1542. <div ng-controller="BadController">
  1543. I can add: {{a}} + {{b}} = {{ a+b }}
  1544. <p>The controller could not be instantiated, due to relying
  1545. on automatic function annotations (which are disabled in
  1546. strict mode). As such, the content of this section is not
  1547. interpolated, and there should be an error in your web console.
  1548. </p>
  1549. </div>
  1550. </div>
  1551. </file>
  1552. <file name="script.js">
  1553. angular.module('ngAppStrictDemo', [])
  1554. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1555. // rather than an explicit annotation
  1556. .controller('BadController', function($scope) {
  1557. $scope.a = 1;
  1558. $scope.b = 2;
  1559. })
  1560. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1561. // due to using explicit annotations using the array style and $inject property, respectively.
  1562. .controller('GoodController1', ['$scope', function($scope) {
  1563. $scope.a = 1;
  1564. $scope.b = 2;
  1565. }])
  1566. .controller('GoodController2', GoodController2);
  1567. function GoodController2($scope) {
  1568. $scope.name = 'World';
  1569. }
  1570. GoodController2.$inject = ['$scope'];
  1571. </file>
  1572. <file name="style.css">
  1573. div[ng-controller] {
  1574. margin-bottom: 1em;
  1575. -webkit-border-radius: 4px;
  1576. border-radius: 4px;
  1577. border: 1px solid;
  1578. padding: .5em;
  1579. }
  1580. div[ng-controller^=Good] {
  1581. border-color: #d6e9c6;
  1582. background-color: #dff0d8;
  1583. color: #3c763d;
  1584. }
  1585. div[ng-controller^=Bad] {
  1586. border-color: #ebccd1;
  1587. background-color: #f2dede;
  1588. color: #a94442;
  1589. margin-bottom: 0;
  1590. }
  1591. </file>
  1592. </example>
  1593. */
  1594. function angularInit(element, bootstrap) {
  1595. var appElement,
  1596. module,
  1597. config = {};
  1598. // The element `element` has priority over any other element.
  1599. forEach(ngAttrPrefixes, function(prefix) {
  1600. var name = prefix + 'app';
  1601. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1602. appElement = element;
  1603. module = element.getAttribute(name);
  1604. }
  1605. });
  1606. forEach(ngAttrPrefixes, function(prefix) {
  1607. var name = prefix + 'app';
  1608. var candidate;
  1609. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1610. appElement = candidate;
  1611. module = candidate.getAttribute(name);
  1612. }
  1613. });
  1614. if (appElement) {
  1615. if (!isAutoBootstrapAllowed) {
  1616. window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' +
  1617. 'an extension, document.location.href does not match.');
  1618. return;
  1619. }
  1620. config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
  1621. bootstrap(appElement, module ? [module] : [], config);
  1622. }
  1623. }
  1624. /**
  1625. * @ngdoc function
  1626. * @name angular.bootstrap
  1627. * @module ng
  1628. * @description
  1629. * Use this function to manually start up angular application.
  1630. *
  1631. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1632. *
  1633. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1634. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1635. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1636. * multiple instances of Angular try to work on the DOM.
  1637. *
  1638. * <div class="alert alert-warning">
  1639. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1640. * They must use {@link ng.directive:ngApp ngApp}.
  1641. * </div>
  1642. *
  1643. * <div class="alert alert-warning">
  1644. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1645. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1646. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1647. * causing animations to stop working and making the injector inaccessible from outside the app.
  1648. * </div>
  1649. *
  1650. * ```html
  1651. * <!doctype html>
  1652. * <html>
  1653. * <body>
  1654. * <div ng-controller="WelcomeController">
  1655. * {{greeting}}
  1656. * </div>
  1657. *
  1658. * <script src="angular.js"></script>
  1659. * <script>
  1660. * var app = angular.module('demo', [])
  1661. * .controller('WelcomeController', function($scope) {
  1662. * $scope.greeting = 'Welcome!';
  1663. * });
  1664. * angular.bootstrap(document, ['demo']);
  1665. * </script>
  1666. * </body>
  1667. * </html>
  1668. * ```
  1669. *
  1670. * @param {DOMElement} element DOM element which is the root of angular application.
  1671. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1672. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1673. * function that will be invoked by the injector as a `config` block.
  1674. * See: {@link angular.module modules}
  1675. * @param {Object=} config an object for defining configuration options for the application. The
  1676. * following keys are supported:
  1677. *
  1678. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1679. * assist in finding bugs which break minified code. Defaults to `false`.
  1680. *
  1681. * @returns {auto.$injector} Returns the newly created injector for this app.
  1682. */
  1683. function bootstrap(element, modules, config) {
  1684. if (!isObject(config)) config = {};
  1685. var defaultConfig = {
  1686. strictDi: false
  1687. };
  1688. config = extend(defaultConfig, config);
  1689. var doBootstrap = function() {
  1690. element = jqLite(element);
  1691. if (element.injector()) {
  1692. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1693. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1694. throw ngMinErr(
  1695. 'btstrpd',
  1696. 'App already bootstrapped with this element \'{0}\'',
  1697. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1698. }
  1699. modules = modules || [];
  1700. modules.unshift(['$provide', function($provide) {
  1701. $provide.value('$rootElement', element);
  1702. }]);
  1703. if (config.debugInfoEnabled) {
  1704. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1705. modules.push(['$compileProvider', function($compileProvider) {
  1706. $compileProvider.debugInfoEnabled(true);
  1707. }]);
  1708. }
  1709. modules.unshift('ng');
  1710. var injector = createInjector(modules, config.strictDi);
  1711. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1712. function bootstrapApply(scope, element, compile, injector) {
  1713. scope.$apply(function() {
  1714. element.data('$injector', injector);
  1715. compile(element)(scope);
  1716. });
  1717. }]
  1718. );
  1719. return injector;
  1720. };
  1721. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1722. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1723. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1724. config.debugInfoEnabled = true;
  1725. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1726. }
  1727. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1728. return doBootstrap();
  1729. }
  1730. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1731. angular.resumeBootstrap = function(extraModules) {
  1732. forEach(extraModules, function(module) {
  1733. modules.push(module);
  1734. });
  1735. return doBootstrap();
  1736. };
  1737. if (isFunction(angular.resumeDeferredBootstrap)) {
  1738. angular.resumeDeferredBootstrap();
  1739. }
  1740. }
  1741. /**
  1742. * @ngdoc function
  1743. * @name angular.reloadWithDebugInfo
  1744. * @module ng
  1745. * @description
  1746. * Use this function to reload the current application with debug information turned on.
  1747. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1748. *
  1749. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1750. */
  1751. function reloadWithDebugInfo() {
  1752. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1753. window.location.reload();
  1754. }
  1755. /**
  1756. * @name angular.getTestability
  1757. * @module ng
  1758. * @description
  1759. * Get the testability service for the instance of Angular on the given
  1760. * element.
  1761. * @param {DOMElement} element DOM element which is the root of angular application.
  1762. */
  1763. function getTestability(rootElement) {
  1764. var injector = angular.element(rootElement).injector();
  1765. if (!injector) {
  1766. throw ngMinErr('test',
  1767. 'no injector found for element argument to getTestability');
  1768. }
  1769. return injector.get('$$testability');
  1770. }
  1771. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1772. function snake_case(name, separator) {
  1773. separator = separator || '_';
  1774. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1775. return (pos ? separator : '') + letter.toLowerCase();
  1776. });
  1777. }
  1778. var bindJQueryFired = false;
  1779. function bindJQuery() {
  1780. var originalCleanData;
  1781. if (bindJQueryFired) {
  1782. return;
  1783. }
  1784. // bind to jQuery if present;
  1785. var jqName = jq();
  1786. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1787. !jqName ? undefined : // use jqLite
  1788. window[jqName]; // use jQuery specified by `ngJq`
  1789. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1790. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1791. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1792. // versions. It will not work for sure with jQuery <1.7, though.
  1793. if (jQuery && jQuery.fn.on) {
  1794. jqLite = jQuery;
  1795. extend(jQuery.fn, {
  1796. scope: JQLitePrototype.scope,
  1797. isolateScope: JQLitePrototype.isolateScope,
  1798. controller: /** @type {?} */ (JQLitePrototype).controller,
  1799. injector: JQLitePrototype.injector,
  1800. inheritedData: JQLitePrototype.inheritedData
  1801. });
  1802. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1803. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1804. // the $destroy event on all removed nodes.
  1805. originalCleanData = jQuery.cleanData;
  1806. jQuery.cleanData = function(elems) {
  1807. var events;
  1808. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1809. events = jQuery._data(elem, 'events');
  1810. if (events && events.$destroy) {
  1811. jQuery(elem).triggerHandler('$destroy');
  1812. }
  1813. }
  1814. originalCleanData(elems);
  1815. };
  1816. } else {
  1817. jqLite = JQLite;
  1818. }
  1819. angular.element = jqLite;
  1820. // Prevent double-proxying.
  1821. bindJQueryFired = true;
  1822. }
  1823. /**
  1824. * throw error if the argument is falsy.
  1825. */
  1826. function assertArg(arg, name, reason) {
  1827. if (!arg) {
  1828. throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  1829. }
  1830. return arg;
  1831. }
  1832. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1833. if (acceptArrayAnnotation && isArray(arg)) {
  1834. arg = arg[arg.length - 1];
  1835. }
  1836. assertArg(isFunction(arg), name, 'not a function, got ' +
  1837. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1838. return arg;
  1839. }
  1840. /**
  1841. * throw error if the name given is hasOwnProperty
  1842. * @param {String} name the name to test
  1843. * @param {String} context the context in which the name is used, such as module or directive
  1844. */
  1845. function assertNotHasOwnProperty(name, context) {
  1846. if (name === 'hasOwnProperty') {
  1847. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1848. }
  1849. }
  1850. /**
  1851. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1852. * @param {Object} obj starting object
  1853. * @param {String} path path to traverse
  1854. * @param {boolean} [bindFnToScope=true]
  1855. * @returns {Object} value as accessible by path
  1856. */
  1857. //TODO(misko): this function needs to be removed
  1858. function getter(obj, path, bindFnToScope) {
  1859. if (!path) return obj;
  1860. var keys = path.split('.');
  1861. var key;
  1862. var lastInstance = obj;
  1863. var len = keys.length;
  1864. for (var i = 0; i < len; i++) {
  1865. key = keys[i];
  1866. if (obj) {
  1867. obj = (lastInstance = obj)[key];
  1868. }
  1869. }
  1870. if (!bindFnToScope && isFunction(obj)) {
  1871. return bind(lastInstance, obj);
  1872. }
  1873. return obj;
  1874. }
  1875. /**
  1876. * Return the DOM siblings between the first and last node in the given array.
  1877. * @param {Array} array like object
  1878. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1879. */
  1880. function getBlockNodes(nodes) {
  1881. // TODO(perf): update `nodes` instead of creating a new object?
  1882. var node = nodes[0];
  1883. var endNode = nodes[nodes.length - 1];
  1884. var blockNodes;
  1885. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1886. if (blockNodes || nodes[i] !== node) {
  1887. if (!blockNodes) {
  1888. blockNodes = jqLite(slice.call(nodes, 0, i));
  1889. }
  1890. blockNodes.push(node);
  1891. }
  1892. }
  1893. return blockNodes || nodes;
  1894. }
  1895. /**
  1896. * Creates a new object without a prototype. This object is useful for lookup without having to
  1897. * guard against prototypically inherited properties via hasOwnProperty.
  1898. *
  1899. * Related micro-benchmarks:
  1900. * - http://jsperf.com/object-create2
  1901. * - http://jsperf.com/proto-map-lookup/2
  1902. * - http://jsperf.com/for-in-vs-object-keys2
  1903. *
  1904. * @returns {Object}
  1905. */
  1906. function createMap() {
  1907. return Object.create(null);
  1908. }
  1909. function stringify(value) {
  1910. if (value == null) { // null || undefined
  1911. return '';
  1912. }
  1913. switch (typeof value) {
  1914. case 'string':
  1915. break;
  1916. case 'number':
  1917. value = '' + value;
  1918. break;
  1919. default:
  1920. if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
  1921. value = value.toString();
  1922. } else {
  1923. value = toJson(value);
  1924. }
  1925. }
  1926. return value;
  1927. }
  1928. var NODE_TYPE_ELEMENT = 1;
  1929. var NODE_TYPE_ATTRIBUTE = 2;
  1930. var NODE_TYPE_TEXT = 3;
  1931. var NODE_TYPE_COMMENT = 8;
  1932. var NODE_TYPE_DOCUMENT = 9;
  1933. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1934. /**
  1935. * @ngdoc type
  1936. * @name angular.Module
  1937. * @module ng
  1938. * @description
  1939. *
  1940. * Interface for configuring angular {@link angular.module modules}.
  1941. */
  1942. function setupModuleLoader(window) {
  1943. var $injectorMinErr = minErr('$injector');
  1944. var ngMinErr = minErr('ng');
  1945. function ensure(obj, name, factory) {
  1946. return obj[name] || (obj[name] = factory());
  1947. }
  1948. var angular = ensure(window, 'angular', Object);
  1949. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1950. angular.$$minErr = angular.$$minErr || minErr;
  1951. return ensure(angular, 'module', function() {
  1952. /** @type {Object.<string, angular.Module>} */
  1953. var modules = {};
  1954. /**
  1955. * @ngdoc function
  1956. * @name angular.module
  1957. * @module ng
  1958. * @description
  1959. *
  1960. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1961. * modules.
  1962. * All modules (angular core or 3rd party) that should be available to an application must be
  1963. * registered using this mechanism.
  1964. *
  1965. * Passing one argument retrieves an existing {@link angular.Module},
  1966. * whereas passing more than one argument creates a new {@link angular.Module}
  1967. *
  1968. *
  1969. * # Module
  1970. *
  1971. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1972. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1973. *
  1974. * ```js
  1975. * // Create a new module
  1976. * var myModule = angular.module('myModule', []);
  1977. *
  1978. * // register a new service
  1979. * myModule.value('appName', 'MyCoolApp');
  1980. *
  1981. * // configure existing services inside initialization blocks.
  1982. * myModule.config(['$locationProvider', function($locationProvider) {
  1983. * // Configure existing providers
  1984. * $locationProvider.hashPrefix('!');
  1985. * }]);
  1986. * ```
  1987. *
  1988. * Then you can create an injector and load your modules like this:
  1989. *
  1990. * ```js
  1991. * var injector = angular.injector(['ng', 'myModule'])
  1992. * ```
  1993. *
  1994. * However it's more likely that you'll just use
  1995. * {@link ng.directive:ngApp ngApp} or
  1996. * {@link angular.bootstrap} to simplify this process for you.
  1997. *
  1998. * @param {!string} name The name of the module to create or retrieve.
  1999. * @param {!Array.<string>=} requires If specified then new module is being created. If
  2000. * unspecified then the module is being retrieved for further configuration.
  2001. * @param {Function=} configFn Optional configuration function for the module. Same as
  2002. * {@link angular.Module#config Module#config()}.
  2003. * @returns {angular.Module} new module with the {@link angular.Module} api.
  2004. */
  2005. return function module(name, requires, configFn) {
  2006. var info = {};
  2007. var assertNotHasOwnProperty = function(name, context) {
  2008. if (name === 'hasOwnProperty') {
  2009. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  2010. }
  2011. };
  2012. assertNotHasOwnProperty(name, 'module');
  2013. if (requires && modules.hasOwnProperty(name)) {
  2014. modules[name] = null;
  2015. }
  2016. return ensure(modules, name, function() {
  2017. if (!requires) {
  2018. throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
  2019. 'the module name or forgot to load it. If registering a module ensure that you ' +
  2020. 'specify the dependencies as the second argument.', name);
  2021. }
  2022. /** @type {!Array.<Array.<*>>} */
  2023. var invokeQueue = [];
  2024. /** @type {!Array.<Function>} */
  2025. var configBlocks = [];
  2026. /** @type {!Array.<Function>} */
  2027. var runBlocks = [];
  2028. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  2029. /** @type {angular.Module} */
  2030. var moduleInstance = {
  2031. // Private state
  2032. _invokeQueue: invokeQueue,
  2033. _configBlocks: configBlocks,
  2034. _runBlocks: runBlocks,
  2035. /**
  2036. * @ngdoc method
  2037. * @name angular.Module#info
  2038. * @module ng
  2039. *
  2040. * @param {Object=} info Information about the module
  2041. * @returns {Object|Module} The current info object for this module if called as a getter,
  2042. * or `this` if called as a setter.
  2043. *
  2044. * @description
  2045. * Read and write custom information about this module.
  2046. * For example you could put the version of the module in here.
  2047. *
  2048. * ```js
  2049. * angular.module('myModule', []).info({ version: '1.0.0' });
  2050. * ```
  2051. *
  2052. * The version could then be read back out by accessing the module elsewhere:
  2053. *
  2054. * ```
  2055. * var version = angular.module('myModule').info().version;
  2056. * ```
  2057. *
  2058. * You can also retrieve this information during runtime via the
  2059. * {@link $injector#modules `$injector.modules`} property:
  2060. *
  2061. * ```js
  2062. * var version = $injector.modules['myModule'].info().version;
  2063. * ```
  2064. */
  2065. info: function(value) {
  2066. if (isDefined(value)) {
  2067. if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value');
  2068. info = value;
  2069. return this;
  2070. }
  2071. return info;
  2072. },
  2073. /**
  2074. * @ngdoc property
  2075. * @name angular.Module#requires
  2076. * @module ng
  2077. *
  2078. * @description
  2079. * Holds the list of modules which the injector will load before the current module is
  2080. * loaded.
  2081. */
  2082. requires: requires,
  2083. /**
  2084. * @ngdoc property
  2085. * @name angular.Module#name
  2086. * @module ng
  2087. *
  2088. * @description
  2089. * Name of the module.
  2090. */
  2091. name: name,
  2092. /**
  2093. * @ngdoc method
  2094. * @name angular.Module#provider
  2095. * @module ng
  2096. * @param {string} name service name
  2097. * @param {Function} providerType Construction function for creating new instance of the
  2098. * service.
  2099. * @description
  2100. * See {@link auto.$provide#provider $provide.provider()}.
  2101. */
  2102. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  2103. /**
  2104. * @ngdoc method
  2105. * @name angular.Module#factory
  2106. * @module ng
  2107. * @param {string} name service name
  2108. * @param {Function} providerFunction Function for creating new instance of the service.
  2109. * @description
  2110. * See {@link auto.$provide#factory $provide.factory()}.
  2111. */
  2112. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  2113. /**
  2114. * @ngdoc method
  2115. * @name angular.Module#service
  2116. * @module ng
  2117. * @param {string} name service name
  2118. * @param {Function} constructor A constructor function that will be instantiated.
  2119. * @description
  2120. * See {@link auto.$provide#service $provide.service()}.
  2121. */
  2122. service: invokeLaterAndSetModuleName('$provide', 'service'),
  2123. /**
  2124. * @ngdoc method
  2125. * @name angular.Module#value
  2126. * @module ng
  2127. * @param {string} name service name
  2128. * @param {*} object Service instance object.
  2129. * @description
  2130. * See {@link auto.$provide#value $provide.value()}.
  2131. */
  2132. value: invokeLater('$provide', 'value'),
  2133. /**
  2134. * @ngdoc method
  2135. * @name angular.Module#constant
  2136. * @module ng
  2137. * @param {string} name constant name
  2138. * @param {*} object Constant value.
  2139. * @description
  2140. * Because the constants are fixed, they get applied before other provide methods.
  2141. * See {@link auto.$provide#constant $provide.constant()}.
  2142. */
  2143. constant: invokeLater('$provide', 'constant', 'unshift'),
  2144. /**
  2145. * @ngdoc method
  2146. * @name angular.Module#decorator
  2147. * @module ng
  2148. * @param {string} name The name of the service to decorate.
  2149. * @param {Function} decorFn This function will be invoked when the service needs to be
  2150. * instantiated and should return the decorated service instance.
  2151. * @description
  2152. * See {@link auto.$provide#decorator $provide.decorator()}.
  2153. */
  2154. decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
  2155. /**
  2156. * @ngdoc method
  2157. * @name angular.Module#animation
  2158. * @module ng
  2159. * @param {string} name animation name
  2160. * @param {Function} animationFactory Factory function for creating new instance of an
  2161. * animation.
  2162. * @description
  2163. *
  2164. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  2165. *
  2166. *
  2167. * Defines an animation hook that can be later used with
  2168. * {@link $animate $animate} service and directives that use this service.
  2169. *
  2170. * ```js
  2171. * module.animation('.animation-name', function($inject1, $inject2) {
  2172. * return {
  2173. * eventName : function(element, done) {
  2174. * //code to run the animation
  2175. * //once complete, then run done()
  2176. * return function cancellationFunction(element) {
  2177. * //code to cancel the animation
  2178. * }
  2179. * }
  2180. * }
  2181. * })
  2182. * ```
  2183. *
  2184. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  2185. * {@link ngAnimate ngAnimate module} for more information.
  2186. */
  2187. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  2188. /**
  2189. * @ngdoc method
  2190. * @name angular.Module#filter
  2191. * @module ng
  2192. * @param {string} name Filter name - this must be a valid angular expression identifier
  2193. * @param {Function} filterFactory Factory function for creating new instance of filter.
  2194. * @description
  2195. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  2196. *
  2197. * <div class="alert alert-warning">
  2198. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2199. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2200. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2201. * (`myapp_subsection_filterx`).
  2202. * </div>
  2203. */
  2204. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2205. /**
  2206. * @ngdoc method
  2207. * @name angular.Module#controller
  2208. * @module ng
  2209. * @param {string|Object} name Controller name, or an object map of controllers where the
  2210. * keys are the names and the values are the constructors.
  2211. * @param {Function} constructor Controller constructor function.
  2212. * @description
  2213. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2214. */
  2215. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2216. /**
  2217. * @ngdoc method
  2218. * @name angular.Module#directive
  2219. * @module ng
  2220. * @param {string|Object} name Directive name, or an object map of directives where the
  2221. * keys are the names and the values are the factories.
  2222. * @param {Function} directiveFactory Factory function for creating new instance of
  2223. * directives.
  2224. * @description
  2225. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2226. */
  2227. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2228. /**
  2229. * @ngdoc method
  2230. * @name angular.Module#component
  2231. * @module ng
  2232. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  2233. * @param {Object} options Component definition object (a simplified
  2234. * {@link ng.$compile#directive-definition-object directive definition object})
  2235. *
  2236. * @description
  2237. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2238. */
  2239. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2240. /**
  2241. * @ngdoc method
  2242. * @name angular.Module#config
  2243. * @module ng
  2244. * @param {Function} configFn Execute this function on module load. Useful for service
  2245. * configuration.
  2246. * @description
  2247. * Use this method to register work which needs to be performed on module loading.
  2248. * For more about how to configure services, see
  2249. * {@link providers#provider-recipe Provider Recipe}.
  2250. */
  2251. config: config,
  2252. /**
  2253. * @ngdoc method
  2254. * @name angular.Module#run
  2255. * @module ng
  2256. * @param {Function} initializationFn Execute this function after injector creation.
  2257. * Useful for application initialization.
  2258. * @description
  2259. * Use this method to register work which should be performed when the injector is done
  2260. * loading all modules.
  2261. */
  2262. run: function(block) {
  2263. runBlocks.push(block);
  2264. return this;
  2265. }
  2266. };
  2267. if (configFn) {
  2268. config(configFn);
  2269. }
  2270. return moduleInstance;
  2271. /**
  2272. * @param {string} provider
  2273. * @param {string} method
  2274. * @param {String=} insertMethod
  2275. * @returns {angular.Module}
  2276. */
  2277. function invokeLater(provider, method, insertMethod, queue) {
  2278. if (!queue) queue = invokeQueue;
  2279. return function() {
  2280. queue[insertMethod || 'push']([provider, method, arguments]);
  2281. return moduleInstance;
  2282. };
  2283. }
  2284. /**
  2285. * @param {string} provider
  2286. * @param {string} method
  2287. * @returns {angular.Module}
  2288. */
  2289. function invokeLaterAndSetModuleName(provider, method, queue) {
  2290. if (!queue) queue = invokeQueue;
  2291. return function(recipeName, factoryFunction) {
  2292. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2293. queue.push([provider, method, arguments]);
  2294. return moduleInstance;
  2295. };
  2296. }
  2297. });
  2298. };
  2299. });
  2300. }
  2301. /* global shallowCopy: true */
  2302. /**
  2303. * Creates a shallow copy of an object, an array or a primitive.
  2304. *
  2305. * Assumes that there are no proto properties for objects.
  2306. */
  2307. function shallowCopy(src, dst) {
  2308. if (isArray(src)) {
  2309. dst = dst || [];
  2310. for (var i = 0, ii = src.length; i < ii; i++) {
  2311. dst[i] = src[i];
  2312. }
  2313. } else if (isObject(src)) {
  2314. dst = dst || {};
  2315. for (var key in src) {
  2316. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2317. dst[key] = src[key];
  2318. }
  2319. }
  2320. }
  2321. return dst || src;
  2322. }
  2323. /* global toDebugString: true */
  2324. function serializeObject(obj, maxDepth) {
  2325. var seen = [];
  2326. // There is no direct way to stringify object until reaching a specific depth
  2327. // and a very deep object can cause a performance issue, so we copy the object
  2328. // based on this specific depth and then stringify it.
  2329. if (isValidObjectMaxDepth(maxDepth)) {
  2330. obj = copy(obj, null, maxDepth);
  2331. }
  2332. return JSON.stringify(obj, function(key, val) {
  2333. val = toJsonReplacer(key, val);
  2334. if (isObject(val)) {
  2335. if (seen.indexOf(val) >= 0) return '...';
  2336. seen.push(val);
  2337. }
  2338. return val;
  2339. });
  2340. }
  2341. function toDebugString(obj, maxDepth) {
  2342. if (typeof obj === 'function') {
  2343. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2344. } else if (isUndefined(obj)) {
  2345. return 'undefined';
  2346. } else if (typeof obj !== 'string') {
  2347. return serializeObject(obj, maxDepth);
  2348. }
  2349. return obj;
  2350. }
  2351. /* global angularModule: true,
  2352. version: true,
  2353. $CompileProvider,
  2354. htmlAnchorDirective,
  2355. inputDirective,
  2356. inputDirective,
  2357. formDirective,
  2358. scriptDirective,
  2359. selectDirective,
  2360. optionDirective,
  2361. ngBindDirective,
  2362. ngBindHtmlDirective,
  2363. ngBindTemplateDirective,
  2364. ngClassDirective,
  2365. ngClassEvenDirective,
  2366. ngClassOddDirective,
  2367. ngCloakDirective,
  2368. ngControllerDirective,
  2369. ngFormDirective,
  2370. ngHideDirective,
  2371. ngIfDirective,
  2372. ngIncludeDirective,
  2373. ngIncludeFillContentDirective,
  2374. ngInitDirective,
  2375. ngNonBindableDirective,
  2376. ngPluralizeDirective,
  2377. ngRepeatDirective,
  2378. ngShowDirective,
  2379. ngStyleDirective,
  2380. ngSwitchDirective,
  2381. ngSwitchWhenDirective,
  2382. ngSwitchDefaultDirective,
  2383. ngOptionsDirective,
  2384. ngTranscludeDirective,
  2385. ngModelDirective,
  2386. ngListDirective,
  2387. ngChangeDirective,
  2388. patternDirective,
  2389. patternDirective,
  2390. requiredDirective,
  2391. requiredDirective,
  2392. minlengthDirective,
  2393. minlengthDirective,
  2394. maxlengthDirective,
  2395. maxlengthDirective,
  2396. ngValueDirective,
  2397. ngModelOptionsDirective,
  2398. ngAttributeAliasDirectives,
  2399. ngEventDirectives,
  2400. $AnchorScrollProvider,
  2401. $AnimateProvider,
  2402. $CoreAnimateCssProvider,
  2403. $$CoreAnimateJsProvider,
  2404. $$CoreAnimateQueueProvider,
  2405. $$AnimateRunnerFactoryProvider,
  2406. $$AnimateAsyncRunFactoryProvider,
  2407. $BrowserProvider,
  2408. $CacheFactoryProvider,
  2409. $ControllerProvider,
  2410. $DateProvider,
  2411. $DocumentProvider,
  2412. $$IsDocumentHiddenProvider,
  2413. $ExceptionHandlerProvider,
  2414. $FilterProvider,
  2415. $$ForceReflowProvider,
  2416. $InterpolateProvider,
  2417. $IntervalProvider,
  2418. $HttpProvider,
  2419. $HttpParamSerializerProvider,
  2420. $HttpParamSerializerJQLikeProvider,
  2421. $HttpBackendProvider,
  2422. $xhrFactoryProvider,
  2423. $jsonpCallbacksProvider,
  2424. $LocationProvider,
  2425. $LogProvider,
  2426. $$MapProvider,
  2427. $ParseProvider,
  2428. $RootScopeProvider,
  2429. $QProvider,
  2430. $$QProvider,
  2431. $$SanitizeUriProvider,
  2432. $SceProvider,
  2433. $SceDelegateProvider,
  2434. $SnifferProvider,
  2435. $TemplateCacheProvider,
  2436. $TemplateRequestProvider,
  2437. $$TestabilityProvider,
  2438. $TimeoutProvider,
  2439. $$RAFProvider,
  2440. $WindowProvider,
  2441. $$jqLiteProvider,
  2442. $$CookieReaderProvider
  2443. */
  2444. /**
  2445. * @ngdoc object
  2446. * @name angular.version
  2447. * @module ng
  2448. * @description
  2449. * An object that contains information about the current AngularJS version.
  2450. *
  2451. * This object has the following properties:
  2452. *
  2453. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2454. * - `major` – `{number}` – Major version number, such as "0".
  2455. * - `minor` – `{number}` – Minor version number, such as "9".
  2456. * - `dot` – `{number}` – Dot version number, such as "18".
  2457. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2458. */
  2459. var version = {
  2460. // These placeholder strings will be replaced by grunt's `build` task.
  2461. // They need to be double- or single-quoted.
  2462. full: '1.6.4',
  2463. major: 1,
  2464. minor: 6,
  2465. dot: 4,
  2466. codeName: 'phenomenal-footnote'
  2467. };
  2468. function publishExternalAPI(angular) {
  2469. extend(angular, {
  2470. 'errorHandlingConfig': errorHandlingConfig,
  2471. 'bootstrap': bootstrap,
  2472. 'copy': copy,
  2473. 'extend': extend,
  2474. 'merge': merge,
  2475. 'equals': equals,
  2476. 'element': jqLite,
  2477. 'forEach': forEach,
  2478. 'injector': createInjector,
  2479. 'noop': noop,
  2480. 'bind': bind,
  2481. 'toJson': toJson,
  2482. 'fromJson': fromJson,
  2483. 'identity': identity,
  2484. 'isUndefined': isUndefined,
  2485. 'isDefined': isDefined,
  2486. 'isString': isString,
  2487. 'isFunction': isFunction,
  2488. 'isObject': isObject,
  2489. 'isNumber': isNumber,
  2490. 'isElement': isElement,
  2491. 'isArray': isArray,
  2492. 'version': version,
  2493. 'isDate': isDate,
  2494. 'lowercase': lowercase,
  2495. 'uppercase': uppercase,
  2496. 'callbacks': {$$counter: 0},
  2497. 'getTestability': getTestability,
  2498. 'reloadWithDebugInfo': reloadWithDebugInfo,
  2499. '$$minErr': minErr,
  2500. '$$csp': csp,
  2501. '$$encodeUriSegment': encodeUriSegment,
  2502. '$$encodeUriQuery': encodeUriQuery,
  2503. '$$stringify': stringify
  2504. });
  2505. angularModule = setupModuleLoader(window);
  2506. angularModule('ng', ['ngLocale'], ['$provide',
  2507. function ngModule($provide) {
  2508. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2509. $provide.provider({
  2510. $$sanitizeUri: $$SanitizeUriProvider
  2511. });
  2512. $provide.provider('$compile', $CompileProvider).
  2513. directive({
  2514. a: htmlAnchorDirective,
  2515. input: inputDirective,
  2516. textarea: inputDirective,
  2517. form: formDirective,
  2518. script: scriptDirective,
  2519. select: selectDirective,
  2520. option: optionDirective,
  2521. ngBind: ngBindDirective,
  2522. ngBindHtml: ngBindHtmlDirective,
  2523. ngBindTemplate: ngBindTemplateDirective,
  2524. ngClass: ngClassDirective,
  2525. ngClassEven: ngClassEvenDirective,
  2526. ngClassOdd: ngClassOddDirective,
  2527. ngCloak: ngCloakDirective,
  2528. ngController: ngControllerDirective,
  2529. ngForm: ngFormDirective,
  2530. ngHide: ngHideDirective,
  2531. ngIf: ngIfDirective,
  2532. ngInclude: ngIncludeDirective,
  2533. ngInit: ngInitDirective,
  2534. ngNonBindable: ngNonBindableDirective,
  2535. ngPluralize: ngPluralizeDirective,
  2536. ngRepeat: ngRepeatDirective,
  2537. ngShow: ngShowDirective,
  2538. ngStyle: ngStyleDirective,
  2539. ngSwitch: ngSwitchDirective,
  2540. ngSwitchWhen: ngSwitchWhenDirective,
  2541. ngSwitchDefault: ngSwitchDefaultDirective,
  2542. ngOptions: ngOptionsDirective,
  2543. ngTransclude: ngTranscludeDirective,
  2544. ngModel: ngModelDirective,
  2545. ngList: ngListDirective,
  2546. ngChange: ngChangeDirective,
  2547. pattern: patternDirective,
  2548. ngPattern: patternDirective,
  2549. required: requiredDirective,
  2550. ngRequired: requiredDirective,
  2551. minlength: minlengthDirective,
  2552. ngMinlength: minlengthDirective,
  2553. maxlength: maxlengthDirective,
  2554. ngMaxlength: maxlengthDirective,
  2555. ngValue: ngValueDirective,
  2556. ngModelOptions: ngModelOptionsDirective
  2557. }).
  2558. directive({
  2559. ngInclude: ngIncludeFillContentDirective
  2560. }).
  2561. directive(ngAttributeAliasDirectives).
  2562. directive(ngEventDirectives);
  2563. $provide.provider({
  2564. $anchorScroll: $AnchorScrollProvider,
  2565. $animate: $AnimateProvider,
  2566. $animateCss: $CoreAnimateCssProvider,
  2567. $$animateJs: $$CoreAnimateJsProvider,
  2568. $$animateQueue: $$CoreAnimateQueueProvider,
  2569. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2570. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2571. $browser: $BrowserProvider,
  2572. $cacheFactory: $CacheFactoryProvider,
  2573. $controller: $ControllerProvider,
  2574. $document: $DocumentProvider,
  2575. $$isDocumentHidden: $$IsDocumentHiddenProvider,
  2576. $exceptionHandler: $ExceptionHandlerProvider,
  2577. $filter: $FilterProvider,
  2578. $$forceReflow: $$ForceReflowProvider,
  2579. $interpolate: $InterpolateProvider,
  2580. $interval: $IntervalProvider,
  2581. $http: $HttpProvider,
  2582. $httpParamSerializer: $HttpParamSerializerProvider,
  2583. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2584. $httpBackend: $HttpBackendProvider,
  2585. $xhrFactory: $xhrFactoryProvider,
  2586. $jsonpCallbacks: $jsonpCallbacksProvider,
  2587. $location: $LocationProvider,
  2588. $log: $LogProvider,
  2589. $parse: $ParseProvider,
  2590. $rootScope: $RootScopeProvider,
  2591. $q: $QProvider,
  2592. $$q: $$QProvider,
  2593. $sce: $SceProvider,
  2594. $sceDelegate: $SceDelegateProvider,
  2595. $sniffer: $SnifferProvider,
  2596. $templateCache: $TemplateCacheProvider,
  2597. $templateRequest: $TemplateRequestProvider,
  2598. $$testability: $$TestabilityProvider,
  2599. $timeout: $TimeoutProvider,
  2600. $window: $WindowProvider,
  2601. $$rAF: $$RAFProvider,
  2602. $$jqLite: $$jqLiteProvider,
  2603. $$Map: $$MapProvider,
  2604. $$cookieReader: $$CookieReaderProvider
  2605. });
  2606. }
  2607. ])
  2608. .info({ angularVersion: '1.6.4' });
  2609. }
  2610. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2611. * Any commits to this file should be reviewed with security in mind. *
  2612. * Changes to this file can potentially create security vulnerabilities. *
  2613. * An approval from 2 Core members with history of modifying *
  2614. * this file is required. *
  2615. * *
  2616. * Does the change somehow allow for arbitrary javascript to be executed? *
  2617. * Or allows for someone to change the prototype of built-in objects? *
  2618. * Or gives undesired access to variables likes document or window? *
  2619. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2620. /* global
  2621. JQLitePrototype: true,
  2622. BOOLEAN_ATTR: true,
  2623. ALIASED_ATTR: true
  2624. */
  2625. //////////////////////////////////
  2626. //JQLite
  2627. //////////////////////////////////
  2628. /**
  2629. * @ngdoc function
  2630. * @name angular.element
  2631. * @module ng
  2632. * @kind function
  2633. *
  2634. * @description
  2635. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2636. *
  2637. * If jQuery is available, `angular.element` is an alias for the
  2638. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2639. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2640. *
  2641. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2642. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2643. * commonly needed functionality with the goal of having a very small footprint.
  2644. *
  2645. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2646. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2647. * specific version of jQuery if multiple versions exist on the page.
  2648. *
  2649. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2650. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2651. *
  2652. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2653. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2654. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2655. *
  2656. * ## Angular's jqLite
  2657. * jqLite provides only the following jQuery methods:
  2658. *
  2659. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2660. * - [`after()`](http://api.jquery.com/after/)
  2661. * - [`append()`](http://api.jquery.com/append/)
  2662. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2663. * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
  2664. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2665. * - [`clone()`](http://api.jquery.com/clone/)
  2666. * - [`contents()`](http://api.jquery.com/contents/)
  2667. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2668. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2669. * - [`data()`](http://api.jquery.com/data/)
  2670. * - [`detach()`](http://api.jquery.com/detach/)
  2671. * - [`empty()`](http://api.jquery.com/empty/)
  2672. * - [`eq()`](http://api.jquery.com/eq/)
  2673. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2674. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2675. * - [`html()`](http://api.jquery.com/html/)
  2676. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2677. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2678. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2679. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2680. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2681. * - [`prepend()`](http://api.jquery.com/prepend/)
  2682. * - [`prop()`](http://api.jquery.com/prop/)
  2683. * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
  2684. * - [`remove()`](http://api.jquery.com/remove/)
  2685. * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
  2686. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2687. * - [`removeData()`](http://api.jquery.com/removeData/)
  2688. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2689. * - [`text()`](http://api.jquery.com/text/)
  2690. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2691. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2692. * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
  2693. * - [`val()`](http://api.jquery.com/val/)
  2694. * - [`wrap()`](http://api.jquery.com/wrap/)
  2695. *
  2696. * ## jQuery/jqLite Extras
  2697. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2698. *
  2699. * ### Events
  2700. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2701. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2702. * element before it is removed.
  2703. *
  2704. * ### Methods
  2705. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2706. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2707. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2708. * `'ngModel'`).
  2709. * - `injector()` - retrieves the injector of the current element or its parent.
  2710. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2711. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2712. * be enabled.
  2713. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2714. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2715. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2716. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2717. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2718. * parent element is reached.
  2719. *
  2720. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2721. * https://github.com/angular/angular.js/issues/14251 for more information.
  2722. *
  2723. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2724. * @returns {Object} jQuery object.
  2725. */
  2726. JQLite.expando = 'ng339';
  2727. var jqCache = JQLite.cache = {},
  2728. jqId = 1;
  2729. /*
  2730. * !!! This is an undocumented "private" function !!!
  2731. */
  2732. JQLite._data = function(node) {
  2733. //jQuery always returns an object on cache miss
  2734. return this.cache[node[this.expando]] || {};
  2735. };
  2736. function jqNextId() { return ++jqId; }
  2737. var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
  2738. var MS_HACK_REGEXP = /^-ms-/;
  2739. var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
  2740. var jqLiteMinErr = minErr('jqLite');
  2741. /**
  2742. * Converts kebab-case to camelCase.
  2743. * There is also a special case for the ms prefix starting with a lowercase letter.
  2744. * @param name Name to normalize
  2745. */
  2746. function cssKebabToCamel(name) {
  2747. return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
  2748. }
  2749. function fnCamelCaseReplace(all, letter) {
  2750. return letter.toUpperCase();
  2751. }
  2752. /**
  2753. * Converts kebab-case to camelCase.
  2754. * @param name Name to normalize
  2755. */
  2756. function kebabToCamel(name) {
  2757. return name
  2758. .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
  2759. }
  2760. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2761. var HTML_REGEXP = /<|&#?\w+;/;
  2762. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2763. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2764. var wrapMap = {
  2765. 'option': [1, '<select multiple="multiple">', '</select>'],
  2766. 'thead': [1, '<table>', '</table>'],
  2767. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2768. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2769. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2770. '_default': [0, '', '']
  2771. };
  2772. wrapMap.optgroup = wrapMap.option;
  2773. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2774. wrapMap.th = wrapMap.td;
  2775. function jqLiteIsTextNode(html) {
  2776. return !HTML_REGEXP.test(html);
  2777. }
  2778. function jqLiteAcceptsData(node) {
  2779. // The window object can accept data but has no nodeType
  2780. // Otherwise we are only interested in elements (1) and documents (9)
  2781. var nodeType = node.nodeType;
  2782. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2783. }
  2784. function jqLiteHasData(node) {
  2785. for (var key in jqCache[node.ng339]) {
  2786. return true;
  2787. }
  2788. return false;
  2789. }
  2790. function jqLiteBuildFragment(html, context) {
  2791. var tmp, tag, wrap,
  2792. fragment = context.createDocumentFragment(),
  2793. nodes = [], i;
  2794. if (jqLiteIsTextNode(html)) {
  2795. // Convert non-html into a text node
  2796. nodes.push(context.createTextNode(html));
  2797. } else {
  2798. // Convert html into DOM nodes
  2799. tmp = fragment.appendChild(context.createElement('div'));
  2800. tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
  2801. wrap = wrapMap[tag] || wrapMap._default;
  2802. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
  2803. // Descend through wrappers to the right content
  2804. i = wrap[0];
  2805. while (i--) {
  2806. tmp = tmp.lastChild;
  2807. }
  2808. nodes = concat(nodes, tmp.childNodes);
  2809. tmp = fragment.firstChild;
  2810. tmp.textContent = '';
  2811. }
  2812. // Remove wrapper from fragment
  2813. fragment.textContent = '';
  2814. fragment.innerHTML = ''; // Clear inner HTML
  2815. forEach(nodes, function(node) {
  2816. fragment.appendChild(node);
  2817. });
  2818. return fragment;
  2819. }
  2820. function jqLiteParseHTML(html, context) {
  2821. context = context || window.document;
  2822. var parsed;
  2823. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2824. return [context.createElement(parsed[1])];
  2825. }
  2826. if ((parsed = jqLiteBuildFragment(html, context))) {
  2827. return parsed.childNodes;
  2828. }
  2829. return [];
  2830. }
  2831. function jqLiteWrapNode(node, wrapper) {
  2832. var parent = node.parentNode;
  2833. if (parent) {
  2834. parent.replaceChild(wrapper, node);
  2835. }
  2836. wrapper.appendChild(node);
  2837. }
  2838. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2839. var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
  2840. // eslint-disable-next-line no-bitwise
  2841. return !!(this.compareDocumentPosition(arg) & 16);
  2842. };
  2843. /////////////////////////////////////////////
  2844. function JQLite(element) {
  2845. if (element instanceof JQLite) {
  2846. return element;
  2847. }
  2848. var argIsString;
  2849. if (isString(element)) {
  2850. element = trim(element);
  2851. argIsString = true;
  2852. }
  2853. if (!(this instanceof JQLite)) {
  2854. if (argIsString && element.charAt(0) !== '<') {
  2855. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2856. }
  2857. return new JQLite(element);
  2858. }
  2859. if (argIsString) {
  2860. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2861. } else if (isFunction(element)) {
  2862. jqLiteReady(element);
  2863. } else {
  2864. jqLiteAddNodes(this, element);
  2865. }
  2866. }
  2867. function jqLiteClone(element) {
  2868. return element.cloneNode(true);
  2869. }
  2870. function jqLiteDealoc(element, onlyDescendants) {
  2871. if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]);
  2872. if (element.querySelectorAll) {
  2873. jqLite.cleanData(element.querySelectorAll('*'));
  2874. }
  2875. }
  2876. function jqLiteOff(element, type, fn, unsupported) {
  2877. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2878. var expandoStore = jqLiteExpandoStore(element);
  2879. var events = expandoStore && expandoStore.events;
  2880. var handle = expandoStore && expandoStore.handle;
  2881. if (!handle) return; //no listeners registered
  2882. if (!type) {
  2883. for (type in events) {
  2884. if (type !== '$destroy') {
  2885. element.removeEventListener(type, handle);
  2886. }
  2887. delete events[type];
  2888. }
  2889. } else {
  2890. var removeHandler = function(type) {
  2891. var listenerFns = events[type];
  2892. if (isDefined(fn)) {
  2893. arrayRemove(listenerFns || [], fn);
  2894. }
  2895. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2896. element.removeEventListener(type, handle);
  2897. delete events[type];
  2898. }
  2899. };
  2900. forEach(type.split(' '), function(type) {
  2901. removeHandler(type);
  2902. if (MOUSE_EVENT_MAP[type]) {
  2903. removeHandler(MOUSE_EVENT_MAP[type]);
  2904. }
  2905. });
  2906. }
  2907. }
  2908. function jqLiteRemoveData(element, name) {
  2909. var expandoId = element.ng339;
  2910. var expandoStore = expandoId && jqCache[expandoId];
  2911. if (expandoStore) {
  2912. if (name) {
  2913. delete expandoStore.data[name];
  2914. return;
  2915. }
  2916. if (expandoStore.handle) {
  2917. if (expandoStore.events.$destroy) {
  2918. expandoStore.handle({}, '$destroy');
  2919. }
  2920. jqLiteOff(element);
  2921. }
  2922. delete jqCache[expandoId];
  2923. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2924. }
  2925. }
  2926. function jqLiteExpandoStore(element, createIfNecessary) {
  2927. var expandoId = element.ng339,
  2928. expandoStore = expandoId && jqCache[expandoId];
  2929. if (createIfNecessary && !expandoStore) {
  2930. element.ng339 = expandoId = jqNextId();
  2931. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2932. }
  2933. return expandoStore;
  2934. }
  2935. function jqLiteData(element, key, value) {
  2936. if (jqLiteAcceptsData(element)) {
  2937. var prop;
  2938. var isSimpleSetter = isDefined(value);
  2939. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2940. var massGetter = !key;
  2941. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2942. var data = expandoStore && expandoStore.data;
  2943. if (isSimpleSetter) { // data('key', value)
  2944. data[kebabToCamel(key)] = value;
  2945. } else {
  2946. if (massGetter) { // data()
  2947. return data;
  2948. } else {
  2949. if (isSimpleGetter) { // data('key')
  2950. // don't force creation of expandoStore if it doesn't exist yet
  2951. return data && data[kebabToCamel(key)];
  2952. } else { // mass-setter: data({key1: val1, key2: val2})
  2953. for (prop in key) {
  2954. data[kebabToCamel(prop)] = key[prop];
  2955. }
  2956. }
  2957. }
  2958. }
  2959. }
  2960. }
  2961. function jqLiteHasClass(element, selector) {
  2962. if (!element.getAttribute) return false;
  2963. return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
  2964. indexOf(' ' + selector + ' ') > -1);
  2965. }
  2966. function jqLiteRemoveClass(element, cssClasses) {
  2967. if (cssClasses && element.setAttribute) {
  2968. forEach(cssClasses.split(' '), function(cssClass) {
  2969. element.setAttribute('class', trim(
  2970. (' ' + (element.getAttribute('class') || '') + ' ')
  2971. .replace(/[\n\t]/g, ' ')
  2972. .replace(' ' + trim(cssClass) + ' ', ' '))
  2973. );
  2974. });
  2975. }
  2976. }
  2977. function jqLiteAddClass(element, cssClasses) {
  2978. if (cssClasses && element.setAttribute) {
  2979. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2980. .replace(/[\n\t]/g, ' ');
  2981. forEach(cssClasses.split(' '), function(cssClass) {
  2982. cssClass = trim(cssClass);
  2983. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2984. existingClasses += cssClass + ' ';
  2985. }
  2986. });
  2987. element.setAttribute('class', trim(existingClasses));
  2988. }
  2989. }
  2990. function jqLiteAddNodes(root, elements) {
  2991. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2992. if (elements) {
  2993. // if a Node (the most common case)
  2994. if (elements.nodeType) {
  2995. root[root.length++] = elements;
  2996. } else {
  2997. var length = elements.length;
  2998. // if an Array or NodeList and not a Window
  2999. if (typeof length === 'number' && elements.window !== elements) {
  3000. if (length) {
  3001. for (var i = 0; i < length; i++) {
  3002. root[root.length++] = elements[i];
  3003. }
  3004. }
  3005. } else {
  3006. root[root.length++] = elements;
  3007. }
  3008. }
  3009. }
  3010. }
  3011. function jqLiteController(element, name) {
  3012. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  3013. }
  3014. function jqLiteInheritedData(element, name, value) {
  3015. // if element is the document object work with the html element instead
  3016. // this makes $(document).scope() possible
  3017. if (element.nodeType === NODE_TYPE_DOCUMENT) {
  3018. element = element.documentElement;
  3019. }
  3020. var names = isArray(name) ? name : [name];
  3021. while (element) {
  3022. for (var i = 0, ii = names.length; i < ii; i++) {
  3023. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  3024. }
  3025. // If dealing with a document fragment node with a host element, and no parent, use the host
  3026. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  3027. // to lookup parent controllers.
  3028. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  3029. }
  3030. }
  3031. function jqLiteEmpty(element) {
  3032. jqLiteDealoc(element, true);
  3033. while (element.firstChild) {
  3034. element.removeChild(element.firstChild);
  3035. }
  3036. }
  3037. function jqLiteRemove(element, keepData) {
  3038. if (!keepData) jqLiteDealoc(element);
  3039. var parent = element.parentNode;
  3040. if (parent) parent.removeChild(element);
  3041. }
  3042. function jqLiteDocumentLoaded(action, win) {
  3043. win = win || window;
  3044. if (win.document.readyState === 'complete') {
  3045. // Force the action to be run async for consistent behavior
  3046. // from the action's point of view
  3047. // i.e. it will definitely not be in a $apply
  3048. win.setTimeout(action);
  3049. } else {
  3050. // No need to unbind this handler as load is only ever called once
  3051. jqLite(win).on('load', action);
  3052. }
  3053. }
  3054. function jqLiteReady(fn) {
  3055. function trigger() {
  3056. window.document.removeEventListener('DOMContentLoaded', trigger);
  3057. window.removeEventListener('load', trigger);
  3058. fn();
  3059. }
  3060. // check if document is already loaded
  3061. if (window.document.readyState === 'complete') {
  3062. window.setTimeout(fn);
  3063. } else {
  3064. // We can not use jqLite since we are not done loading and jQuery could be loaded later.
  3065. // Works for modern browsers and IE9
  3066. window.document.addEventListener('DOMContentLoaded', trigger);
  3067. // Fallback to window.onload for others
  3068. window.addEventListener('load', trigger);
  3069. }
  3070. }
  3071. //////////////////////////////////////////
  3072. // Functions which are declared directly.
  3073. //////////////////////////////////////////
  3074. var JQLitePrototype = JQLite.prototype = {
  3075. ready: jqLiteReady,
  3076. toString: function() {
  3077. var value = [];
  3078. forEach(this, function(e) { value.push('' + e);});
  3079. return '[' + value.join(', ') + ']';
  3080. },
  3081. eq: function(index) {
  3082. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  3083. },
  3084. length: 0,
  3085. push: push,
  3086. sort: [].sort,
  3087. splice: [].splice
  3088. };
  3089. //////////////////////////////////////////
  3090. // Functions iterating getter/setters.
  3091. // these functions return self on setter and
  3092. // value on get.
  3093. //////////////////////////////////////////
  3094. var BOOLEAN_ATTR = {};
  3095. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  3096. BOOLEAN_ATTR[lowercase(value)] = value;
  3097. });
  3098. var BOOLEAN_ELEMENTS = {};
  3099. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  3100. BOOLEAN_ELEMENTS[value] = true;
  3101. });
  3102. var ALIASED_ATTR = {
  3103. 'ngMinlength': 'minlength',
  3104. 'ngMaxlength': 'maxlength',
  3105. 'ngMin': 'min',
  3106. 'ngMax': 'max',
  3107. 'ngPattern': 'pattern',
  3108. 'ngStep': 'step'
  3109. };
  3110. function getBooleanAttrName(element, name) {
  3111. // check dom last since we will most likely fail on name
  3112. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  3113. // booleanAttr is here twice to minimize DOM access
  3114. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  3115. }
  3116. function getAliasedAttrName(name) {
  3117. return ALIASED_ATTR[name];
  3118. }
  3119. forEach({
  3120. data: jqLiteData,
  3121. removeData: jqLiteRemoveData,
  3122. hasData: jqLiteHasData,
  3123. cleanData: function jqLiteCleanData(nodes) {
  3124. for (var i = 0, ii = nodes.length; i < ii; i++) {
  3125. jqLiteRemoveData(nodes[i]);
  3126. }
  3127. }
  3128. }, function(fn, name) {
  3129. JQLite[name] = fn;
  3130. });
  3131. forEach({
  3132. data: jqLiteData,
  3133. inheritedData: jqLiteInheritedData,
  3134. scope: function(element) {
  3135. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3136. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  3137. },
  3138. isolateScope: function(element) {
  3139. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3140. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  3141. },
  3142. controller: jqLiteController,
  3143. injector: function(element) {
  3144. return jqLiteInheritedData(element, '$injector');
  3145. },
  3146. removeAttr: function(element, name) {
  3147. element.removeAttribute(name);
  3148. },
  3149. hasClass: jqLiteHasClass,
  3150. css: function(element, name, value) {
  3151. name = cssKebabToCamel(name);
  3152. if (isDefined(value)) {
  3153. element.style[name] = value;
  3154. } else {
  3155. return element.style[name];
  3156. }
  3157. },
  3158. attr: function(element, name, value) {
  3159. var ret;
  3160. var nodeType = element.nodeType;
  3161. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
  3162. !element.getAttribute) {
  3163. return;
  3164. }
  3165. var lowercasedName = lowercase(name);
  3166. var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
  3167. if (isDefined(value)) {
  3168. // setter
  3169. if (value === null || (value === false && isBooleanAttr)) {
  3170. element.removeAttribute(name);
  3171. } else {
  3172. element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
  3173. }
  3174. } else {
  3175. // getter
  3176. ret = element.getAttribute(name);
  3177. if (isBooleanAttr && ret !== null) {
  3178. ret = lowercasedName;
  3179. }
  3180. // Normalize non-existing attributes to undefined (as jQuery).
  3181. return ret === null ? undefined : ret;
  3182. }
  3183. },
  3184. prop: function(element, name, value) {
  3185. if (isDefined(value)) {
  3186. element[name] = value;
  3187. } else {
  3188. return element[name];
  3189. }
  3190. },
  3191. text: (function() {
  3192. getText.$dv = '';
  3193. return getText;
  3194. function getText(element, value) {
  3195. if (isUndefined(value)) {
  3196. var nodeType = element.nodeType;
  3197. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  3198. }
  3199. element.textContent = value;
  3200. }
  3201. })(),
  3202. val: function(element, value) {
  3203. if (isUndefined(value)) {
  3204. if (element.multiple && nodeName_(element) === 'select') {
  3205. var result = [];
  3206. forEach(element.options, function(option) {
  3207. if (option.selected) {
  3208. result.push(option.value || option.text);
  3209. }
  3210. });
  3211. return result;
  3212. }
  3213. return element.value;
  3214. }
  3215. element.value = value;
  3216. },
  3217. html: function(element, value) {
  3218. if (isUndefined(value)) {
  3219. return element.innerHTML;
  3220. }
  3221. jqLiteDealoc(element, true);
  3222. element.innerHTML = value;
  3223. },
  3224. empty: jqLiteEmpty
  3225. }, function(fn, name) {
  3226. /**
  3227. * Properties: writes return selection, reads return first value
  3228. */
  3229. JQLite.prototype[name] = function(arg1, arg2) {
  3230. var i, key;
  3231. var nodeCount = this.length;
  3232. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3233. // in a way that survives minification.
  3234. // jqLiteEmpty takes no arguments but is a setter.
  3235. if (fn !== jqLiteEmpty &&
  3236. (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3237. if (isObject(arg1)) {
  3238. // we are a write, but the object properties are the key/values
  3239. for (i = 0; i < nodeCount; i++) {
  3240. if (fn === jqLiteData) {
  3241. // data() takes the whole object in jQuery
  3242. fn(this[i], arg1);
  3243. } else {
  3244. for (key in arg1) {
  3245. fn(this[i], key, arg1[key]);
  3246. }
  3247. }
  3248. }
  3249. // return self for chaining
  3250. return this;
  3251. } else {
  3252. // we are a read, so read the first child.
  3253. // TODO: do we still need this?
  3254. var value = fn.$dv;
  3255. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3256. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3257. for (var j = 0; j < jj; j++) {
  3258. var nodeValue = fn(this[j], arg1, arg2);
  3259. value = value ? value + nodeValue : nodeValue;
  3260. }
  3261. return value;
  3262. }
  3263. } else {
  3264. // we are a write, so apply to all children
  3265. for (i = 0; i < nodeCount; i++) {
  3266. fn(this[i], arg1, arg2);
  3267. }
  3268. // return self for chaining
  3269. return this;
  3270. }
  3271. };
  3272. });
  3273. function createEventHandler(element, events) {
  3274. var eventHandler = function(event, type) {
  3275. // jQuery specific api
  3276. event.isDefaultPrevented = function() {
  3277. return event.defaultPrevented;
  3278. };
  3279. var eventFns = events[type || event.type];
  3280. var eventFnsLength = eventFns ? eventFns.length : 0;
  3281. if (!eventFnsLength) return;
  3282. if (isUndefined(event.immediatePropagationStopped)) {
  3283. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3284. event.stopImmediatePropagation = function() {
  3285. event.immediatePropagationStopped = true;
  3286. if (event.stopPropagation) {
  3287. event.stopPropagation();
  3288. }
  3289. if (originalStopImmediatePropagation) {
  3290. originalStopImmediatePropagation.call(event);
  3291. }
  3292. };
  3293. }
  3294. event.isImmediatePropagationStopped = function() {
  3295. return event.immediatePropagationStopped === true;
  3296. };
  3297. // Some events have special handlers that wrap the real handler
  3298. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3299. // Copy event handlers in case event handlers array is modified during execution.
  3300. if ((eventFnsLength > 1)) {
  3301. eventFns = shallowCopy(eventFns);
  3302. }
  3303. for (var i = 0; i < eventFnsLength; i++) {
  3304. if (!event.isImmediatePropagationStopped()) {
  3305. handlerWrapper(element, event, eventFns[i]);
  3306. }
  3307. }
  3308. };
  3309. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3310. // events on `element`
  3311. eventHandler.elem = element;
  3312. return eventHandler;
  3313. }
  3314. function defaultHandlerWrapper(element, event, handler) {
  3315. handler.call(element, event);
  3316. }
  3317. function specialMouseHandlerWrapper(target, event, handler) {
  3318. // Refer to jQuery's implementation of mouseenter & mouseleave
  3319. // Read about mouseenter and mouseleave:
  3320. // http://www.quirksmode.org/js/events_mouse.html#link8
  3321. var related = event.relatedTarget;
  3322. // For mousenter/leave call the handler if related is outside the target.
  3323. // NB: No relatedTarget if the mouse left/entered the browser window
  3324. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3325. handler.call(target, event);
  3326. }
  3327. }
  3328. //////////////////////////////////////////
  3329. // Functions iterating traversal.
  3330. // These functions chain results into a single
  3331. // selector.
  3332. //////////////////////////////////////////
  3333. forEach({
  3334. removeData: jqLiteRemoveData,
  3335. on: function jqLiteOn(element, type, fn, unsupported) {
  3336. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3337. // Do not add event handlers to non-elements because they will not be cleaned up.
  3338. if (!jqLiteAcceptsData(element)) {
  3339. return;
  3340. }
  3341. var expandoStore = jqLiteExpandoStore(element, true);
  3342. var events = expandoStore.events;
  3343. var handle = expandoStore.handle;
  3344. if (!handle) {
  3345. handle = expandoStore.handle = createEventHandler(element, events);
  3346. }
  3347. // http://jsperf.com/string-indexof-vs-split
  3348. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3349. var i = types.length;
  3350. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3351. var eventFns = events[type];
  3352. if (!eventFns) {
  3353. eventFns = events[type] = [];
  3354. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3355. if (type !== '$destroy' && !noEventListener) {
  3356. element.addEventListener(type, handle);
  3357. }
  3358. }
  3359. eventFns.push(fn);
  3360. };
  3361. while (i--) {
  3362. type = types[i];
  3363. if (MOUSE_EVENT_MAP[type]) {
  3364. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3365. addHandler(type, undefined, true);
  3366. } else {
  3367. addHandler(type);
  3368. }
  3369. }
  3370. },
  3371. off: jqLiteOff,
  3372. one: function(element, type, fn) {
  3373. element = jqLite(element);
  3374. //add the listener twice so that when it is called
  3375. //you can remove the original function and still be
  3376. //able to call element.off(ev, fn) normally
  3377. element.on(type, function onFn() {
  3378. element.off(type, fn);
  3379. element.off(type, onFn);
  3380. });
  3381. element.on(type, fn);
  3382. },
  3383. replaceWith: function(element, replaceNode) {
  3384. var index, parent = element.parentNode;
  3385. jqLiteDealoc(element);
  3386. forEach(new JQLite(replaceNode), function(node) {
  3387. if (index) {
  3388. parent.insertBefore(node, index.nextSibling);
  3389. } else {
  3390. parent.replaceChild(node, element);
  3391. }
  3392. index = node;
  3393. });
  3394. },
  3395. children: function(element) {
  3396. var children = [];
  3397. forEach(element.childNodes, function(element) {
  3398. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3399. children.push(element);
  3400. }
  3401. });
  3402. return children;
  3403. },
  3404. contents: function(element) {
  3405. return element.contentDocument || element.childNodes || [];
  3406. },
  3407. append: function(element, node) {
  3408. var nodeType = element.nodeType;
  3409. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3410. node = new JQLite(node);
  3411. for (var i = 0, ii = node.length; i < ii; i++) {
  3412. var child = node[i];
  3413. element.appendChild(child);
  3414. }
  3415. },
  3416. prepend: function(element, node) {
  3417. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3418. var index = element.firstChild;
  3419. forEach(new JQLite(node), function(child) {
  3420. element.insertBefore(child, index);
  3421. });
  3422. }
  3423. },
  3424. wrap: function(element, wrapNode) {
  3425. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3426. },
  3427. remove: jqLiteRemove,
  3428. detach: function(element) {
  3429. jqLiteRemove(element, true);
  3430. },
  3431. after: function(element, newElement) {
  3432. var index = element, parent = element.parentNode;
  3433. if (parent) {
  3434. newElement = new JQLite(newElement);
  3435. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3436. var node = newElement[i];
  3437. parent.insertBefore(node, index.nextSibling);
  3438. index = node;
  3439. }
  3440. }
  3441. },
  3442. addClass: jqLiteAddClass,
  3443. removeClass: jqLiteRemoveClass,
  3444. toggleClass: function(element, selector, condition) {
  3445. if (selector) {
  3446. forEach(selector.split(' '), function(className) {
  3447. var classCondition = condition;
  3448. if (isUndefined(classCondition)) {
  3449. classCondition = !jqLiteHasClass(element, className);
  3450. }
  3451. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3452. });
  3453. }
  3454. },
  3455. parent: function(element) {
  3456. var parent = element.parentNode;
  3457. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3458. },
  3459. next: function(element) {
  3460. return element.nextElementSibling;
  3461. },
  3462. find: function(element, selector) {
  3463. if (element.getElementsByTagName) {
  3464. return element.getElementsByTagName(selector);
  3465. } else {
  3466. return [];
  3467. }
  3468. },
  3469. clone: jqLiteClone,
  3470. triggerHandler: function(element, event, extraParameters) {
  3471. var dummyEvent, eventFnsCopy, handlerArgs;
  3472. var eventName = event.type || event;
  3473. var expandoStore = jqLiteExpandoStore(element);
  3474. var events = expandoStore && expandoStore.events;
  3475. var eventFns = events && events[eventName];
  3476. if (eventFns) {
  3477. // Create a dummy event to pass to the handlers
  3478. dummyEvent = {
  3479. preventDefault: function() { this.defaultPrevented = true; },
  3480. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3481. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3482. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3483. stopPropagation: noop,
  3484. type: eventName,
  3485. target: element
  3486. };
  3487. // If a custom event was provided then extend our dummy event with it
  3488. if (event.type) {
  3489. dummyEvent = extend(dummyEvent, event);
  3490. }
  3491. // Copy event handlers in case event handlers array is modified during execution.
  3492. eventFnsCopy = shallowCopy(eventFns);
  3493. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3494. forEach(eventFnsCopy, function(fn) {
  3495. if (!dummyEvent.isImmediatePropagationStopped()) {
  3496. fn.apply(element, handlerArgs);
  3497. }
  3498. });
  3499. }
  3500. }
  3501. }, function(fn, name) {
  3502. /**
  3503. * chaining functions
  3504. */
  3505. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3506. var value;
  3507. for (var i = 0, ii = this.length; i < ii; i++) {
  3508. if (isUndefined(value)) {
  3509. value = fn(this[i], arg1, arg2, arg3);
  3510. if (isDefined(value)) {
  3511. // any function which returns a value needs to be wrapped
  3512. value = jqLite(value);
  3513. }
  3514. } else {
  3515. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3516. }
  3517. }
  3518. return isDefined(value) ? value : this;
  3519. };
  3520. });
  3521. // bind legacy bind/unbind to on/off
  3522. JQLite.prototype.bind = JQLite.prototype.on;
  3523. JQLite.prototype.unbind = JQLite.prototype.off;
  3524. // Provider for private $$jqLite service
  3525. /** @this */
  3526. function $$jqLiteProvider() {
  3527. this.$get = function $$jqLite() {
  3528. return extend(JQLite, {
  3529. hasClass: function(node, classes) {
  3530. if (node.attr) node = node[0];
  3531. return jqLiteHasClass(node, classes);
  3532. },
  3533. addClass: function(node, classes) {
  3534. if (node.attr) node = node[0];
  3535. return jqLiteAddClass(node, classes);
  3536. },
  3537. removeClass: function(node, classes) {
  3538. if (node.attr) node = node[0];
  3539. return jqLiteRemoveClass(node, classes);
  3540. }
  3541. });
  3542. };
  3543. }
  3544. /**
  3545. * Computes a hash of an 'obj'.
  3546. * Hash of a:
  3547. * string is string
  3548. * number is number as string
  3549. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3550. * that is also assigned to the $$hashKey property of the object.
  3551. *
  3552. * @param obj
  3553. * @returns {string} hash string such that the same input will have the same hash string.
  3554. * The resulting string key is in 'type:hashKey' format.
  3555. */
  3556. function hashKey(obj, nextUidFn) {
  3557. var key = obj && obj.$$hashKey;
  3558. if (key) {
  3559. if (typeof key === 'function') {
  3560. key = obj.$$hashKey();
  3561. }
  3562. return key;
  3563. }
  3564. var objType = typeof obj;
  3565. if (objType === 'function' || (objType === 'object' && obj !== null)) {
  3566. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3567. } else {
  3568. key = objType + ':' + obj;
  3569. }
  3570. return key;
  3571. }
  3572. // A minimal ES2015 Map implementation.
  3573. // Should be bug/feature equivalent to the native implementations of supported browsers
  3574. // (for the features required in Angular).
  3575. // See https://kangax.github.io/compat-table/es6/#test-Map
  3576. var nanKey = Object.create(null);
  3577. function NgMapShim() {
  3578. this._keys = [];
  3579. this._values = [];
  3580. this._lastKey = NaN;
  3581. this._lastIndex = -1;
  3582. }
  3583. NgMapShim.prototype = {
  3584. _idx: function(key) {
  3585. if (key === this._lastKey) {
  3586. return this._lastIndex;
  3587. }
  3588. this._lastKey = key;
  3589. this._lastIndex = this._keys.indexOf(key);
  3590. return this._lastIndex;
  3591. },
  3592. _transformKey: function(key) {
  3593. return isNumberNaN(key) ? nanKey : key;
  3594. },
  3595. get: function(key) {
  3596. key = this._transformKey(key);
  3597. var idx = this._idx(key);
  3598. if (idx !== -1) {
  3599. return this._values[idx];
  3600. }
  3601. },
  3602. set: function(key, value) {
  3603. key = this._transformKey(key);
  3604. var idx = this._idx(key);
  3605. if (idx === -1) {
  3606. idx = this._lastIndex = this._keys.length;
  3607. }
  3608. this._keys[idx] = key;
  3609. this._values[idx] = value;
  3610. // Support: IE11
  3611. // Do not `return this` to simulate the partial IE11 implementation
  3612. },
  3613. delete: function(key) {
  3614. key = this._transformKey(key);
  3615. var idx = this._idx(key);
  3616. if (idx === -1) {
  3617. return false;
  3618. }
  3619. this._keys.splice(idx, 1);
  3620. this._values.splice(idx, 1);
  3621. this._lastKey = NaN;
  3622. this._lastIndex = -1;
  3623. return true;
  3624. }
  3625. };
  3626. // For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations
  3627. // are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`
  3628. // implementations get more stable, we can reconsider switching to `window.Map` (when available).
  3629. var NgMap = NgMapShim;
  3630. var $$MapProvider = [/** @this */function() {
  3631. this.$get = [function() {
  3632. return NgMap;
  3633. }];
  3634. }];
  3635. /**
  3636. * @ngdoc function
  3637. * @module ng
  3638. * @name angular.injector
  3639. * @kind function
  3640. *
  3641. * @description
  3642. * Creates an injector object that can be used for retrieving services as well as for
  3643. * dependency injection (see {@link guide/di dependency injection}).
  3644. *
  3645. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3646. * {@link angular.module}. The `ng` module must be explicitly added.
  3647. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3648. * disallows argument name annotation inference.
  3649. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3650. *
  3651. * @example
  3652. * Typical usage
  3653. * ```js
  3654. * // create an injector
  3655. * var $injector = angular.injector(['ng']);
  3656. *
  3657. * // use the injector to kick off your application
  3658. * // use the type inference to auto inject arguments, or use implicit injection
  3659. * $injector.invoke(function($rootScope, $compile, $document) {
  3660. * $compile($document)($rootScope);
  3661. * $rootScope.$digest();
  3662. * });
  3663. * ```
  3664. *
  3665. * Sometimes you want to get access to the injector of a currently running Angular app
  3666. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3667. * application has been bootstrapped. You can do this using the extra `injector()` added
  3668. * to JQuery/jqLite elements. See {@link angular.element}.
  3669. *
  3670. * *This is fairly rare but could be the case if a third party library is injecting the
  3671. * markup.*
  3672. *
  3673. * In the following example a new block of HTML containing a `ng-controller`
  3674. * directive is added to the end of the document body by JQuery. We then compile and link
  3675. * it into the current AngularJS scope.
  3676. *
  3677. * ```js
  3678. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3679. * $(document.body).append($div);
  3680. *
  3681. * angular.element(document).injector().invoke(function($compile) {
  3682. * var scope = angular.element($div).scope();
  3683. * $compile($div)(scope);
  3684. * });
  3685. * ```
  3686. */
  3687. /**
  3688. * @ngdoc module
  3689. * @name auto
  3690. * @installation
  3691. * @description
  3692. *
  3693. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3694. */
  3695. var ARROW_ARG = /^([^(]+?)=>/;
  3696. var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
  3697. var FN_ARG_SPLIT = /,/;
  3698. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3699. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3700. var $injectorMinErr = minErr('$injector');
  3701. function stringifyFn(fn) {
  3702. return Function.prototype.toString.call(fn);
  3703. }
  3704. function extractArgs(fn) {
  3705. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3706. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3707. return args;
  3708. }
  3709. function anonFn(fn) {
  3710. // For anonymous functions, showing at the very least the function signature can help in
  3711. // debugging.
  3712. var args = extractArgs(fn);
  3713. if (args) {
  3714. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3715. }
  3716. return 'fn';
  3717. }
  3718. function annotate(fn, strictDi, name) {
  3719. var $inject,
  3720. argDecl,
  3721. last;
  3722. if (typeof fn === 'function') {
  3723. if (!($inject = fn.$inject)) {
  3724. $inject = [];
  3725. if (fn.length) {
  3726. if (strictDi) {
  3727. if (!isString(name) || !name) {
  3728. name = fn.name || anonFn(fn);
  3729. }
  3730. throw $injectorMinErr('strictdi',
  3731. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3732. }
  3733. argDecl = extractArgs(fn);
  3734. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3735. arg.replace(FN_ARG, function(all, underscore, name) {
  3736. $inject.push(name);
  3737. });
  3738. });
  3739. }
  3740. fn.$inject = $inject;
  3741. }
  3742. } else if (isArray(fn)) {
  3743. last = fn.length - 1;
  3744. assertArgFn(fn[last], 'fn');
  3745. $inject = fn.slice(0, last);
  3746. } else {
  3747. assertArgFn(fn, 'fn', true);
  3748. }
  3749. return $inject;
  3750. }
  3751. ///////////////////////////////////////
  3752. /**
  3753. * @ngdoc service
  3754. * @name $injector
  3755. *
  3756. * @description
  3757. *
  3758. * `$injector` is used to retrieve object instances as defined by
  3759. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3760. * and load modules.
  3761. *
  3762. * The following always holds true:
  3763. *
  3764. * ```js
  3765. * var $injector = angular.injector();
  3766. * expect($injector.get('$injector')).toBe($injector);
  3767. * expect($injector.invoke(function($injector) {
  3768. * return $injector;
  3769. * })).toBe($injector);
  3770. * ```
  3771. *
  3772. * # Injection Function Annotation
  3773. *
  3774. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3775. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3776. *
  3777. * ```js
  3778. * // inferred (only works if code not minified/obfuscated)
  3779. * $injector.invoke(function(serviceA){});
  3780. *
  3781. * // annotated
  3782. * function explicit(serviceA) {};
  3783. * explicit.$inject = ['serviceA'];
  3784. * $injector.invoke(explicit);
  3785. *
  3786. * // inline
  3787. * $injector.invoke(['serviceA', function(serviceA){}]);
  3788. * ```
  3789. *
  3790. * ## Inference
  3791. *
  3792. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3793. * can then be parsed and the function arguments can be extracted. This method of discovering
  3794. * annotations is disallowed when the injector is in strict mode.
  3795. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3796. * argument names.
  3797. *
  3798. * ## `$inject` Annotation
  3799. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3800. *
  3801. * ## Inline
  3802. * As an array of injection names, where the last item in the array is the function to call.
  3803. */
  3804. /**
  3805. * @ngdoc property
  3806. * @name $injector#modules
  3807. * @type {Object}
  3808. * @description
  3809. * A hash containing all the modules that have been loaded into the
  3810. * $injector.
  3811. *
  3812. * You can use this property to find out information about a module via the
  3813. * {@link angular.Module#info `myModule.info(...)`} method.
  3814. *
  3815. * For example:
  3816. *
  3817. * ```
  3818. * var info = $injector.modules['ngAnimate'].info();
  3819. * ```
  3820. *
  3821. * **Do not use this property to attempt to modify the modules after the application
  3822. * has been bootstrapped.**
  3823. */
  3824. /**
  3825. * @ngdoc method
  3826. * @name $injector#get
  3827. *
  3828. * @description
  3829. * Return an instance of the service.
  3830. *
  3831. * @param {string} name The name of the instance to retrieve.
  3832. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3833. * @return {*} The instance.
  3834. */
  3835. /**
  3836. * @ngdoc method
  3837. * @name $injector#invoke
  3838. *
  3839. * @description
  3840. * Invoke the method and supply the method arguments from the `$injector`.
  3841. *
  3842. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3843. * injected according to the {@link guide/di $inject Annotation} rules.
  3844. * @param {Object=} self The `this` for the invoked method.
  3845. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3846. * object first, before the `$injector` is consulted.
  3847. * @returns {*} the value returned by the invoked `fn` function.
  3848. */
  3849. /**
  3850. * @ngdoc method
  3851. * @name $injector#has
  3852. *
  3853. * @description
  3854. * Allows the user to query if the particular service exists.
  3855. *
  3856. * @param {string} name Name of the service to query.
  3857. * @returns {boolean} `true` if injector has given service.
  3858. */
  3859. /**
  3860. * @ngdoc method
  3861. * @name $injector#instantiate
  3862. * @description
  3863. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3864. * operator, and supplies all of the arguments to the constructor function as specified by the
  3865. * constructor annotation.
  3866. *
  3867. * @param {Function} Type Annotated constructor function.
  3868. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3869. * object first, before the `$injector` is consulted.
  3870. * @returns {Object} new instance of `Type`.
  3871. */
  3872. /**
  3873. * @ngdoc method
  3874. * @name $injector#annotate
  3875. *
  3876. * @description
  3877. * Returns an array of service names which the function is requesting for injection. This API is
  3878. * used by the injector to determine which services need to be injected into the function when the
  3879. * function is invoked. There are three ways in which the function can be annotated with the needed
  3880. * dependencies.
  3881. *
  3882. * # Argument names
  3883. *
  3884. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3885. * by converting the function into a string using `toString()` method and extracting the argument
  3886. * names.
  3887. * ```js
  3888. * // Given
  3889. * function MyController($scope, $route) {
  3890. * // ...
  3891. * }
  3892. *
  3893. * // Then
  3894. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3895. * ```
  3896. *
  3897. * You can disallow this method by using strict injection mode.
  3898. *
  3899. * This method does not work with code minification / obfuscation. For this reason the following
  3900. * annotation strategies are supported.
  3901. *
  3902. * # The `$inject` property
  3903. *
  3904. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3905. * represent names of services to be injected into the function.
  3906. * ```js
  3907. * // Given
  3908. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3909. * // ...
  3910. * }
  3911. * // Define function dependencies
  3912. * MyController['$inject'] = ['$scope', '$route'];
  3913. *
  3914. * // Then
  3915. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3916. * ```
  3917. *
  3918. * # The array notation
  3919. *
  3920. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3921. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3922. * a way that survives minification is a better choice:
  3923. *
  3924. * ```js
  3925. * // We wish to write this (not minification / obfuscation safe)
  3926. * injector.invoke(function($compile, $rootScope) {
  3927. * // ...
  3928. * });
  3929. *
  3930. * // We are forced to write break inlining
  3931. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3932. * // ...
  3933. * };
  3934. * tmpFn.$inject = ['$compile', '$rootScope'];
  3935. * injector.invoke(tmpFn);
  3936. *
  3937. * // To better support inline function the inline annotation is supported
  3938. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3939. * // ...
  3940. * }]);
  3941. *
  3942. * // Therefore
  3943. * expect(injector.annotate(
  3944. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3945. * ).toEqual(['$compile', '$rootScope']);
  3946. * ```
  3947. *
  3948. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3949. * be retrieved as described above.
  3950. *
  3951. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3952. *
  3953. * @returns {Array.<string>} The names of the services which the function requires.
  3954. */
  3955. /**
  3956. * @ngdoc service
  3957. * @name $provide
  3958. *
  3959. * @description
  3960. *
  3961. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3962. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3963. * {@link angular.Module}.
  3964. *
  3965. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3966. * factories** are functions which, in turn, are created by a **service provider**.
  3967. * The **service providers** are constructor functions. When instantiated they must contain a
  3968. * property called `$get`, which holds the **service factory** function.
  3969. *
  3970. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3971. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3972. * function to get the instance of the **service**.
  3973. *
  3974. * Often services have no configuration options and there is no need to add methods to the service
  3975. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3976. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3977. * services without specifying a provider.
  3978. *
  3979. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  3980. * {@link auto.$injector $injector}
  3981. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  3982. * providers and services.
  3983. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  3984. * services, not providers.
  3985. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  3986. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3987. * given factory function.
  3988. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  3989. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3990. * a new object using the given constructor function.
  3991. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  3992. * will be able to modify or replace the implementation of another service.
  3993. *
  3994. * See the individual methods for more information and examples.
  3995. */
  3996. /**
  3997. * @ngdoc method
  3998. * @name $provide#provider
  3999. * @description
  4000. *
  4001. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  4002. * are constructor functions, whose instances are responsible for "providing" a factory for a
  4003. * service.
  4004. *
  4005. * Service provider names start with the name of the service they provide followed by `Provider`.
  4006. * For example, the {@link ng.$log $log} service has a provider called
  4007. * {@link ng.$logProvider $logProvider}.
  4008. *
  4009. * Service provider objects can have additional methods which allow configuration of the provider
  4010. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  4011. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  4012. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  4013. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  4014. * console or not.
  4015. *
  4016. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  4017. 'Provider'` key.
  4018. * @param {(Object|function())} provider If the provider is:
  4019. *
  4020. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  4021. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  4022. * - `Constructor`: a new instance of the provider will be created using
  4023. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  4024. *
  4025. * @returns {Object} registered provider instance
  4026. * @example
  4027. *
  4028. * The following example shows how to create a simple event tracking service and register it using
  4029. * {@link auto.$provide#provider $provide.provider()}.
  4030. *
  4031. * ```js
  4032. * // Define the eventTracker provider
  4033. * function EventTrackerProvider() {
  4034. * var trackingUrl = '/track';
  4035. *
  4036. * // A provider method for configuring where the tracked events should been saved
  4037. * this.setTrackingUrl = function(url) {
  4038. * trackingUrl = url;
  4039. * };
  4040. *
  4041. * // The service factory function
  4042. * this.$get = ['$http', function($http) {
  4043. * var trackedEvents = {};
  4044. * return {
  4045. * // Call this to track an event
  4046. * event: function(event) {
  4047. * var count = trackedEvents[event] || 0;
  4048. * count += 1;
  4049. * trackedEvents[event] = count;
  4050. * return count;
  4051. * },
  4052. * // Call this to save the tracked events to the trackingUrl
  4053. * save: function() {
  4054. * $http.post(trackingUrl, trackedEvents);
  4055. * }
  4056. * };
  4057. * }];
  4058. * }
  4059. *
  4060. * describe('eventTracker', function() {
  4061. * var postSpy;
  4062. *
  4063. * beforeEach(module(function($provide) {
  4064. * // Register the eventTracker provider
  4065. * $provide.provider('eventTracker', EventTrackerProvider);
  4066. * }));
  4067. *
  4068. * beforeEach(module(function(eventTrackerProvider) {
  4069. * // Configure eventTracker provider
  4070. * eventTrackerProvider.setTrackingUrl('/custom-track');
  4071. * }));
  4072. *
  4073. * it('tracks events', inject(function(eventTracker) {
  4074. * expect(eventTracker.event('login')).toEqual(1);
  4075. * expect(eventTracker.event('login')).toEqual(2);
  4076. * }));
  4077. *
  4078. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  4079. * postSpy = spyOn($http, 'post');
  4080. * eventTracker.event('login');
  4081. * eventTracker.save();
  4082. * expect(postSpy).toHaveBeenCalled();
  4083. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  4084. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  4085. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  4086. * }));
  4087. * });
  4088. * ```
  4089. */
  4090. /**
  4091. * @ngdoc method
  4092. * @name $provide#factory
  4093. * @description
  4094. *
  4095. * Register a **service factory**, which will be called to return the service instance.
  4096. * This is short for registering a service where its provider consists of only a `$get` property,
  4097. * which is the given service factory function.
  4098. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  4099. * configure your service in a provider.
  4100. *
  4101. * @param {string} name The name of the instance.
  4102. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  4103. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  4104. * @returns {Object} registered provider instance
  4105. *
  4106. * @example
  4107. * Here is an example of registering a service
  4108. * ```js
  4109. * $provide.factory('ping', ['$http', function($http) {
  4110. * return function ping() {
  4111. * return $http.send('/ping');
  4112. * };
  4113. * }]);
  4114. * ```
  4115. * You would then inject and use this service like this:
  4116. * ```js
  4117. * someModule.controller('Ctrl', ['ping', function(ping) {
  4118. * ping();
  4119. * }]);
  4120. * ```
  4121. */
  4122. /**
  4123. * @ngdoc method
  4124. * @name $provide#service
  4125. * @description
  4126. *
  4127. * Register a **service constructor**, which will be invoked with `new` to create the service
  4128. * instance.
  4129. * This is short for registering a service where its provider's `$get` property is a factory
  4130. * function that returns an instance instantiated by the injector from the service constructor
  4131. * function.
  4132. *
  4133. * Internally it looks a bit like this:
  4134. *
  4135. * ```
  4136. * {
  4137. * $get: function() {
  4138. * return $injector.instantiate(constructor);
  4139. * }
  4140. * }
  4141. * ```
  4142. *
  4143. *
  4144. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  4145. * as a type/class.
  4146. *
  4147. * @param {string} name The name of the instance.
  4148. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  4149. * that will be instantiated.
  4150. * @returns {Object} registered provider instance
  4151. *
  4152. * @example
  4153. * Here is an example of registering a service using
  4154. * {@link auto.$provide#service $provide.service(class)}.
  4155. * ```js
  4156. * var Ping = function($http) {
  4157. * this.$http = $http;
  4158. * };
  4159. *
  4160. * Ping.$inject = ['$http'];
  4161. *
  4162. * Ping.prototype.send = function() {
  4163. * return this.$http.get('/ping');
  4164. * };
  4165. * $provide.service('ping', Ping);
  4166. * ```
  4167. * You would then inject and use this service like this:
  4168. * ```js
  4169. * someModule.controller('Ctrl', ['ping', function(ping) {
  4170. * ping.send();
  4171. * }]);
  4172. * ```
  4173. */
  4174. /**
  4175. * @ngdoc method
  4176. * @name $provide#value
  4177. * @description
  4178. *
  4179. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  4180. * number, an array, an object or a function. This is short for registering a service where its
  4181. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  4182. * service**. That also means it is not possible to inject other services into a value service.
  4183. *
  4184. * Value services are similar to constant services, except that they cannot be injected into a
  4185. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  4186. * an Angular {@link auto.$provide#decorator decorator}.
  4187. *
  4188. * @param {string} name The name of the instance.
  4189. * @param {*} value The value.
  4190. * @returns {Object} registered provider instance
  4191. *
  4192. * @example
  4193. * Here are some examples of creating value services.
  4194. * ```js
  4195. * $provide.value('ADMIN_USER', 'admin');
  4196. *
  4197. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  4198. *
  4199. * $provide.value('halfOf', function(value) {
  4200. * return value / 2;
  4201. * });
  4202. * ```
  4203. */
  4204. /**
  4205. * @ngdoc method
  4206. * @name $provide#constant
  4207. * @description
  4208. *
  4209. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  4210. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  4211. * possible to inject other services into a constant.
  4212. *
  4213. * But unlike {@link auto.$provide#value value}, a constant can be
  4214. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  4215. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  4216. *
  4217. * @param {string} name The name of the constant.
  4218. * @param {*} value The constant value.
  4219. * @returns {Object} registered instance
  4220. *
  4221. * @example
  4222. * Here a some examples of creating constants:
  4223. * ```js
  4224. * $provide.constant('SHARD_HEIGHT', 306);
  4225. *
  4226. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4227. *
  4228. * $provide.constant('double', function(value) {
  4229. * return value * 2;
  4230. * });
  4231. * ```
  4232. */
  4233. /**
  4234. * @ngdoc method
  4235. * @name $provide#decorator
  4236. * @description
  4237. *
  4238. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  4239. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  4240. * service. The return value of the decorator function may be the original service, or a new service
  4241. * that replaces (or wraps and delegates to) the original service.
  4242. *
  4243. * You can find out more about using decorators in the {@link guide/decorators} guide.
  4244. *
  4245. * @param {string} name The name of the service to decorate.
  4246. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  4247. * provided and should return the decorated service instance. The function is called using
  4248. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4249. * Local injection arguments:
  4250. *
  4251. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4252. * decorated or delegated to.
  4253. *
  4254. * @example
  4255. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4256. * calls to {@link ng.$log#error $log.warn()}.
  4257. * ```js
  4258. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4259. * $delegate.warn = $delegate.error;
  4260. * return $delegate;
  4261. * }]);
  4262. * ```
  4263. */
  4264. function createInjector(modulesToLoad, strictDi) {
  4265. strictDi = (strictDi === true);
  4266. var INSTANTIATING = {},
  4267. providerSuffix = 'Provider',
  4268. path = [],
  4269. loadedModules = new NgMap(),
  4270. providerCache = {
  4271. $provide: {
  4272. provider: supportObject(provider),
  4273. factory: supportObject(factory),
  4274. service: supportObject(service),
  4275. value: supportObject(value),
  4276. constant: supportObject(constant),
  4277. decorator: decorator
  4278. }
  4279. },
  4280. providerInjector = (providerCache.$injector =
  4281. createInternalInjector(providerCache, function(serviceName, caller) {
  4282. if (angular.isString(caller)) {
  4283. path.push(caller);
  4284. }
  4285. throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
  4286. })),
  4287. instanceCache = {},
  4288. protoInstanceInjector =
  4289. createInternalInjector(instanceCache, function(serviceName, caller) {
  4290. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4291. return instanceInjector.invoke(
  4292. provider.$get, provider, undefined, serviceName);
  4293. }),
  4294. instanceInjector = protoInstanceInjector;
  4295. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4296. instanceInjector.modules = providerInjector.modules = createMap();
  4297. var runBlocks = loadModules(modulesToLoad);
  4298. instanceInjector = protoInstanceInjector.get('$injector');
  4299. instanceInjector.strictDi = strictDi;
  4300. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4301. return instanceInjector;
  4302. ////////////////////////////////////
  4303. // $provider
  4304. ////////////////////////////////////
  4305. function supportObject(delegate) {
  4306. return function(key, value) {
  4307. if (isObject(key)) {
  4308. forEach(key, reverseParams(delegate));
  4309. } else {
  4310. return delegate(key, value);
  4311. }
  4312. };
  4313. }
  4314. function provider(name, provider_) {
  4315. assertNotHasOwnProperty(name, 'service');
  4316. if (isFunction(provider_) || isArray(provider_)) {
  4317. provider_ = providerInjector.instantiate(provider_);
  4318. }
  4319. if (!provider_.$get) {
  4320. throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
  4321. }
  4322. return (providerCache[name + providerSuffix] = provider_);
  4323. }
  4324. function enforceReturnValue(name, factory) {
  4325. return /** @this */ function enforcedReturnValue() {
  4326. var result = instanceInjector.invoke(factory, this);
  4327. if (isUndefined(result)) {
  4328. throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
  4329. }
  4330. return result;
  4331. };
  4332. }
  4333. function factory(name, factoryFn, enforce) {
  4334. return provider(name, {
  4335. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4336. });
  4337. }
  4338. function service(name, constructor) {
  4339. return factory(name, ['$injector', function($injector) {
  4340. return $injector.instantiate(constructor);
  4341. }]);
  4342. }
  4343. function value(name, val) { return factory(name, valueFn(val), false); }
  4344. function constant(name, value) {
  4345. assertNotHasOwnProperty(name, 'constant');
  4346. providerCache[name] = value;
  4347. instanceCache[name] = value;
  4348. }
  4349. function decorator(serviceName, decorFn) {
  4350. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4351. orig$get = origProvider.$get;
  4352. origProvider.$get = function() {
  4353. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4354. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4355. };
  4356. }
  4357. ////////////////////////////////////
  4358. // Module Loading
  4359. ////////////////////////////////////
  4360. function loadModules(modulesToLoad) {
  4361. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4362. var runBlocks = [], moduleFn;
  4363. forEach(modulesToLoad, function(module) {
  4364. if (loadedModules.get(module)) return;
  4365. loadedModules.set(module, true);
  4366. function runInvokeQueue(queue) {
  4367. var i, ii;
  4368. for (i = 0, ii = queue.length; i < ii; i++) {
  4369. var invokeArgs = queue[i],
  4370. provider = providerInjector.get(invokeArgs[0]);
  4371. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4372. }
  4373. }
  4374. try {
  4375. if (isString(module)) {
  4376. moduleFn = angularModule(module);
  4377. instanceInjector.modules[module] = moduleFn;
  4378. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4379. runInvokeQueue(moduleFn._invokeQueue);
  4380. runInvokeQueue(moduleFn._configBlocks);
  4381. } else if (isFunction(module)) {
  4382. runBlocks.push(providerInjector.invoke(module));
  4383. } else if (isArray(module)) {
  4384. runBlocks.push(providerInjector.invoke(module));
  4385. } else {
  4386. assertArgFn(module, 'module');
  4387. }
  4388. } catch (e) {
  4389. if (isArray(module)) {
  4390. module = module[module.length - 1];
  4391. }
  4392. if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
  4393. // Safari & FF's stack traces don't contain error.message content
  4394. // unlike those of Chrome and IE
  4395. // So if stack doesn't contain message, we create a new string that contains both.
  4396. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4397. // eslint-disable-next-line no-ex-assign
  4398. e = e.message + '\n' + e.stack;
  4399. }
  4400. throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
  4401. module, e.stack || e.message || e);
  4402. }
  4403. });
  4404. return runBlocks;
  4405. }
  4406. ////////////////////////////////////
  4407. // internal Injector
  4408. ////////////////////////////////////
  4409. function createInternalInjector(cache, factory) {
  4410. function getService(serviceName, caller) {
  4411. if (cache.hasOwnProperty(serviceName)) {
  4412. if (cache[serviceName] === INSTANTIATING) {
  4413. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4414. serviceName + ' <- ' + path.join(' <- '));
  4415. }
  4416. return cache[serviceName];
  4417. } else {
  4418. try {
  4419. path.unshift(serviceName);
  4420. cache[serviceName] = INSTANTIATING;
  4421. cache[serviceName] = factory(serviceName, caller);
  4422. return cache[serviceName];
  4423. } catch (err) {
  4424. if (cache[serviceName] === INSTANTIATING) {
  4425. delete cache[serviceName];
  4426. }
  4427. throw err;
  4428. } finally {
  4429. path.shift();
  4430. }
  4431. }
  4432. }
  4433. function injectionArgs(fn, locals, serviceName) {
  4434. var args = [],
  4435. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4436. for (var i = 0, length = $inject.length; i < length; i++) {
  4437. var key = $inject[i];
  4438. if (typeof key !== 'string') {
  4439. throw $injectorMinErr('itkn',
  4440. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4441. }
  4442. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4443. getService(key, serviceName));
  4444. }
  4445. return args;
  4446. }
  4447. function isClass(func) {
  4448. // Support: IE 9-11 only
  4449. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4450. if (msie || typeof func !== 'function') {
  4451. return false;
  4452. }
  4453. var result = func.$$ngIsClass;
  4454. if (!isBoolean(result)) {
  4455. // Support: Edge 12-13 only
  4456. // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
  4457. result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func));
  4458. }
  4459. return result;
  4460. }
  4461. function invoke(fn, self, locals, serviceName) {
  4462. if (typeof locals === 'string') {
  4463. serviceName = locals;
  4464. locals = null;
  4465. }
  4466. var args = injectionArgs(fn, locals, serviceName);
  4467. if (isArray(fn)) {
  4468. fn = fn[fn.length - 1];
  4469. }
  4470. if (!isClass(fn)) {
  4471. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4472. // #5388
  4473. return fn.apply(self, args);
  4474. } else {
  4475. args.unshift(null);
  4476. return new (Function.prototype.bind.apply(fn, args))();
  4477. }
  4478. }
  4479. function instantiate(Type, locals, serviceName) {
  4480. // Check if Type is annotated and use just the given function at n-1 as parameter
  4481. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4482. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4483. var args = injectionArgs(Type, locals, serviceName);
  4484. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4485. args.unshift(null);
  4486. return new (Function.prototype.bind.apply(ctor, args))();
  4487. }
  4488. return {
  4489. invoke: invoke,
  4490. instantiate: instantiate,
  4491. get: getService,
  4492. annotate: createInjector.$$annotate,
  4493. has: function(name) {
  4494. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4495. }
  4496. };
  4497. }
  4498. }
  4499. createInjector.$$annotate = annotate;
  4500. /**
  4501. * @ngdoc provider
  4502. * @name $anchorScrollProvider
  4503. * @this
  4504. *
  4505. * @description
  4506. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4507. * {@link ng.$location#hash $location.hash()} changes.
  4508. */
  4509. function $AnchorScrollProvider() {
  4510. var autoScrollingEnabled = true;
  4511. /**
  4512. * @ngdoc method
  4513. * @name $anchorScrollProvider#disableAutoScrolling
  4514. *
  4515. * @description
  4516. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4517. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4518. * Use this method to disable automatic scrolling.
  4519. *
  4520. * If automatic scrolling is disabled, one must explicitly call
  4521. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4522. * current hash.
  4523. */
  4524. this.disableAutoScrolling = function() {
  4525. autoScrollingEnabled = false;
  4526. };
  4527. /**
  4528. * @ngdoc service
  4529. * @name $anchorScroll
  4530. * @kind function
  4531. * @requires $window
  4532. * @requires $location
  4533. * @requires $rootScope
  4534. *
  4535. * @description
  4536. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4537. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4538. * in the
  4539. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4540. *
  4541. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4542. * match any anchor whenever it changes. This can be disabled by calling
  4543. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4544. *
  4545. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4546. * vertical scroll-offset (either fixed or dynamic).
  4547. *
  4548. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4549. * {@link ng.$location#hash $location.hash()} will be used.
  4550. *
  4551. * @property {(number|function|jqLite)} yOffset
  4552. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4553. * positioned elements at the top of the page, such as navbars, headers etc.
  4554. *
  4555. * `yOffset` can be specified in various ways:
  4556. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4557. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4558. * a number representing the offset (in pixels).<br /><br />
  4559. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4560. * the top of the page to the element's bottom will be used as offset.<br />
  4561. * **Note**: The element will be taken into account only as long as its `position` is set to
  4562. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4563. * their height and/or positioning according to the viewport's size.
  4564. *
  4565. * <br />
  4566. * <div class="alert alert-warning">
  4567. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4568. * not some child element.
  4569. * </div>
  4570. *
  4571. * @example
  4572. <example module="anchorScrollExample" name="anchor-scroll">
  4573. <file name="index.html">
  4574. <div id="scrollArea" ng-controller="ScrollController">
  4575. <a ng-click="gotoBottom()">Go to bottom</a>
  4576. <a id="bottom"></a> You're at the bottom!
  4577. </div>
  4578. </file>
  4579. <file name="script.js">
  4580. angular.module('anchorScrollExample', [])
  4581. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4582. function($scope, $location, $anchorScroll) {
  4583. $scope.gotoBottom = function() {
  4584. // set the location.hash to the id of
  4585. // the element you wish to scroll to.
  4586. $location.hash('bottom');
  4587. // call $anchorScroll()
  4588. $anchorScroll();
  4589. };
  4590. }]);
  4591. </file>
  4592. <file name="style.css">
  4593. #scrollArea {
  4594. height: 280px;
  4595. overflow: auto;
  4596. }
  4597. #bottom {
  4598. display: block;
  4599. margin-top: 2000px;
  4600. }
  4601. </file>
  4602. </example>
  4603. *
  4604. * <hr />
  4605. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4606. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4607. *
  4608. * @example
  4609. <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
  4610. <file name="index.html">
  4611. <div class="fixed-header" ng-controller="headerCtrl">
  4612. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4613. Go to anchor {{x}}
  4614. </a>
  4615. </div>
  4616. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4617. Anchor {{x}} of 5
  4618. </div>
  4619. </file>
  4620. <file name="script.js">
  4621. angular.module('anchorScrollOffsetExample', [])
  4622. .run(['$anchorScroll', function($anchorScroll) {
  4623. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4624. }])
  4625. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4626. function($anchorScroll, $location, $scope) {
  4627. $scope.gotoAnchor = function(x) {
  4628. var newHash = 'anchor' + x;
  4629. if ($location.hash() !== newHash) {
  4630. // set the $location.hash to `newHash` and
  4631. // $anchorScroll will automatically scroll to it
  4632. $location.hash('anchor' + x);
  4633. } else {
  4634. // call $anchorScroll() explicitly,
  4635. // since $location.hash hasn't changed
  4636. $anchorScroll();
  4637. }
  4638. };
  4639. }
  4640. ]);
  4641. </file>
  4642. <file name="style.css">
  4643. body {
  4644. padding-top: 50px;
  4645. }
  4646. .anchor {
  4647. border: 2px dashed DarkOrchid;
  4648. padding: 10px 10px 200px 10px;
  4649. }
  4650. .fixed-header {
  4651. background-color: rgba(0, 0, 0, 0.2);
  4652. height: 50px;
  4653. position: fixed;
  4654. top: 0; left: 0; right: 0;
  4655. }
  4656. .fixed-header > a {
  4657. display: inline-block;
  4658. margin: 5px 15px;
  4659. }
  4660. </file>
  4661. </example>
  4662. */
  4663. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4664. var document = $window.document;
  4665. // Helper function to get first anchor from a NodeList
  4666. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4667. // and working in all supported browsers.)
  4668. function getFirstAnchor(list) {
  4669. var result = null;
  4670. Array.prototype.some.call(list, function(element) {
  4671. if (nodeName_(element) === 'a') {
  4672. result = element;
  4673. return true;
  4674. }
  4675. });
  4676. return result;
  4677. }
  4678. function getYOffset() {
  4679. var offset = scroll.yOffset;
  4680. if (isFunction(offset)) {
  4681. offset = offset();
  4682. } else if (isElement(offset)) {
  4683. var elem = offset[0];
  4684. var style = $window.getComputedStyle(elem);
  4685. if (style.position !== 'fixed') {
  4686. offset = 0;
  4687. } else {
  4688. offset = elem.getBoundingClientRect().bottom;
  4689. }
  4690. } else if (!isNumber(offset)) {
  4691. offset = 0;
  4692. }
  4693. return offset;
  4694. }
  4695. function scrollTo(elem) {
  4696. if (elem) {
  4697. elem.scrollIntoView();
  4698. var offset = getYOffset();
  4699. if (offset) {
  4700. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4701. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4702. // top of the viewport.
  4703. //
  4704. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4705. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4706. // way down the page.
  4707. //
  4708. // This is often the case for elements near the bottom of the page.
  4709. //
  4710. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4711. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4712. // desired position.
  4713. var elemTop = elem.getBoundingClientRect().top;
  4714. $window.scrollBy(0, elemTop - offset);
  4715. }
  4716. } else {
  4717. $window.scrollTo(0, 0);
  4718. }
  4719. }
  4720. function scroll(hash) {
  4721. // Allow numeric hashes
  4722. hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
  4723. var elm;
  4724. // empty hash, scroll to the top of the page
  4725. if (!hash) scrollTo(null);
  4726. // element with given id
  4727. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4728. // first anchor with given name :-D
  4729. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4730. // no element and hash === 'top', scroll to the top of the page
  4731. else if (hash === 'top') scrollTo(null);
  4732. }
  4733. // does not scroll when user clicks on anchor link that is currently on
  4734. // (no url change, no $location.hash() change), browser native does scroll
  4735. if (autoScrollingEnabled) {
  4736. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4737. function autoScrollWatchAction(newVal, oldVal) {
  4738. // skip the initial scroll if $location.hash is empty
  4739. if (newVal === oldVal && newVal === '') return;
  4740. jqLiteDocumentLoaded(function() {
  4741. $rootScope.$evalAsync(scroll);
  4742. });
  4743. });
  4744. }
  4745. return scroll;
  4746. }];
  4747. }
  4748. var $animateMinErr = minErr('$animate');
  4749. var ELEMENT_NODE = 1;
  4750. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4751. function mergeClasses(a,b) {
  4752. if (!a && !b) return '';
  4753. if (!a) return b;
  4754. if (!b) return a;
  4755. if (isArray(a)) a = a.join(' ');
  4756. if (isArray(b)) b = b.join(' ');
  4757. return a + ' ' + b;
  4758. }
  4759. function extractElementNode(element) {
  4760. for (var i = 0; i < element.length; i++) {
  4761. var elm = element[i];
  4762. if (elm.nodeType === ELEMENT_NODE) {
  4763. return elm;
  4764. }
  4765. }
  4766. }
  4767. function splitClasses(classes) {
  4768. if (isString(classes)) {
  4769. classes = classes.split(' ');
  4770. }
  4771. // Use createMap() to prevent class assumptions involving property names in
  4772. // Object.prototype
  4773. var obj = createMap();
  4774. forEach(classes, function(klass) {
  4775. // sometimes the split leaves empty string values
  4776. // incase extra spaces were applied to the options
  4777. if (klass.length) {
  4778. obj[klass] = true;
  4779. }
  4780. });
  4781. return obj;
  4782. }
  4783. // if any other type of options value besides an Object value is
  4784. // passed into the $animate.method() animation then this helper code
  4785. // will be run which will ignore it. While this patch is not the
  4786. // greatest solution to this, a lot of existing plugins depend on
  4787. // $animate to either call the callback (< 1.2) or return a promise
  4788. // that can be changed. This helper function ensures that the options
  4789. // are wiped clean incase a callback function is provided.
  4790. function prepareAnimateOptions(options) {
  4791. return isObject(options)
  4792. ? options
  4793. : {};
  4794. }
  4795. var $$CoreAnimateJsProvider = /** @this */ function() {
  4796. this.$get = noop;
  4797. };
  4798. // this is prefixed with Core since it conflicts with
  4799. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4800. var $$CoreAnimateQueueProvider = /** @this */ function() {
  4801. var postDigestQueue = new NgMap();
  4802. var postDigestElements = [];
  4803. this.$get = ['$$AnimateRunner', '$rootScope',
  4804. function($$AnimateRunner, $rootScope) {
  4805. return {
  4806. enabled: noop,
  4807. on: noop,
  4808. off: noop,
  4809. pin: noop,
  4810. push: function(element, event, options, domOperation) {
  4811. if (domOperation) {
  4812. domOperation();
  4813. }
  4814. options = options || {};
  4815. if (options.from) {
  4816. element.css(options.from);
  4817. }
  4818. if (options.to) {
  4819. element.css(options.to);
  4820. }
  4821. if (options.addClass || options.removeClass) {
  4822. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4823. }
  4824. var runner = new $$AnimateRunner();
  4825. // since there are no animations to run the runner needs to be
  4826. // notified that the animation call is complete.
  4827. runner.complete();
  4828. return runner;
  4829. }
  4830. };
  4831. function updateData(data, classes, value) {
  4832. var changed = false;
  4833. if (classes) {
  4834. classes = isString(classes) ? classes.split(' ') :
  4835. isArray(classes) ? classes : [];
  4836. forEach(classes, function(className) {
  4837. if (className) {
  4838. changed = true;
  4839. data[className] = value;
  4840. }
  4841. });
  4842. }
  4843. return changed;
  4844. }
  4845. function handleCSSClassChanges() {
  4846. forEach(postDigestElements, function(element) {
  4847. var data = postDigestQueue.get(element);
  4848. if (data) {
  4849. var existing = splitClasses(element.attr('class'));
  4850. var toAdd = '';
  4851. var toRemove = '';
  4852. forEach(data, function(status, className) {
  4853. var hasClass = !!existing[className];
  4854. if (status !== hasClass) {
  4855. if (status) {
  4856. toAdd += (toAdd.length ? ' ' : '') + className;
  4857. } else {
  4858. toRemove += (toRemove.length ? ' ' : '') + className;
  4859. }
  4860. }
  4861. });
  4862. forEach(element, function(elm) {
  4863. if (toAdd) {
  4864. jqLiteAddClass(elm, toAdd);
  4865. }
  4866. if (toRemove) {
  4867. jqLiteRemoveClass(elm, toRemove);
  4868. }
  4869. });
  4870. postDigestQueue.delete(element);
  4871. }
  4872. });
  4873. postDigestElements.length = 0;
  4874. }
  4875. function addRemoveClassesPostDigest(element, add, remove) {
  4876. var data = postDigestQueue.get(element) || {};
  4877. var classesAdded = updateData(data, add, true);
  4878. var classesRemoved = updateData(data, remove, false);
  4879. if (classesAdded || classesRemoved) {
  4880. postDigestQueue.set(element, data);
  4881. postDigestElements.push(element);
  4882. if (postDigestElements.length === 1) {
  4883. $rootScope.$$postDigest(handleCSSClassChanges);
  4884. }
  4885. }
  4886. }
  4887. }];
  4888. };
  4889. /**
  4890. * @ngdoc provider
  4891. * @name $animateProvider
  4892. *
  4893. * @description
  4894. * Default implementation of $animate that doesn't perform any animations, instead just
  4895. * synchronously performs DOM updates and resolves the returned runner promise.
  4896. *
  4897. * In order to enable animations the `ngAnimate` module has to be loaded.
  4898. *
  4899. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4900. */
  4901. var $AnimateProvider = ['$provide', /** @this */ function($provide) {
  4902. var provider = this;
  4903. var classNameFilter = null;
  4904. this.$$registeredAnimations = Object.create(null);
  4905. /**
  4906. * @ngdoc method
  4907. * @name $animateProvider#register
  4908. *
  4909. * @description
  4910. * Registers a new injectable animation factory function. The factory function produces the
  4911. * animation object which contains callback functions for each event that is expected to be
  4912. * animated.
  4913. *
  4914. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4915. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4916. * on the type of animation additional arguments will be injected into the animation function. The
  4917. * list below explains the function signatures for the different animation methods:
  4918. *
  4919. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4920. * - addClass: function(element, addedClasses, doneFunction, options)
  4921. * - removeClass: function(element, removedClasses, doneFunction, options)
  4922. * - enter, leave, move: function(element, doneFunction, options)
  4923. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4924. *
  4925. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4926. *
  4927. * ```js
  4928. * return {
  4929. * //enter, leave, move signature
  4930. * eventFn : function(element, done, options) {
  4931. * //code to run the animation
  4932. * //once complete, then run done()
  4933. * return function endFunction(wasCancelled) {
  4934. * //code to cancel the animation
  4935. * }
  4936. * }
  4937. * }
  4938. * ```
  4939. *
  4940. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4941. * @param {Function} factory The factory function that will be executed to return the animation
  4942. * object.
  4943. */
  4944. this.register = function(name, factory) {
  4945. if (name && name.charAt(0) !== '.') {
  4946. throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
  4947. }
  4948. var key = name + '-animation';
  4949. provider.$$registeredAnimations[name.substr(1)] = key;
  4950. $provide.factory(key, factory);
  4951. };
  4952. /**
  4953. * @ngdoc method
  4954. * @name $animateProvider#classNameFilter
  4955. *
  4956. * @description
  4957. * Sets and/or returns the CSS class regular expression that is checked when performing
  4958. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4959. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4960. * When setting the `classNameFilter` value, animations will only be performed on elements
  4961. * that successfully match the filter expression. This in turn can boost performance
  4962. * for low-powered devices as well as applications containing a lot of structural operations.
  4963. * @param {RegExp=} expression The className expression which will be checked against all animations
  4964. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4965. */
  4966. this.classNameFilter = function(expression) {
  4967. if (arguments.length === 1) {
  4968. classNameFilter = (expression instanceof RegExp) ? expression : null;
  4969. if (classNameFilter) {
  4970. var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]');
  4971. if (reservedRegex.test(classNameFilter.toString())) {
  4972. classNameFilter = null;
  4973. throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4974. }
  4975. }
  4976. }
  4977. return classNameFilter;
  4978. };
  4979. this.$get = ['$$animateQueue', function($$animateQueue) {
  4980. function domInsert(element, parentElement, afterElement) {
  4981. // if for some reason the previous element was removed
  4982. // from the dom sometime before this code runs then let's
  4983. // just stick to using the parent element as the anchor
  4984. if (afterElement) {
  4985. var afterNode = extractElementNode(afterElement);
  4986. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4987. afterElement = null;
  4988. }
  4989. }
  4990. if (afterElement) {
  4991. afterElement.after(element);
  4992. } else {
  4993. parentElement.prepend(element);
  4994. }
  4995. }
  4996. /**
  4997. * @ngdoc service
  4998. * @name $animate
  4999. * @description The $animate service exposes a series of DOM utility methods that provide support
  5000. * for animation hooks. The default behavior is the application of DOM operations, however,
  5001. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  5002. * to ensure that animation runs with the triggered DOM operation.
  5003. *
  5004. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  5005. * included and only when it is active then the animation hooks that `$animate` triggers will be
  5006. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  5007. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  5008. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  5009. *
  5010. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  5011. *
  5012. * To learn more about enabling animation support, click here to visit the
  5013. * {@link ngAnimate ngAnimate module page}.
  5014. */
  5015. return {
  5016. // we don't call it directly since non-existant arguments may
  5017. // be interpreted as null within the sub enabled function
  5018. /**
  5019. *
  5020. * @ngdoc method
  5021. * @name $animate#on
  5022. * @kind function
  5023. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  5024. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  5025. * is fired with the following params:
  5026. *
  5027. * ```js
  5028. * $animate.on('enter', container,
  5029. * function callback(element, phase) {
  5030. * // cool we detected an enter animation within the container
  5031. * }
  5032. * );
  5033. * ```
  5034. *
  5035. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  5036. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  5037. * as well as among its children
  5038. * @param {Function} callback the callback function that will be fired when the listener is triggered
  5039. *
  5040. * The arguments present in the callback function are:
  5041. * * `element` - The captured DOM element that the animation was fired on.
  5042. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  5043. */
  5044. on: $$animateQueue.on,
  5045. /**
  5046. *
  5047. * @ngdoc method
  5048. * @name $animate#off
  5049. * @kind function
  5050. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  5051. * can be used in three different ways depending on the arguments:
  5052. *
  5053. * ```js
  5054. * // remove all the animation event listeners listening for `enter`
  5055. * $animate.off('enter');
  5056. *
  5057. * // remove listeners for all animation events from the container element
  5058. * $animate.off(container);
  5059. *
  5060. * // remove all the animation event listeners listening for `enter` on the given element and its children
  5061. * $animate.off('enter', container);
  5062. *
  5063. * // remove the event listener function provided by `callback` that is set
  5064. * // to listen for `enter` on the given `container` as well as its children
  5065. * $animate.off('enter', container, callback);
  5066. * ```
  5067. *
  5068. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  5069. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  5070. * arguments are ignored.
  5071. * @param {DOMElement=} container the container element the event listener was placed on
  5072. * @param {Function=} callback the callback function that was registered as the listener
  5073. */
  5074. off: $$animateQueue.off,
  5075. /**
  5076. * @ngdoc method
  5077. * @name $animate#pin
  5078. * @kind function
  5079. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  5080. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  5081. * element despite being outside the realm of the application or within another application. Say for example if the application
  5082. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  5083. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  5084. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  5085. *
  5086. * Note that this feature is only active when the `ngAnimate` module is used.
  5087. *
  5088. * @param {DOMElement} element the external element that will be pinned
  5089. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  5090. */
  5091. pin: $$animateQueue.pin,
  5092. /**
  5093. *
  5094. * @ngdoc method
  5095. * @name $animate#enabled
  5096. * @kind function
  5097. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  5098. * function can be called in four ways:
  5099. *
  5100. * ```js
  5101. * // returns true or false
  5102. * $animate.enabled();
  5103. *
  5104. * // changes the enabled state for all animations
  5105. * $animate.enabled(false);
  5106. * $animate.enabled(true);
  5107. *
  5108. * // returns true or false if animations are enabled for an element
  5109. * $animate.enabled(element);
  5110. *
  5111. * // changes the enabled state for an element and its children
  5112. * $animate.enabled(element, true);
  5113. * $animate.enabled(element, false);
  5114. * ```
  5115. *
  5116. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  5117. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  5118. *
  5119. * @return {boolean} whether or not animations are enabled
  5120. */
  5121. enabled: $$animateQueue.enabled,
  5122. /**
  5123. * @ngdoc method
  5124. * @name $animate#cancel
  5125. * @kind function
  5126. * @description Cancels the provided animation.
  5127. *
  5128. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  5129. */
  5130. cancel: function(runner) {
  5131. if (runner.end) {
  5132. runner.end();
  5133. }
  5134. },
  5135. /**
  5136. *
  5137. * @ngdoc method
  5138. * @name $animate#enter
  5139. * @kind function
  5140. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  5141. * as the first child within the `parent` element and then triggers an animation.
  5142. * A promise is returned that will be resolved during the next digest once the animation
  5143. * has completed.
  5144. *
  5145. * @param {DOMElement} element the element which will be inserted into the DOM
  5146. * @param {DOMElement} parent the parent element which will append the element as
  5147. * a child (so long as the after element is not present)
  5148. * @param {DOMElement=} after the sibling element after which the element will be appended
  5149. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5150. * The object can have the following properties:
  5151. *
  5152. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5153. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5154. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5155. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5156. *
  5157. * @return {Promise} the animation callback promise
  5158. */
  5159. enter: function(element, parent, after, options) {
  5160. parent = parent && jqLite(parent);
  5161. after = after && jqLite(after);
  5162. parent = parent || after.parent();
  5163. domInsert(element, parent, after);
  5164. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  5165. },
  5166. /**
  5167. *
  5168. * @ngdoc method
  5169. * @name $animate#move
  5170. * @kind function
  5171. * @description Inserts (moves) the element into its new position in the DOM either after
  5172. * the `after` element (if provided) or as the first child within the `parent` element
  5173. * and then triggers an animation. A promise is returned that will be resolved
  5174. * during the next digest once the animation has completed.
  5175. *
  5176. * @param {DOMElement} element the element which will be moved into the new DOM position
  5177. * @param {DOMElement} parent the parent element which will append the element as
  5178. * a child (so long as the after element is not present)
  5179. * @param {DOMElement=} after the sibling element after which the element will be appended
  5180. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5181. * The object can have the following properties:
  5182. *
  5183. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5184. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5185. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5186. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5187. *
  5188. * @return {Promise} the animation callback promise
  5189. */
  5190. move: function(element, parent, after, options) {
  5191. parent = parent && jqLite(parent);
  5192. after = after && jqLite(after);
  5193. parent = parent || after.parent();
  5194. domInsert(element, parent, after);
  5195. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  5196. },
  5197. /**
  5198. * @ngdoc method
  5199. * @name $animate#leave
  5200. * @kind function
  5201. * @description Triggers an animation and then removes the element from the DOM.
  5202. * When the function is called a promise is returned that will be resolved during the next
  5203. * digest once the animation has completed.
  5204. *
  5205. * @param {DOMElement} element the element which will be removed from the DOM
  5206. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5207. * The object can have the following properties:
  5208. *
  5209. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5210. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5211. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5212. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5213. *
  5214. * @return {Promise} the animation callback promise
  5215. */
  5216. leave: function(element, options) {
  5217. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  5218. element.remove();
  5219. });
  5220. },
  5221. /**
  5222. * @ngdoc method
  5223. * @name $animate#addClass
  5224. * @kind function
  5225. *
  5226. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  5227. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  5228. * animation if element already contains the CSS class or if the class is removed at a later step.
  5229. * Note that class-based animations are treated differently compared to structural animations
  5230. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5231. * depending if CSS or JavaScript animations are used.
  5232. *
  5233. * @param {DOMElement} element the element which the CSS classes will be applied to
  5234. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  5235. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5236. * The object can have the following properties:
  5237. *
  5238. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5239. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5240. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5241. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5242. *
  5243. * @return {Promise} the animation callback promise
  5244. */
  5245. addClass: function(element, className, options) {
  5246. options = prepareAnimateOptions(options);
  5247. options.addClass = mergeClasses(options.addclass, className);
  5248. return $$animateQueue.push(element, 'addClass', options);
  5249. },
  5250. /**
  5251. * @ngdoc method
  5252. * @name $animate#removeClass
  5253. * @kind function
  5254. *
  5255. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  5256. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  5257. * animation if element does not contain the CSS class or if the class is added at a later step.
  5258. * Note that class-based animations are treated differently compared to structural animations
  5259. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5260. * depending if CSS or JavaScript animations are used.
  5261. *
  5262. * @param {DOMElement} element the element which the CSS classes will be applied to
  5263. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5264. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5265. * The object can have the following properties:
  5266. *
  5267. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5268. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5269. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5270. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5271. *
  5272. * @return {Promise} the animation callback promise
  5273. */
  5274. removeClass: function(element, className, options) {
  5275. options = prepareAnimateOptions(options);
  5276. options.removeClass = mergeClasses(options.removeClass, className);
  5277. return $$animateQueue.push(element, 'removeClass', options);
  5278. },
  5279. /**
  5280. * @ngdoc method
  5281. * @name $animate#setClass
  5282. * @kind function
  5283. *
  5284. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5285. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5286. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5287. * passed. Note that class-based animations are treated differently compared to structural animations
  5288. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5289. * depending if CSS or JavaScript animations are used.
  5290. *
  5291. * @param {DOMElement} element the element which the CSS classes will be applied to
  5292. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5293. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5294. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5295. * The object can have the following properties:
  5296. *
  5297. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5298. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5299. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5300. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5301. *
  5302. * @return {Promise} the animation callback promise
  5303. */
  5304. setClass: function(element, add, remove, options) {
  5305. options = prepareAnimateOptions(options);
  5306. options.addClass = mergeClasses(options.addClass, add);
  5307. options.removeClass = mergeClasses(options.removeClass, remove);
  5308. return $$animateQueue.push(element, 'setClass', options);
  5309. },
  5310. /**
  5311. * @ngdoc method
  5312. * @name $animate#animate
  5313. * @kind function
  5314. *
  5315. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5316. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5317. * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
  5318. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5319. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5320. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5321. * method (or as part of the `options` parameter):
  5322. *
  5323. * ```js
  5324. * ngModule.animation('.my-inline-animation', function() {
  5325. * return {
  5326. * animate : function(element, from, to, done, options) {
  5327. * //animation
  5328. * done();
  5329. * }
  5330. * }
  5331. * });
  5332. * ```
  5333. *
  5334. * @param {DOMElement} element the element which the CSS styles will be applied to
  5335. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5336. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5337. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5338. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5339. * (Note that if no animation is detected then this value will not be applied to the element.)
  5340. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5341. * The object can have the following properties:
  5342. *
  5343. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5344. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5345. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5346. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5347. *
  5348. * @return {Promise} the animation callback promise
  5349. */
  5350. animate: function(element, from, to, className, options) {
  5351. options = prepareAnimateOptions(options);
  5352. options.from = options.from ? extend(options.from, from) : from;
  5353. options.to = options.to ? extend(options.to, to) : to;
  5354. className = className || 'ng-inline-animate';
  5355. options.tempClasses = mergeClasses(options.tempClasses, className);
  5356. return $$animateQueue.push(element, 'animate', options);
  5357. }
  5358. };
  5359. }];
  5360. }];
  5361. var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
  5362. this.$get = ['$$rAF', function($$rAF) {
  5363. var waitQueue = [];
  5364. function waitForTick(fn) {
  5365. waitQueue.push(fn);
  5366. if (waitQueue.length > 1) return;
  5367. $$rAF(function() {
  5368. for (var i = 0; i < waitQueue.length; i++) {
  5369. waitQueue[i]();
  5370. }
  5371. waitQueue = [];
  5372. });
  5373. }
  5374. return function() {
  5375. var passed = false;
  5376. waitForTick(function() {
  5377. passed = true;
  5378. });
  5379. return function(callback) {
  5380. if (passed) {
  5381. callback();
  5382. } else {
  5383. waitForTick(callback);
  5384. }
  5385. };
  5386. };
  5387. }];
  5388. };
  5389. var $$AnimateRunnerFactoryProvider = /** @this */ function() {
  5390. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
  5391. function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
  5392. var INITIAL_STATE = 0;
  5393. var DONE_PENDING_STATE = 1;
  5394. var DONE_COMPLETE_STATE = 2;
  5395. AnimateRunner.chain = function(chain, callback) {
  5396. var index = 0;
  5397. next();
  5398. function next() {
  5399. if (index === chain.length) {
  5400. callback(true);
  5401. return;
  5402. }
  5403. chain[index](function(response) {
  5404. if (response === false) {
  5405. callback(false);
  5406. return;
  5407. }
  5408. index++;
  5409. next();
  5410. });
  5411. }
  5412. };
  5413. AnimateRunner.all = function(runners, callback) {
  5414. var count = 0;
  5415. var status = true;
  5416. forEach(runners, function(runner) {
  5417. runner.done(onProgress);
  5418. });
  5419. function onProgress(response) {
  5420. status = status && response;
  5421. if (++count === runners.length) {
  5422. callback(status);
  5423. }
  5424. }
  5425. };
  5426. function AnimateRunner(host) {
  5427. this.setHost(host);
  5428. var rafTick = $$animateAsyncRun();
  5429. var timeoutTick = function(fn) {
  5430. $timeout(fn, 0, false);
  5431. };
  5432. this._doneCallbacks = [];
  5433. this._tick = function(fn) {
  5434. if ($$isDocumentHidden()) {
  5435. timeoutTick(fn);
  5436. } else {
  5437. rafTick(fn);
  5438. }
  5439. };
  5440. this._state = 0;
  5441. }
  5442. AnimateRunner.prototype = {
  5443. setHost: function(host) {
  5444. this.host = host || {};
  5445. },
  5446. done: function(fn) {
  5447. if (this._state === DONE_COMPLETE_STATE) {
  5448. fn();
  5449. } else {
  5450. this._doneCallbacks.push(fn);
  5451. }
  5452. },
  5453. progress: noop,
  5454. getPromise: function() {
  5455. if (!this.promise) {
  5456. var self = this;
  5457. this.promise = $q(function(resolve, reject) {
  5458. self.done(function(status) {
  5459. if (status === false) {
  5460. reject();
  5461. } else {
  5462. resolve();
  5463. }
  5464. });
  5465. });
  5466. }
  5467. return this.promise;
  5468. },
  5469. then: function(resolveHandler, rejectHandler) {
  5470. return this.getPromise().then(resolveHandler, rejectHandler);
  5471. },
  5472. 'catch': function(handler) {
  5473. return this.getPromise()['catch'](handler);
  5474. },
  5475. 'finally': function(handler) {
  5476. return this.getPromise()['finally'](handler);
  5477. },
  5478. pause: function() {
  5479. if (this.host.pause) {
  5480. this.host.pause();
  5481. }
  5482. },
  5483. resume: function() {
  5484. if (this.host.resume) {
  5485. this.host.resume();
  5486. }
  5487. },
  5488. end: function() {
  5489. if (this.host.end) {
  5490. this.host.end();
  5491. }
  5492. this._resolve(true);
  5493. },
  5494. cancel: function() {
  5495. if (this.host.cancel) {
  5496. this.host.cancel();
  5497. }
  5498. this._resolve(false);
  5499. },
  5500. complete: function(response) {
  5501. var self = this;
  5502. if (self._state === INITIAL_STATE) {
  5503. self._state = DONE_PENDING_STATE;
  5504. self._tick(function() {
  5505. self._resolve(response);
  5506. });
  5507. }
  5508. },
  5509. _resolve: function(response) {
  5510. if (this._state !== DONE_COMPLETE_STATE) {
  5511. forEach(this._doneCallbacks, function(fn) {
  5512. fn(response);
  5513. });
  5514. this._doneCallbacks.length = 0;
  5515. this._state = DONE_COMPLETE_STATE;
  5516. }
  5517. }
  5518. };
  5519. return AnimateRunner;
  5520. }];
  5521. };
  5522. /* exported $CoreAnimateCssProvider */
  5523. /**
  5524. * @ngdoc service
  5525. * @name $animateCss
  5526. * @kind object
  5527. * @this
  5528. *
  5529. * @description
  5530. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5531. * then the `$animateCss` service will actually perform animations.
  5532. *
  5533. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5534. */
  5535. var $CoreAnimateCssProvider = function() {
  5536. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5537. return function(element, initialOptions) {
  5538. // all of the animation functions should create
  5539. // a copy of the options data, however, if a
  5540. // parent service has already created a copy then
  5541. // we should stick to using that
  5542. var options = initialOptions || {};
  5543. if (!options.$$prepared) {
  5544. options = copy(options);
  5545. }
  5546. // there is no point in applying the styles since
  5547. // there is no animation that goes on at all in
  5548. // this version of $animateCss.
  5549. if (options.cleanupStyles) {
  5550. options.from = options.to = null;
  5551. }
  5552. if (options.from) {
  5553. element.css(options.from);
  5554. options.from = null;
  5555. }
  5556. var closed, runner = new $$AnimateRunner();
  5557. return {
  5558. start: run,
  5559. end: run
  5560. };
  5561. function run() {
  5562. $$rAF(function() {
  5563. applyAnimationContents();
  5564. if (!closed) {
  5565. runner.complete();
  5566. }
  5567. closed = true;
  5568. });
  5569. return runner;
  5570. }
  5571. function applyAnimationContents() {
  5572. if (options.addClass) {
  5573. element.addClass(options.addClass);
  5574. options.addClass = null;
  5575. }
  5576. if (options.removeClass) {
  5577. element.removeClass(options.removeClass);
  5578. options.removeClass = null;
  5579. }
  5580. if (options.to) {
  5581. element.css(options.to);
  5582. options.to = null;
  5583. }
  5584. }
  5585. };
  5586. }];
  5587. };
  5588. /* global stripHash: true */
  5589. /**
  5590. * ! This is a private undocumented service !
  5591. *
  5592. * @name $browser
  5593. * @requires $log
  5594. * @description
  5595. * This object has two goals:
  5596. *
  5597. * - hide all the global state in the browser caused by the window object
  5598. * - abstract away all the browser specific features and inconsistencies
  5599. *
  5600. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5601. * service, which can be used for convenient testing of the application without the interaction with
  5602. * the real browser apis.
  5603. */
  5604. /**
  5605. * @param {object} window The global window object.
  5606. * @param {object} document jQuery wrapped document.
  5607. * @param {object} $log window.console or an object with the same interface.
  5608. * @param {object} $sniffer $sniffer service
  5609. */
  5610. function Browser(window, document, $log, $sniffer) {
  5611. var self = this,
  5612. location = window.location,
  5613. history = window.history,
  5614. setTimeout = window.setTimeout,
  5615. clearTimeout = window.clearTimeout,
  5616. pendingDeferIds = {};
  5617. self.isMock = false;
  5618. var outstandingRequestCount = 0;
  5619. var outstandingRequestCallbacks = [];
  5620. // TODO(vojta): remove this temporary api
  5621. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5622. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5623. /**
  5624. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5625. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5626. */
  5627. function completeOutstandingRequest(fn) {
  5628. try {
  5629. fn.apply(null, sliceArgs(arguments, 1));
  5630. } finally {
  5631. outstandingRequestCount--;
  5632. if (outstandingRequestCount === 0) {
  5633. while (outstandingRequestCallbacks.length) {
  5634. try {
  5635. outstandingRequestCallbacks.pop()();
  5636. } catch (e) {
  5637. $log.error(e);
  5638. }
  5639. }
  5640. }
  5641. }
  5642. }
  5643. function getHash(url) {
  5644. var index = url.indexOf('#');
  5645. return index === -1 ? '' : url.substr(index);
  5646. }
  5647. /**
  5648. * @private
  5649. * Note: this method is used only by scenario runner
  5650. * TODO(vojta): prefix this method with $$ ?
  5651. * @param {function()} callback Function that will be called when no outstanding request
  5652. */
  5653. self.notifyWhenNoOutstandingRequests = function(callback) {
  5654. if (outstandingRequestCount === 0) {
  5655. callback();
  5656. } else {
  5657. outstandingRequestCallbacks.push(callback);
  5658. }
  5659. };
  5660. //////////////////////////////////////////////////////////////
  5661. // URL API
  5662. //////////////////////////////////////////////////////////////
  5663. var cachedState, lastHistoryState,
  5664. lastBrowserUrl = location.href,
  5665. baseElement = document.find('base'),
  5666. pendingLocation = null,
  5667. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5668. try {
  5669. return history.state;
  5670. } catch (e) {
  5671. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5672. }
  5673. };
  5674. cacheState();
  5675. /**
  5676. * @name $browser#url
  5677. *
  5678. * @description
  5679. * GETTER:
  5680. * Without any argument, this method just returns current value of location.href.
  5681. *
  5682. * SETTER:
  5683. * With at least one argument, this method sets url to new value.
  5684. * If html5 history api supported, pushState/replaceState is used, otherwise
  5685. * location.href/location.replace is used.
  5686. * Returns its own instance to allow chaining
  5687. *
  5688. * NOTE: this api is intended for use only by the $location service. Please use the
  5689. * {@link ng.$location $location service} to change url.
  5690. *
  5691. * @param {string} url New url (when used as setter)
  5692. * @param {boolean=} replace Should new url replace current history record?
  5693. * @param {object=} state object to use with pushState/replaceState
  5694. */
  5695. self.url = function(url, replace, state) {
  5696. // In modern browsers `history.state` is `null` by default; treating it separately
  5697. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5698. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5699. if (isUndefined(state)) {
  5700. state = null;
  5701. }
  5702. // Android Browser BFCache causes location, history reference to become stale.
  5703. if (location !== window.location) location = window.location;
  5704. if (history !== window.history) history = window.history;
  5705. // setter
  5706. if (url) {
  5707. var sameState = lastHistoryState === state;
  5708. // Don't change anything if previous and current URLs and states match. This also prevents
  5709. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5710. // See https://github.com/angular/angular.js/commit/ffb2701
  5711. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5712. return self;
  5713. }
  5714. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5715. lastBrowserUrl = url;
  5716. lastHistoryState = state;
  5717. // Don't use history API if only the hash changed
  5718. // due to a bug in IE10/IE11 which leads
  5719. // to not firing a `hashchange` nor `popstate` event
  5720. // in some cases (see #9143).
  5721. if ($sniffer.history && (!sameBase || !sameState)) {
  5722. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5723. cacheState();
  5724. } else {
  5725. if (!sameBase) {
  5726. pendingLocation = url;
  5727. }
  5728. if (replace) {
  5729. location.replace(url);
  5730. } else if (!sameBase) {
  5731. location.href = url;
  5732. } else {
  5733. location.hash = getHash(url);
  5734. }
  5735. if (location.href !== url) {
  5736. pendingLocation = url;
  5737. }
  5738. }
  5739. if (pendingLocation) {
  5740. pendingLocation = url;
  5741. }
  5742. return self;
  5743. // getter
  5744. } else {
  5745. // - pendingLocation is needed as browsers don't allow to read out
  5746. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5747. // https://openradar.appspot.com/22186109).
  5748. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5749. return pendingLocation || location.href.replace(/%27/g,'\'');
  5750. }
  5751. };
  5752. /**
  5753. * @name $browser#state
  5754. *
  5755. * @description
  5756. * This method is a getter.
  5757. *
  5758. * Return history.state or null if history.state is undefined.
  5759. *
  5760. * @returns {object} state
  5761. */
  5762. self.state = function() {
  5763. return cachedState;
  5764. };
  5765. var urlChangeListeners = [],
  5766. urlChangeInit = false;
  5767. function cacheStateAndFireUrlChange() {
  5768. pendingLocation = null;
  5769. fireStateOrUrlChange();
  5770. }
  5771. // This variable should be used *only* inside the cacheState function.
  5772. var lastCachedState = null;
  5773. function cacheState() {
  5774. // This should be the only place in $browser where `history.state` is read.
  5775. cachedState = getCurrentState();
  5776. cachedState = isUndefined(cachedState) ? null : cachedState;
  5777. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5778. if (equals(cachedState, lastCachedState)) {
  5779. cachedState = lastCachedState;
  5780. }
  5781. lastCachedState = cachedState;
  5782. lastHistoryState = cachedState;
  5783. }
  5784. function fireStateOrUrlChange() {
  5785. var prevLastHistoryState = lastHistoryState;
  5786. cacheState();
  5787. if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
  5788. return;
  5789. }
  5790. lastBrowserUrl = self.url();
  5791. lastHistoryState = cachedState;
  5792. forEach(urlChangeListeners, function(listener) {
  5793. listener(self.url(), cachedState);
  5794. });
  5795. }
  5796. /**
  5797. * @name $browser#onUrlChange
  5798. *
  5799. * @description
  5800. * Register callback function that will be called, when url changes.
  5801. *
  5802. * It's only called when the url is changed from outside of angular:
  5803. * - user types different url into address bar
  5804. * - user clicks on history (forward/back) button
  5805. * - user clicks on a link
  5806. *
  5807. * It's not called when url is changed by $browser.url() method
  5808. *
  5809. * The listener gets called with new url as parameter.
  5810. *
  5811. * NOTE: this api is intended for use only by the $location service. Please use the
  5812. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5813. *
  5814. * @param {function(string)} listener Listener function to be called when url changes.
  5815. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5816. */
  5817. self.onUrlChange = function(callback) {
  5818. // TODO(vojta): refactor to use node's syntax for events
  5819. if (!urlChangeInit) {
  5820. // We listen on both (hashchange/popstate) when available, as some browsers don't
  5821. // fire popstate when user changes the address bar and don't fire hashchange when url
  5822. // changed by push/replaceState
  5823. // html5 history api - popstate event
  5824. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5825. // hashchange event
  5826. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5827. urlChangeInit = true;
  5828. }
  5829. urlChangeListeners.push(callback);
  5830. return callback;
  5831. };
  5832. /**
  5833. * @private
  5834. * Remove popstate and hashchange handler from window.
  5835. *
  5836. * NOTE: this api is intended for use only by $rootScope.
  5837. */
  5838. self.$$applicationDestroyed = function() {
  5839. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5840. };
  5841. /**
  5842. * Checks whether the url has changed outside of Angular.
  5843. * Needs to be exported to be able to check for changes that have been done in sync,
  5844. * as hashchange/popstate events fire in async.
  5845. */
  5846. self.$$checkUrlChange = fireStateOrUrlChange;
  5847. //////////////////////////////////////////////////////////////
  5848. // Misc API
  5849. //////////////////////////////////////////////////////////////
  5850. /**
  5851. * @name $browser#baseHref
  5852. *
  5853. * @description
  5854. * Returns current <base href>
  5855. * (always relative - without domain)
  5856. *
  5857. * @returns {string} The current base href
  5858. */
  5859. self.baseHref = function() {
  5860. var href = baseElement.attr('href');
  5861. return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
  5862. };
  5863. /**
  5864. * @name $browser#defer
  5865. * @param {function()} fn A function, who's execution should be deferred.
  5866. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5867. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5868. *
  5869. * @description
  5870. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5871. *
  5872. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5873. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5874. * via `$browser.defer.flush()`.
  5875. *
  5876. */
  5877. self.defer = function(fn, delay) {
  5878. var timeoutId;
  5879. outstandingRequestCount++;
  5880. timeoutId = setTimeout(function() {
  5881. delete pendingDeferIds[timeoutId];
  5882. completeOutstandingRequest(fn);
  5883. }, delay || 0);
  5884. pendingDeferIds[timeoutId] = true;
  5885. return timeoutId;
  5886. };
  5887. /**
  5888. * @name $browser#defer.cancel
  5889. *
  5890. * @description
  5891. * Cancels a deferred task identified with `deferId`.
  5892. *
  5893. * @param {*} deferId Token returned by the `$browser.defer` function.
  5894. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5895. * canceled.
  5896. */
  5897. self.defer.cancel = function(deferId) {
  5898. if (pendingDeferIds[deferId]) {
  5899. delete pendingDeferIds[deferId];
  5900. clearTimeout(deferId);
  5901. completeOutstandingRequest(noop);
  5902. return true;
  5903. }
  5904. return false;
  5905. };
  5906. }
  5907. /** @this */
  5908. function $BrowserProvider() {
  5909. this.$get = ['$window', '$log', '$sniffer', '$document',
  5910. function($window, $log, $sniffer, $document) {
  5911. return new Browser($window, $document, $log, $sniffer);
  5912. }];
  5913. }
  5914. /**
  5915. * @ngdoc service
  5916. * @name $cacheFactory
  5917. * @this
  5918. *
  5919. * @description
  5920. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5921. * them.
  5922. *
  5923. * ```js
  5924. *
  5925. * var cache = $cacheFactory('cacheId');
  5926. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5927. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5928. *
  5929. * cache.put("key", "value");
  5930. * cache.put("another key", "another value");
  5931. *
  5932. * // We've specified no options on creation
  5933. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5934. *
  5935. * ```
  5936. *
  5937. *
  5938. * @param {string} cacheId Name or id of the newly created cache.
  5939. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5940. *
  5941. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5942. *
  5943. * @returns {object} Newly created cache object with the following set of methods:
  5944. *
  5945. * - `{object}` `info()` — Returns id, size, and options of cache.
  5946. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5947. * it.
  5948. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5949. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5950. * - `{void}` `removeAll()` — Removes all cached values.
  5951. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5952. *
  5953. * @example
  5954. <example module="cacheExampleApp" name="cache-factory">
  5955. <file name="index.html">
  5956. <div ng-controller="CacheController">
  5957. <input ng-model="newCacheKey" placeholder="Key">
  5958. <input ng-model="newCacheValue" placeholder="Value">
  5959. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5960. <p ng-if="keys.length">Cached Values</p>
  5961. <div ng-repeat="key in keys">
  5962. <span ng-bind="key"></span>
  5963. <span>: </span>
  5964. <b ng-bind="cache.get(key)"></b>
  5965. </div>
  5966. <p>Cache Info</p>
  5967. <div ng-repeat="(key, value) in cache.info()">
  5968. <span ng-bind="key"></span>
  5969. <span>: </span>
  5970. <b ng-bind="value"></b>
  5971. </div>
  5972. </div>
  5973. </file>
  5974. <file name="script.js">
  5975. angular.module('cacheExampleApp', []).
  5976. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5977. $scope.keys = [];
  5978. $scope.cache = $cacheFactory('cacheId');
  5979. $scope.put = function(key, value) {
  5980. if (angular.isUndefined($scope.cache.get(key))) {
  5981. $scope.keys.push(key);
  5982. }
  5983. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5984. };
  5985. }]);
  5986. </file>
  5987. <file name="style.css">
  5988. p {
  5989. margin: 10px 0 3px;
  5990. }
  5991. </file>
  5992. </example>
  5993. */
  5994. function $CacheFactoryProvider() {
  5995. this.$get = function() {
  5996. var caches = {};
  5997. function cacheFactory(cacheId, options) {
  5998. if (cacheId in caches) {
  5999. throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
  6000. }
  6001. var size = 0,
  6002. stats = extend({}, options, {id: cacheId}),
  6003. data = createMap(),
  6004. capacity = (options && options.capacity) || Number.MAX_VALUE,
  6005. lruHash = createMap(),
  6006. freshEnd = null,
  6007. staleEnd = null;
  6008. /**
  6009. * @ngdoc type
  6010. * @name $cacheFactory.Cache
  6011. *
  6012. * @description
  6013. * A cache object used to store and retrieve data, primarily used by
  6014. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  6015. * templates and other data.
  6016. *
  6017. * ```js
  6018. * angular.module('superCache')
  6019. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  6020. * return $cacheFactory('super-cache');
  6021. * }]);
  6022. * ```
  6023. *
  6024. * Example test:
  6025. *
  6026. * ```js
  6027. * it('should behave like a cache', inject(function(superCache) {
  6028. * superCache.put('key', 'value');
  6029. * superCache.put('another key', 'another value');
  6030. *
  6031. * expect(superCache.info()).toEqual({
  6032. * id: 'super-cache',
  6033. * size: 2
  6034. * });
  6035. *
  6036. * superCache.remove('another key');
  6037. * expect(superCache.get('another key')).toBeUndefined();
  6038. *
  6039. * superCache.removeAll();
  6040. * expect(superCache.info()).toEqual({
  6041. * id: 'super-cache',
  6042. * size: 0
  6043. * });
  6044. * }));
  6045. * ```
  6046. */
  6047. return (caches[cacheId] = {
  6048. /**
  6049. * @ngdoc method
  6050. * @name $cacheFactory.Cache#put
  6051. * @kind function
  6052. *
  6053. * @description
  6054. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  6055. * retrieved later, and incrementing the size of the cache if the key was not already
  6056. * present in the cache. If behaving like an LRU cache, it will also remove stale
  6057. * entries from the set.
  6058. *
  6059. * It will not insert undefined values into the cache.
  6060. *
  6061. * @param {string} key the key under which the cached data is stored.
  6062. * @param {*} value the value to store alongside the key. If it is undefined, the key
  6063. * will not be stored.
  6064. * @returns {*} the value stored.
  6065. */
  6066. put: function(key, value) {
  6067. if (isUndefined(value)) return;
  6068. if (capacity < Number.MAX_VALUE) {
  6069. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  6070. refresh(lruEntry);
  6071. }
  6072. if (!(key in data)) size++;
  6073. data[key] = value;
  6074. if (size > capacity) {
  6075. this.remove(staleEnd.key);
  6076. }
  6077. return value;
  6078. },
  6079. /**
  6080. * @ngdoc method
  6081. * @name $cacheFactory.Cache#get
  6082. * @kind function
  6083. *
  6084. * @description
  6085. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  6086. *
  6087. * @param {string} key the key of the data to be retrieved
  6088. * @returns {*} the value stored.
  6089. */
  6090. get: function(key) {
  6091. if (capacity < Number.MAX_VALUE) {
  6092. var lruEntry = lruHash[key];
  6093. if (!lruEntry) return;
  6094. refresh(lruEntry);
  6095. }
  6096. return data[key];
  6097. },
  6098. /**
  6099. * @ngdoc method
  6100. * @name $cacheFactory.Cache#remove
  6101. * @kind function
  6102. *
  6103. * @description
  6104. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  6105. *
  6106. * @param {string} key the key of the entry to be removed
  6107. */
  6108. remove: function(key) {
  6109. if (capacity < Number.MAX_VALUE) {
  6110. var lruEntry = lruHash[key];
  6111. if (!lruEntry) return;
  6112. if (lruEntry === freshEnd) freshEnd = lruEntry.p;
  6113. if (lruEntry === staleEnd) staleEnd = lruEntry.n;
  6114. link(lruEntry.n,lruEntry.p);
  6115. delete lruHash[key];
  6116. }
  6117. if (!(key in data)) return;
  6118. delete data[key];
  6119. size--;
  6120. },
  6121. /**
  6122. * @ngdoc method
  6123. * @name $cacheFactory.Cache#removeAll
  6124. * @kind function
  6125. *
  6126. * @description
  6127. * Clears the cache object of any entries.
  6128. */
  6129. removeAll: function() {
  6130. data = createMap();
  6131. size = 0;
  6132. lruHash = createMap();
  6133. freshEnd = staleEnd = null;
  6134. },
  6135. /**
  6136. * @ngdoc method
  6137. * @name $cacheFactory.Cache#destroy
  6138. * @kind function
  6139. *
  6140. * @description
  6141. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  6142. * removing it from the {@link $cacheFactory $cacheFactory} set.
  6143. */
  6144. destroy: function() {
  6145. data = null;
  6146. stats = null;
  6147. lruHash = null;
  6148. delete caches[cacheId];
  6149. },
  6150. /**
  6151. * @ngdoc method
  6152. * @name $cacheFactory.Cache#info
  6153. * @kind function
  6154. *
  6155. * @description
  6156. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  6157. *
  6158. * @returns {object} an object with the following properties:
  6159. * <ul>
  6160. * <li>**id**: the id of the cache instance</li>
  6161. * <li>**size**: the number of entries kept in the cache instance</li>
  6162. * <li>**...**: any additional properties from the options object when creating the
  6163. * cache.</li>
  6164. * </ul>
  6165. */
  6166. info: function() {
  6167. return extend({}, stats, {size: size});
  6168. }
  6169. });
  6170. /**
  6171. * makes the `entry` the freshEnd of the LRU linked list
  6172. */
  6173. function refresh(entry) {
  6174. if (entry !== freshEnd) {
  6175. if (!staleEnd) {
  6176. staleEnd = entry;
  6177. } else if (staleEnd === entry) {
  6178. staleEnd = entry.n;
  6179. }
  6180. link(entry.n, entry.p);
  6181. link(entry, freshEnd);
  6182. freshEnd = entry;
  6183. freshEnd.n = null;
  6184. }
  6185. }
  6186. /**
  6187. * bidirectionally links two entries of the LRU linked list
  6188. */
  6189. function link(nextEntry, prevEntry) {
  6190. if (nextEntry !== prevEntry) {
  6191. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  6192. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  6193. }
  6194. }
  6195. }
  6196. /**
  6197. * @ngdoc method
  6198. * @name $cacheFactory#info
  6199. *
  6200. * @description
  6201. * Get information about all the caches that have been created
  6202. *
  6203. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  6204. */
  6205. cacheFactory.info = function() {
  6206. var info = {};
  6207. forEach(caches, function(cache, cacheId) {
  6208. info[cacheId] = cache.info();
  6209. });
  6210. return info;
  6211. };
  6212. /**
  6213. * @ngdoc method
  6214. * @name $cacheFactory#get
  6215. *
  6216. * @description
  6217. * Get access to a cache object by the `cacheId` used when it was created.
  6218. *
  6219. * @param {string} cacheId Name or id of a cache to access.
  6220. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  6221. */
  6222. cacheFactory.get = function(cacheId) {
  6223. return caches[cacheId];
  6224. };
  6225. return cacheFactory;
  6226. };
  6227. }
  6228. /**
  6229. * @ngdoc service
  6230. * @name $templateCache
  6231. * @this
  6232. *
  6233. * @description
  6234. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  6235. * can load templates directly into the cache in a `script` tag, or by consuming the
  6236. * `$templateCache` service directly.
  6237. *
  6238. * Adding via the `script` tag:
  6239. *
  6240. * ```html
  6241. * <script type="text/ng-template" id="templateId.html">
  6242. * <p>This is the content of the template</p>
  6243. * </script>
  6244. * ```
  6245. *
  6246. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  6247. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  6248. * element with ng-app attribute), otherwise the template will be ignored.
  6249. *
  6250. * Adding via the `$templateCache` service:
  6251. *
  6252. * ```js
  6253. * var myApp = angular.module('myApp', []);
  6254. * myApp.run(function($templateCache) {
  6255. * $templateCache.put('templateId.html', 'This is the content of the template');
  6256. * });
  6257. * ```
  6258. *
  6259. * To retrieve the template later, simply use it in your component:
  6260. * ```js
  6261. * myApp.component('myComponent', {
  6262. * templateUrl: 'templateId.html'
  6263. * });
  6264. * ```
  6265. *
  6266. * or get it via the `$templateCache` service:
  6267. * ```js
  6268. * $templateCache.get('templateId.html')
  6269. * ```
  6270. *
  6271. * See {@link ng.$cacheFactory $cacheFactory}.
  6272. *
  6273. */
  6274. function $TemplateCacheProvider() {
  6275. this.$get = ['$cacheFactory', function($cacheFactory) {
  6276. return $cacheFactory('templates');
  6277. }];
  6278. }
  6279. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  6280. * Any commits to this file should be reviewed with security in mind. *
  6281. * Changes to this file can potentially create security vulnerabilities. *
  6282. * An approval from 2 Core members with history of modifying *
  6283. * this file is required. *
  6284. * *
  6285. * Does the change somehow allow for arbitrary javascript to be executed? *
  6286. * Or allows for someone to change the prototype of built-in objects? *
  6287. * Or gives undesired access to variables like document or window? *
  6288. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6289. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6290. *
  6291. * DOM-related variables:
  6292. *
  6293. * - "node" - DOM Node
  6294. * - "element" - DOM Element or Node
  6295. * - "$node" or "$element" - jqLite-wrapped node or element
  6296. *
  6297. *
  6298. * Compiler related stuff:
  6299. *
  6300. * - "linkFn" - linking fn of a single directive
  6301. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6302. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6303. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6304. */
  6305. /**
  6306. * @ngdoc service
  6307. * @name $compile
  6308. * @kind function
  6309. *
  6310. * @description
  6311. * Compiles an HTML string or DOM into a template and produces a template function, which
  6312. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6313. *
  6314. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6315. * {@link ng.$compileProvider#directive directives}.
  6316. *
  6317. * <div class="alert alert-warning">
  6318. * **Note:** This document is an in-depth reference of all directive options.
  6319. * For a gentle introduction to directives with examples of common use cases,
  6320. * see the {@link guide/directive directive guide}.
  6321. * </div>
  6322. *
  6323. * ## Comprehensive Directive API
  6324. *
  6325. * There are many different options for a directive.
  6326. *
  6327. * The difference resides in the return value of the factory function.
  6328. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6329. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6330. * the default values).
  6331. *
  6332. * <div class="alert alert-success">
  6333. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6334. * </div>
  6335. *
  6336. * Here's an example directive declared with a Directive Definition Object:
  6337. *
  6338. * ```js
  6339. * var myModule = angular.module(...);
  6340. *
  6341. * myModule.directive('directiveName', function factory(injectables) {
  6342. * var directiveDefinitionObject = {
  6343. * {@link $compile#-priority- priority}: 0,
  6344. * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6345. * // or
  6346. * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6347. * {@link $compile#-transclude- transclude}: false,
  6348. * {@link $compile#-restrict- restrict}: 'A',
  6349. * {@link $compile#-templatenamespace- templateNamespace}: 'html',
  6350. * {@link $compile#-scope- scope}: false,
  6351. * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6352. * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
  6353. * {@link $compile#-bindtocontroller- bindToController}: false,
  6354. * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6355. * {@link $compile#-multielement- multiElement}: false,
  6356. * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
  6357. * return {
  6358. * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6359. * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6360. * }
  6361. * // or
  6362. * // return function postLink( ... ) { ... }
  6363. * },
  6364. * // or
  6365. * // {@link $compile#-link- link}: {
  6366. * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6367. * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6368. * // }
  6369. * // or
  6370. * // {@link $compile#-link- link}: function postLink( ... ) { ... }
  6371. * };
  6372. * return directiveDefinitionObject;
  6373. * });
  6374. * ```
  6375. *
  6376. * <div class="alert alert-warning">
  6377. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6378. * </div>
  6379. *
  6380. * Therefore the above can be simplified as:
  6381. *
  6382. * ```js
  6383. * var myModule = angular.module(...);
  6384. *
  6385. * myModule.directive('directiveName', function factory(injectables) {
  6386. * var directiveDefinitionObject = {
  6387. * link: function postLink(scope, iElement, iAttrs) { ... }
  6388. * };
  6389. * return directiveDefinitionObject;
  6390. * // or
  6391. * // return function postLink(scope, iElement, iAttrs) { ... }
  6392. * });
  6393. * ```
  6394. *
  6395. * ### Life-cycle hooks
  6396. * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the
  6397. * directive:
  6398. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6399. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6400. * this element). This is a good place to put initialization code for your controller.
  6401. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6402. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6403. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6404. * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
  6405. * also be called when your bindings are initialized.
  6406. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6407. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6408. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6409. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6410. * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6411. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6412. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6413. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6414. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6415. * components will have their `$onDestroy()` hook called before child components.
  6416. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6417. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6418. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6419. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6420. * suspended until that occurs.
  6421. *
  6422. * #### Comparison with Angular 2 life-cycle hooks
  6423. * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are
  6424. * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:
  6425. *
  6426. * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.
  6427. * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6428. * In Angular 2 you can only define hooks on the prototype of the Component class.
  6429. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to
  6430. * `ngDoCheck` in Angular 2
  6431. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6432. * propagated throughout the application.
  6433. * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6434. * error or do nothing depending upon the state of `enableProdMode()`.
  6435. *
  6436. * #### Life-cycle hook examples
  6437. *
  6438. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6439. * has not changed.
  6440. *
  6441. * <example name="doCheckDateExample" module="do-check-module">
  6442. * <file name="app.js">
  6443. * angular.module('do-check-module', [])
  6444. * .component('app', {
  6445. * template:
  6446. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6447. * 'Date: {{ $ctrl.date }}' +
  6448. * '<test date="$ctrl.date"></test>',
  6449. * controller: function() {
  6450. * this.date = new Date();
  6451. * this.month = this.date.getMonth();
  6452. * this.updateDate = function() {
  6453. * this.date.setMonth(this.month);
  6454. * };
  6455. * }
  6456. * })
  6457. * .component('test', {
  6458. * bindings: { date: '<' },
  6459. * template:
  6460. * '<pre>{{ $ctrl.log | json }}</pre>',
  6461. * controller: function() {
  6462. * var previousValue;
  6463. * this.log = [];
  6464. * this.$doCheck = function() {
  6465. * var currentValue = this.date && this.date.valueOf();
  6466. * if (previousValue !== currentValue) {
  6467. * this.log.push('doCheck: date mutated: ' + this.date);
  6468. * previousValue = currentValue;
  6469. * }
  6470. * };
  6471. * }
  6472. * });
  6473. * </file>
  6474. * <file name="index.html">
  6475. * <app></app>
  6476. * </file>
  6477. * </example>
  6478. *
  6479. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6480. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6481. * arrays or objects can have a negative impact on your application performance)
  6482. *
  6483. * <example name="doCheckArrayExample" module="do-check-module">
  6484. * <file name="index.html">
  6485. * <div ng-init="items = []">
  6486. * <button ng-click="items.push(items.length)">Add Item</button>
  6487. * <button ng-click="items = []">Reset Items</button>
  6488. * <pre>{{ items }}</pre>
  6489. * <test items="items"></test>
  6490. * </div>
  6491. * </file>
  6492. * <file name="app.js">
  6493. * angular.module('do-check-module', [])
  6494. * .component('test', {
  6495. * bindings: { items: '<' },
  6496. * template:
  6497. * '<pre>{{ $ctrl.log | json }}</pre>',
  6498. * controller: function() {
  6499. * this.log = [];
  6500. *
  6501. * this.$doCheck = function() {
  6502. * if (this.items_ref !== this.items) {
  6503. * this.log.push('doCheck: items changed');
  6504. * this.items_ref = this.items;
  6505. * }
  6506. * if (!angular.equals(this.items_clone, this.items)) {
  6507. * this.log.push('doCheck: items mutated');
  6508. * this.items_clone = angular.copy(this.items);
  6509. * }
  6510. * };
  6511. * }
  6512. * });
  6513. * </file>
  6514. * </example>
  6515. *
  6516. *
  6517. * ### Directive Definition Object
  6518. *
  6519. * The directive definition object provides instructions to the {@link ng.$compile
  6520. * compiler}. The attributes are:
  6521. *
  6522. * #### `multiElement`
  6523. * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
  6524. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6525. * together as the directive elements. It is recommended that this feature be used on directives
  6526. * which are not strictly behavioral (such as {@link ngClick}), and which
  6527. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6528. *
  6529. * #### `priority`
  6530. * When there are multiple directives defined on a single DOM element, sometimes it
  6531. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6532. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6533. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6534. * are also run in priority order, but post-link functions are run in reverse order. The order
  6535. * of directives with the same priority is undefined. The default priority is `0`.
  6536. *
  6537. * #### `terminal`
  6538. * If set to true then the current `priority` will be the last set of directives
  6539. * which will execute (any directives at the current priority will still execute
  6540. * as the order of execution on same `priority` is undefined). Note that expressions
  6541. * and other directives used in the directive's template will also be excluded from execution.
  6542. *
  6543. * #### `scope`
  6544. * The scope property can be `false`, `true`, or an object:
  6545. *
  6546. * * **`false` (default):** No scope will be created for the directive. The directive will use its
  6547. * parent's scope.
  6548. *
  6549. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6550. * the directive's element. If multiple directives on the same element request a new scope,
  6551. * only one new scope is created.
  6552. *
  6553. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template.
  6554. * The 'isolate' scope differs from normal scope in that it does not prototypically
  6555. * inherit from its parent scope. This is useful when creating reusable components, which should not
  6556. * accidentally read or modify data in the parent scope. Note that an isolate scope
  6557. * directive without a `template` or `templateUrl` will not apply the isolate scope
  6558. * to its children elements.
  6559. *
  6560. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6561. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6562. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6563. * is bound to the parent scope, via matching attributes on the directive's element:
  6564. *
  6565. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6566. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6567. * attribute name is assumed to be the same as the local name. Given `<my-component
  6568. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6569. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6570. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6571. * scope. The `name` is read from the parent scope (not the directive's scope).
  6572. *
  6573. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6574. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6575. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6576. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6577. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6578. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6579. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6580. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6581. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6582. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6583. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6584. * method is used for tracking changes, and the equality check is based on object identity.
  6585. * However, if an object literal or an array literal is passed as the binding expression, the
  6586. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6587. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6588. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6589. *
  6590. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6591. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6592. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6593. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6594. *
  6595. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6596. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6597. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6598. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6599. * two caveats:
  6600. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6601. * sets the same value. That means if your bound value is an object, changes to its properties
  6602. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6603. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6604. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6605. * to the value has changed. In most cases, this should not be of concern, but can be important
  6606. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6607. * If you now change a property of the object in your parent scope, the change will not be
  6608. * propagated to the isolated scope, because the identity of the object on the parent scope
  6609. * has not changed. Instead you must assign a new object.
  6610. *
  6611. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6612. * back to the parent. However, it does not make this completely impossible.
  6613. *
  6614. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6615. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6616. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6617. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6618. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6619. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6620. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6621. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6622. *
  6623. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6624. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6625. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6626. *
  6627. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6628. * * **child scope** + **no scope** => Both directives will share one single child scope
  6629. * * **child scope** + **child scope** => Both directives will share one single child scope
  6630. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6631. * its parent's scope
  6632. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6633. * be applied to the same element.
  6634. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6635. * cannot be applied to the same element.
  6636. *
  6637. *
  6638. * #### `bindToController`
  6639. * This property is used to bind scope properties directly to the controller. It can be either
  6640. * `true` or an object hash with the same format as the `scope` property.
  6641. *
  6642. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6643. * allow a component to have its properties bound to the controller, rather than to scope.
  6644. *
  6645. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6646. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6647. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6648. * initialized.
  6649. *
  6650. * <div class="alert alert-warning">
  6651. * **Deprecation warning:** if `$compileProcvider.preAssignBindingsEnabled(true)` was called, bindings for non-ES6 class
  6652. * controllers are bound to `this` before the controller constructor is called but this use is now deprecated. Please
  6653. * place initialization code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6654. * </div>
  6655. *
  6656. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6657. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6658. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6659. * scope (useful for component directives).
  6660. *
  6661. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6662. *
  6663. *
  6664. * #### `controller`
  6665. * Controller constructor function. The controller is instantiated before the
  6666. * pre-linking phase and can be accessed by other directives (see
  6667. * `require` attribute). This allows the directives to communicate with each other and augment
  6668. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6669. *
  6670. * * `$scope` - Current scope associated with the element
  6671. * * `$element` - Current element
  6672. * * `$attrs` - Current attributes object for the element
  6673. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6674. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6675. * * `scope`: (optional) override the scope.
  6676. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6677. * * `futureParentElement` (optional):
  6678. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6679. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6680. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6681. * and when the `cloneLinkingFn` is passed,
  6682. * as those elements need to created and cloned in a special way when they are defined outside their
  6683. * usual containers (e.g. like `<svg>`).
  6684. * * See also the `directive.templateNamespace` property.
  6685. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6686. * then the default transclusion is provided.
  6687. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6688. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6689. *
  6690. * #### `require`
  6691. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6692. * `require` property can be a string, an array or an object:
  6693. * * a **string** containing the name of the directive to pass to the linking function
  6694. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6695. * linking function will be an array of controllers in the same order as the names in the `require` property
  6696. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6697. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6698. * controllers.
  6699. *
  6700. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6701. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6702. * have been constructed but before `$onInit` is called.
  6703. * If the name of the required controller is the same as the local name (the key), the name can be
  6704. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6705. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6706. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6707. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6708. * controller, in which case error checking is skipped). The name can be prefixed with:
  6709. *
  6710. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6711. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6712. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6713. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6714. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6715. * `null` to the `link` fn if not found.
  6716. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6717. * `null` to the `link` fn if not found.
  6718. *
  6719. *
  6720. * #### `controllerAs`
  6721. * Identifier name for a reference to the controller in the directive's scope.
  6722. * This allows the controller to be referenced from the directive template. This is especially
  6723. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6724. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6725. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6726. *
  6727. *
  6728. * #### `restrict`
  6729. * String of subset of `EACM` which restricts the directive to a specific directive
  6730. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6731. *
  6732. * * `E` - Element name (default): `<my-directive></my-directive>`
  6733. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6734. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6735. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6736. *
  6737. *
  6738. * #### `templateNamespace`
  6739. * String representing the document type used by the markup in the template.
  6740. * AngularJS needs this information as those elements need to be created and cloned
  6741. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6742. *
  6743. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6744. * top-level elements such as `<svg>` or `<math>`.
  6745. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6746. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6747. *
  6748. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6749. *
  6750. * #### `template`
  6751. * HTML markup that may:
  6752. * * Replace the contents of the directive's element (default).
  6753. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6754. * * Wrap the contents of the directive's element (if `transclude` is true).
  6755. *
  6756. * Value may be:
  6757. *
  6758. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6759. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6760. * function api below) and returns a string value.
  6761. *
  6762. *
  6763. * #### `templateUrl`
  6764. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6765. *
  6766. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6767. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6768. * sibling and parent elements as though this element had not contained any directives.
  6769. *
  6770. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6771. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6772. * case when only one deeply nested directive has `templateUrl`.
  6773. *
  6774. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6775. *
  6776. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6777. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6778. * a string value representing the url. In either case, the template URL is passed through {@link
  6779. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6780. *
  6781. *
  6782. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6783. * specify what the template should replace. Defaults to `false`.
  6784. *
  6785. * * `true` - the template will replace the directive's element.
  6786. * * `false` - the template will replace the contents of the directive's element.
  6787. *
  6788. * The replacement process migrates all of the attributes / classes from the old element to the new
  6789. * one. See the {@link guide/directive#template-expanding-directive
  6790. * Directives Guide} for an example.
  6791. *
  6792. * There are very few scenarios where element replacement is required for the application function,
  6793. * the main one being reusable custom components that are used within SVG contexts
  6794. * (because SVG doesn't work with custom elements in the DOM tree).
  6795. *
  6796. * #### `transclude`
  6797. * Extract the contents of the element where the directive appears and make it available to the directive.
  6798. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6799. * {@link $compile#transclusion Transclusion} section below.
  6800. *
  6801. *
  6802. * #### `compile`
  6803. *
  6804. * ```js
  6805. * function compile(tElement, tAttrs, transclude) { ... }
  6806. * ```
  6807. *
  6808. * The compile function deals with transforming the template DOM. Since most directives do not do
  6809. * template transformation, it is not used often. The compile function takes the following arguments:
  6810. *
  6811. * * `tElement` - template element - The element where the directive has been declared. It is
  6812. * safe to do template transformation on the element and child elements only.
  6813. *
  6814. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6815. * between all directive compile functions.
  6816. *
  6817. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6818. *
  6819. * <div class="alert alert-warning">
  6820. * **Note:** The template instance and the link instance may be different objects if the template has
  6821. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6822. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6823. * should be done in a linking function rather than in a compile function.
  6824. * </div>
  6825. * <div class="alert alert-warning">
  6826. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6827. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6828. * stack overflow errors.
  6829. *
  6830. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6831. * a directive's template instead of relying on automatic template compilation via `template` or
  6832. * `templateUrl` declaration or manual compilation inside the compile function.
  6833. * </div>
  6834. *
  6835. * <div class="alert alert-danger">
  6836. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6837. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6838. * to the link function instead.
  6839. * </div>
  6840. * A compile function can have a return value which can be either a function or an object.
  6841. *
  6842. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6843. * `link` property of the config object when the compile function is empty.
  6844. *
  6845. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6846. * control when a linking function should be called during the linking phase. See info about
  6847. * pre-linking and post-linking functions below.
  6848. *
  6849. *
  6850. * #### `link`
  6851. * This property is used only if the `compile` property is not defined.
  6852. *
  6853. * ```js
  6854. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6855. * ```
  6856. *
  6857. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6858. * executed after the template has been cloned. This is where most of the directive logic will be
  6859. * put.
  6860. *
  6861. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6862. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6863. *
  6864. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6865. * manipulate the children of the element only in `postLink` function since the children have
  6866. * already been linked.
  6867. *
  6868. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6869. * between all directive linking functions.
  6870. *
  6871. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6872. * among all directives, which allows the directives to use the controllers as a communication
  6873. * channel. The exact value depends on the directive's `require` property:
  6874. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6875. * * `string`: the controller instance
  6876. * * `array`: array of controller instances
  6877. *
  6878. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6879. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6880. *
  6881. * Note that you can also require the directive's own controller - it will be made available like
  6882. * any other controller.
  6883. *
  6884. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6885. * This is the same as the `$transclude` parameter of directive controllers,
  6886. * see {@link ng.$compile#-controller- the controller section for details}.
  6887. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6888. *
  6889. * #### Pre-linking function
  6890. *
  6891. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6892. * compiler linking function will fail to locate the correct elements for linking.
  6893. *
  6894. * #### Post-linking function
  6895. *
  6896. * Executed after the child elements are linked.
  6897. *
  6898. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6899. * and linked since they are waiting for their template to load asynchronously and their own
  6900. * compilation and linking has been suspended until that occurs.
  6901. *
  6902. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6903. * for their async templates to be resolved.
  6904. *
  6905. *
  6906. * ### Transclusion
  6907. *
  6908. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6909. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6910. * scope from where they were taken.
  6911. *
  6912. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6913. * original contents of a directive's element into a specified place in the template of the directive.
  6914. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6915. * content has access to the properties on the scope from which it was taken, even if the directive
  6916. * has isolated scope.
  6917. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6918. *
  6919. * This makes it possible for the widget to have private state for its template, while the transcluded
  6920. * content has access to its originating scope.
  6921. *
  6922. * <div class="alert alert-warning">
  6923. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6924. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6925. * Testing Transclusion Directives}.
  6926. * </div>
  6927. *
  6928. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  6929. * directive's element, the entire element or multiple parts of the element contents:
  6930. *
  6931. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  6932. * * `'element'` - transclude the whole of the directive's element including any directives on this
  6933. * element that defined at a lower priority than this directive. When used, the `template`
  6934. * property is ignored.
  6935. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  6936. *
  6937. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  6938. *
  6939. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  6940. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  6941. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  6942. *
  6943. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6944. *
  6945. * If the element selector is prefixed with a `?` then that slot is optional.
  6946. *
  6947. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  6948. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  6949. *
  6950. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  6951. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  6952. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  6953. * injectable into the directive's controller.
  6954. *
  6955. *
  6956. * #### Transclusion Functions
  6957. *
  6958. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6959. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6960. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6961. *
  6962. * <div class="alert alert-info">
  6963. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6964. * ngTransclude will deal with it for us.
  6965. * </div>
  6966. *
  6967. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6968. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6969. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6970. *
  6971. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6972. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6973. * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
  6974. *
  6975. * <div class="alert alert-info">
  6976. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  6977. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6978. * </div>
  6979. *
  6980. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6981. * attach function**:
  6982. *
  6983. * ```js
  6984. * var transcludedContent, transclusionScope;
  6985. *
  6986. * $transclude(function(clone, scope) {
  6987. * element.append(clone);
  6988. * transcludedContent = clone;
  6989. * transclusionScope = scope;
  6990. * });
  6991. * ```
  6992. *
  6993. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6994. * associated transclusion scope:
  6995. *
  6996. * ```js
  6997. * transcludedContent.remove();
  6998. * transclusionScope.$destroy();
  6999. * ```
  7000. *
  7001. * <div class="alert alert-info">
  7002. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  7003. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  7004. * then you are also responsible for calling `$destroy` on the transclusion scope.
  7005. * </div>
  7006. *
  7007. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  7008. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  7009. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  7010. *
  7011. *
  7012. * #### Transclusion Scopes
  7013. *
  7014. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  7015. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  7016. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  7017. * was taken.
  7018. *
  7019. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  7020. * like this:
  7021. *
  7022. * ```html
  7023. * <div ng-app>
  7024. * <div isolate>
  7025. * <div transclusion>
  7026. * </div>
  7027. * </div>
  7028. * </div>
  7029. * ```
  7030. *
  7031. * The `$parent` scope hierarchy will look like this:
  7032. *
  7033. ```
  7034. - $rootScope
  7035. - isolate
  7036. - transclusion
  7037. ```
  7038. *
  7039. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  7040. *
  7041. ```
  7042. - $rootScope
  7043. - transclusion
  7044. - isolate
  7045. ```
  7046. *
  7047. *
  7048. * ### Attributes
  7049. *
  7050. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  7051. * `link()` or `compile()` functions. It has a variety of uses.
  7052. *
  7053. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  7054. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  7055. * to the attributes.
  7056. *
  7057. * * *Directive inter-communication:* All directives share the same instance of the attributes
  7058. * object which allows the directives to use the attributes object as inter directive
  7059. * communication.
  7060. *
  7061. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  7062. * allowing other directives to read the interpolated value.
  7063. *
  7064. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  7065. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  7066. * the only way to easily get the actual value because during the linking phase the interpolation
  7067. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  7068. *
  7069. * ```js
  7070. * function linkingFn(scope, elm, attrs, ctrl) {
  7071. * // get the attribute value
  7072. * console.log(attrs.ngModel);
  7073. *
  7074. * // change the attribute
  7075. * attrs.$set('ngModel', 'new value');
  7076. *
  7077. * // observe changes to interpolated attribute
  7078. * attrs.$observe('ngModel', function(value) {
  7079. * console.log('ngModel has changed value to ' + value);
  7080. * });
  7081. * }
  7082. * ```
  7083. *
  7084. * ## Example
  7085. *
  7086. * <div class="alert alert-warning">
  7087. * **Note**: Typically directives are registered with `module.directive`. The example below is
  7088. * to illustrate how `$compile` works.
  7089. * </div>
  7090. *
  7091. <example module="compileExample" name="compile">
  7092. <file name="index.html">
  7093. <script>
  7094. angular.module('compileExample', [], function($compileProvider) {
  7095. // configure new 'compile' directive by passing a directive
  7096. // factory function. The factory function injects the '$compile'
  7097. $compileProvider.directive('compile', function($compile) {
  7098. // directive factory creates a link function
  7099. return function(scope, element, attrs) {
  7100. scope.$watch(
  7101. function(scope) {
  7102. // watch the 'compile' expression for changes
  7103. return scope.$eval(attrs.compile);
  7104. },
  7105. function(value) {
  7106. // when the 'compile' expression changes
  7107. // assign it into the current DOM
  7108. element.html(value);
  7109. // compile the new DOM and link it to the current
  7110. // scope.
  7111. // NOTE: we only compile .childNodes so that
  7112. // we don't get into infinite loop compiling ourselves
  7113. $compile(element.contents())(scope);
  7114. }
  7115. );
  7116. };
  7117. });
  7118. })
  7119. .controller('GreeterController', ['$scope', function($scope) {
  7120. $scope.name = 'Angular';
  7121. $scope.html = 'Hello {{name}}';
  7122. }]);
  7123. </script>
  7124. <div ng-controller="GreeterController">
  7125. <input ng-model="name"> <br/>
  7126. <textarea ng-model="html"></textarea> <br/>
  7127. <div compile="html"></div>
  7128. </div>
  7129. </file>
  7130. <file name="protractor.js" type="protractor">
  7131. it('should auto compile', function() {
  7132. var textarea = $('textarea');
  7133. var output = $('div[compile]');
  7134. // The initial state reads 'Hello Angular'.
  7135. expect(output.getText()).toBe('Hello Angular');
  7136. textarea.clear();
  7137. textarea.sendKeys('{{name}}!');
  7138. expect(output.getText()).toBe('Angular!');
  7139. });
  7140. </file>
  7141. </example>
  7142. *
  7143. *
  7144. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  7145. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  7146. *
  7147. * <div class="alert alert-danger">
  7148. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  7149. * e.g. will not use the right outer scope. Please pass the transclude function as a
  7150. * `parentBoundTranscludeFn` to the link function instead.
  7151. * </div>
  7152. *
  7153. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  7154. * root element(s), not their children)
  7155. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  7156. * (a DOM element/tree) to a scope. Where:
  7157. *
  7158. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  7159. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  7160. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  7161. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  7162. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  7163. *
  7164. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  7165. * * `scope` - is the current scope with which the linking function is working with.
  7166. *
  7167. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  7168. * keys may be used to control linking behavior:
  7169. *
  7170. * * `parentBoundTranscludeFn` - the transclude function made available to
  7171. * directives; if given, it will be passed through to the link functions of
  7172. * directives found in `element` during compilation.
  7173. * * `transcludeControllers` - an object hash with keys that map controller names
  7174. * to a hash with the key `instance`, which maps to the controller instance;
  7175. * if given, it will make the controllers available to directives on the compileNode:
  7176. * ```
  7177. * {
  7178. * parent: {
  7179. * instance: parentControllerInstance
  7180. * }
  7181. * }
  7182. * ```
  7183. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  7184. * the cloned elements; only needed for transcludes that are allowed to contain non html
  7185. * elements (e.g. SVG elements). See also the directive.controller property.
  7186. *
  7187. * Calling the linking function returns the element of the template. It is either the original
  7188. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  7189. *
  7190. * After linking the view is not updated until after a call to $digest which typically is done by
  7191. * Angular automatically.
  7192. *
  7193. * If you need access to the bound view, there are two ways to do it:
  7194. *
  7195. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  7196. * before you send them to the compiler and keep this reference around.
  7197. * ```js
  7198. * var element = $compile('<p>{{total}}</p>')(scope);
  7199. * ```
  7200. *
  7201. * - if on the other hand, you need the element to be cloned, the view reference from the original
  7202. * example would not point to the clone, but rather to the original template that was cloned. In
  7203. * this case, you can access the clone via the cloneAttachFn:
  7204. * ```js
  7205. * var templateElement = angular.element('<p>{{total}}</p>'),
  7206. * scope = ....;
  7207. *
  7208. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  7209. * //attach the clone to DOM document at the right place
  7210. * });
  7211. *
  7212. * //now we have reference to the cloned DOM via `clonedElement`
  7213. * ```
  7214. *
  7215. *
  7216. * For information on how the compiler works, see the
  7217. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  7218. *
  7219. * @knownIssue
  7220. *
  7221. * ### Double Compilation
  7222. *
  7223. Double compilation occurs when an already compiled part of the DOM gets
  7224. compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
  7225. and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
  7226. section on double compilation} for an in-depth explanation and ways to avoid it.
  7227. *
  7228. */
  7229. var $compileMinErr = minErr('$compile');
  7230. function UNINITIALIZED_VALUE() {}
  7231. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  7232. /**
  7233. * @ngdoc provider
  7234. * @name $compileProvider
  7235. *
  7236. * @description
  7237. */
  7238. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  7239. /** @this */
  7240. function $CompileProvider($provide, $$sanitizeUriProvider) {
  7241. var hasDirectives = {},
  7242. Suffix = 'Directive',
  7243. COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
  7244. CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
  7245. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  7246. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  7247. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  7248. // The assumption is that future DOM event attribute names will begin with
  7249. // 'on' and be composed of only English letters.
  7250. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  7251. var bindingCache = createMap();
  7252. function parseIsolateBindings(scope, directiveName, isController) {
  7253. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/;
  7254. var bindings = createMap();
  7255. forEach(scope, function(definition, scopeName) {
  7256. if (definition in bindingCache) {
  7257. bindings[scopeName] = bindingCache[definition];
  7258. return;
  7259. }
  7260. var match = definition.match(LOCAL_REGEXP);
  7261. if (!match) {
  7262. throw $compileMinErr('iscp',
  7263. 'Invalid {3} for directive \'{0}\'.' +
  7264. ' Definition: {... {1}: \'{2}\' ...}',
  7265. directiveName, scopeName, definition,
  7266. (isController ? 'controller bindings definition' :
  7267. 'isolate scope definition'));
  7268. }
  7269. bindings[scopeName] = {
  7270. mode: match[1][0],
  7271. collection: match[2] === '*',
  7272. optional: match[3] === '?',
  7273. attrName: match[4] || scopeName
  7274. };
  7275. if (match[4]) {
  7276. bindingCache[definition] = bindings[scopeName];
  7277. }
  7278. });
  7279. return bindings;
  7280. }
  7281. function parseDirectiveBindings(directive, directiveName) {
  7282. var bindings = {
  7283. isolateScope: null,
  7284. bindToController: null
  7285. };
  7286. if (isObject(directive.scope)) {
  7287. if (directive.bindToController === true) {
  7288. bindings.bindToController = parseIsolateBindings(directive.scope,
  7289. directiveName, true);
  7290. bindings.isolateScope = {};
  7291. } else {
  7292. bindings.isolateScope = parseIsolateBindings(directive.scope,
  7293. directiveName, false);
  7294. }
  7295. }
  7296. if (isObject(directive.bindToController)) {
  7297. bindings.bindToController =
  7298. parseIsolateBindings(directive.bindToController, directiveName, true);
  7299. }
  7300. if (bindings.bindToController && !directive.controller) {
  7301. // There is no controller
  7302. throw $compileMinErr('noctrl',
  7303. 'Cannot bind to controller without directive \'{0}\'s controller.',
  7304. directiveName);
  7305. }
  7306. return bindings;
  7307. }
  7308. function assertValidDirectiveName(name) {
  7309. var letter = name.charAt(0);
  7310. if (!letter || letter !== lowercase(letter)) {
  7311. throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
  7312. }
  7313. if (name !== name.trim()) {
  7314. throw $compileMinErr('baddir',
  7315. 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
  7316. name);
  7317. }
  7318. }
  7319. function getDirectiveRequire(directive) {
  7320. var require = directive.require || (directive.controller && directive.name);
  7321. if (!isArray(require) && isObject(require)) {
  7322. forEach(require, function(value, key) {
  7323. var match = value.match(REQUIRE_PREFIX_REGEXP);
  7324. var name = value.substring(match[0].length);
  7325. if (!name) require[key] = match[0] + key;
  7326. });
  7327. }
  7328. return require;
  7329. }
  7330. function getDirectiveRestrict(restrict, name) {
  7331. if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
  7332. throw $compileMinErr('badrestrict',
  7333. 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
  7334. restrict,
  7335. name);
  7336. }
  7337. return restrict || 'EA';
  7338. }
  7339. /**
  7340. * @ngdoc method
  7341. * @name $compileProvider#directive
  7342. * @kind function
  7343. *
  7344. * @description
  7345. * Register a new directive with the compiler.
  7346. *
  7347. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  7348. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  7349. * names and the values are the factories.
  7350. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  7351. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  7352. * @returns {ng.$compileProvider} Self for chaining.
  7353. */
  7354. this.directive = function registerDirective(name, directiveFactory) {
  7355. assertArg(name, 'name');
  7356. assertNotHasOwnProperty(name, 'directive');
  7357. if (isString(name)) {
  7358. assertValidDirectiveName(name);
  7359. assertArg(directiveFactory, 'directiveFactory');
  7360. if (!hasDirectives.hasOwnProperty(name)) {
  7361. hasDirectives[name] = [];
  7362. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  7363. function($injector, $exceptionHandler) {
  7364. var directives = [];
  7365. forEach(hasDirectives[name], function(directiveFactory, index) {
  7366. try {
  7367. var directive = $injector.invoke(directiveFactory);
  7368. if (isFunction(directive)) {
  7369. directive = { compile: valueFn(directive) };
  7370. } else if (!directive.compile && directive.link) {
  7371. directive.compile = valueFn(directive.link);
  7372. }
  7373. directive.priority = directive.priority || 0;
  7374. directive.index = index;
  7375. directive.name = directive.name || name;
  7376. directive.require = getDirectiveRequire(directive);
  7377. directive.restrict = getDirectiveRestrict(directive.restrict, name);
  7378. directive.$$moduleName = directiveFactory.$$moduleName;
  7379. directives.push(directive);
  7380. } catch (e) {
  7381. $exceptionHandler(e);
  7382. }
  7383. });
  7384. return directives;
  7385. }]);
  7386. }
  7387. hasDirectives[name].push(directiveFactory);
  7388. } else {
  7389. forEach(name, reverseParams(registerDirective));
  7390. }
  7391. return this;
  7392. };
  7393. /**
  7394. * @ngdoc method
  7395. * @name $compileProvider#component
  7396. * @module ng
  7397. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  7398. * @param {Object} options Component definition object (a simplified
  7399. * {@link ng.$compile#directive-definition-object directive definition object}),
  7400. * with the following properties (all optional):
  7401. *
  7402. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  7403. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  7404. * registered controller} if passed as a string. An empty `noop` function by default.
  7405. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  7406. * If present, the controller will be published to scope under the `controllerAs` name.
  7407. * If not present, this will default to be `$ctrl`.
  7408. * - `template` – `{string=|function()=}` – html template as a string or a function that
  7409. * returns an html template as a string which should be used as the contents of this component.
  7410. * Empty string by default.
  7411. *
  7412. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  7413. * the following locals:
  7414. *
  7415. * - `$element` - Current element
  7416. * - `$attrs` - Current attributes object for the element
  7417. *
  7418. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  7419. * template that should be used as the contents of this component.
  7420. *
  7421. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  7422. * the following locals:
  7423. *
  7424. * - `$element` - Current element
  7425. * - `$attrs` - Current attributes object for the element
  7426. *
  7427. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  7428. * Component properties are always bound to the component controller and not to the scope.
  7429. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  7430. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  7431. * Disabled by default.
  7432. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  7433. * this component's controller. The object keys specify the property names under which the required
  7434. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  7435. * - `$...` – additional properties to attach to the directive factory function and the controller
  7436. * constructor function. (This is used by the component router to annotate)
  7437. *
  7438. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  7439. * @description
  7440. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  7441. * type of directive, which represents a self-contained UI component in your application. Such components
  7442. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  7443. *
  7444. * Component definitions are very simple and do not require as much configuration as defining general
  7445. * directives. Component definitions usually consist only of a template and a controller backing it.
  7446. *
  7447. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  7448. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  7449. *
  7450. * Here are a few examples of how you would usually define components:
  7451. *
  7452. * ```js
  7453. * var myMod = angular.module(...);
  7454. * myMod.component('myComp', {
  7455. * template: '<div>My name is {{$ctrl.name}}</div>',
  7456. * controller: function() {
  7457. * this.name = 'shahar';
  7458. * }
  7459. * });
  7460. *
  7461. * myMod.component('myComp', {
  7462. * template: '<div>My name is {{$ctrl.name}}</div>',
  7463. * bindings: {name: '@'}
  7464. * });
  7465. *
  7466. * myMod.component('myComp', {
  7467. * templateUrl: 'views/my-comp.html',
  7468. * controller: 'MyCtrl',
  7469. * controllerAs: 'ctrl',
  7470. * bindings: {name: '@'}
  7471. * });
  7472. *
  7473. * ```
  7474. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  7475. *
  7476. * <br />
  7477. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  7478. */
  7479. this.component = function registerComponent(name, options) {
  7480. var controller = options.controller || function() {};
  7481. function factory($injector) {
  7482. function makeInjectable(fn) {
  7483. if (isFunction(fn) || isArray(fn)) {
  7484. return /** @this */ function(tElement, tAttrs) {
  7485. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  7486. };
  7487. } else {
  7488. return fn;
  7489. }
  7490. }
  7491. var template = (!options.template && !options.templateUrl ? '' : options.template);
  7492. var ddo = {
  7493. controller: controller,
  7494. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  7495. template: makeInjectable(template),
  7496. templateUrl: makeInjectable(options.templateUrl),
  7497. transclude: options.transclude,
  7498. scope: {},
  7499. bindToController: options.bindings || {},
  7500. restrict: 'E',
  7501. require: options.require
  7502. };
  7503. // Copy annotations (starting with $) over to the DDO
  7504. forEach(options, function(val, key) {
  7505. if (key.charAt(0) === '$') ddo[key] = val;
  7506. });
  7507. return ddo;
  7508. }
  7509. // TODO(pete) remove the following `forEach` before we release 1.6.0
  7510. // The component-router@0.2.0 looks for the annotations on the controller constructor
  7511. // Nothing in Angular looks for annotations on the factory function but we can't remove
  7512. // it from 1.5.x yet.
  7513. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  7514. // These could be used by libraries such as the new component router
  7515. forEach(options, function(val, key) {
  7516. if (key.charAt(0) === '$') {
  7517. factory[key] = val;
  7518. // Don't try to copy over annotations to named controller
  7519. if (isFunction(controller)) controller[key] = val;
  7520. }
  7521. });
  7522. factory.$inject = ['$injector'];
  7523. return this.directive(name, factory);
  7524. };
  7525. /**
  7526. * @ngdoc method
  7527. * @name $compileProvider#aHrefSanitizationWhitelist
  7528. * @kind function
  7529. *
  7530. * @description
  7531. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7532. * urls during a[href] sanitization.
  7533. *
  7534. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  7535. *
  7536. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  7537. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  7538. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7539. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7540. *
  7541. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7542. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7543. * chaining otherwise.
  7544. */
  7545. this.aHrefSanitizationWhitelist = function(regexp) {
  7546. if (isDefined(regexp)) {
  7547. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  7548. return this;
  7549. } else {
  7550. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  7551. }
  7552. };
  7553. /**
  7554. * @ngdoc method
  7555. * @name $compileProvider#imgSrcSanitizationWhitelist
  7556. * @kind function
  7557. *
  7558. * @description
  7559. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7560. * urls during img[src] sanitization.
  7561. *
  7562. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  7563. *
  7564. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7565. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7566. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7567. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7568. *
  7569. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7570. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7571. * chaining otherwise.
  7572. */
  7573. this.imgSrcSanitizationWhitelist = function(regexp) {
  7574. if (isDefined(regexp)) {
  7575. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7576. return this;
  7577. } else {
  7578. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7579. }
  7580. };
  7581. /**
  7582. * @ngdoc method
  7583. * @name $compileProvider#debugInfoEnabled
  7584. *
  7585. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7586. * current debugInfoEnabled state
  7587. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7588. *
  7589. * @kind function
  7590. *
  7591. * @description
  7592. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7593. * binding information and a reference to the current scope on to DOM elements.
  7594. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7595. * * `ng-binding` CSS class
  7596. * * `$binding` data property containing an array of the binding expressions
  7597. *
  7598. * You may want to disable this in production for a significant performance boost. See
  7599. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7600. *
  7601. * The default value is true.
  7602. */
  7603. var debugInfoEnabled = true;
  7604. this.debugInfoEnabled = function(enabled) {
  7605. if (isDefined(enabled)) {
  7606. debugInfoEnabled = enabled;
  7607. return this;
  7608. }
  7609. return debugInfoEnabled;
  7610. };
  7611. /**
  7612. * @ngdoc method
  7613. * @name $compileProvider#preAssignBindingsEnabled
  7614. *
  7615. * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the
  7616. * current preAssignBindingsEnabled state
  7617. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7618. *
  7619. * @kind function
  7620. *
  7621. * @description
  7622. * Call this method to enable/disable whether directive controllers are assigned bindings before
  7623. * calling the controller's constructor.
  7624. * If enabled (true), the compiler assigns the value of each of the bindings to the
  7625. * properties of the controller object before the constructor of this object is called.
  7626. *
  7627. * If disabled (false), the compiler calls the constructor first before assigning bindings.
  7628. *
  7629. * The default value is false.
  7630. *
  7631. * @deprecated
  7632. * sinceVersion="1.6.0"
  7633. * removeVersion="1.7.0"
  7634. *
  7635. * This method and the option to assign the bindings before calling the controller's constructor
  7636. * will be removed in v1.7.0.
  7637. */
  7638. var preAssignBindingsEnabled = false;
  7639. this.preAssignBindingsEnabled = function(enabled) {
  7640. if (isDefined(enabled)) {
  7641. preAssignBindingsEnabled = enabled;
  7642. return this;
  7643. }
  7644. return preAssignBindingsEnabled;
  7645. };
  7646. var TTL = 10;
  7647. /**
  7648. * @ngdoc method
  7649. * @name $compileProvider#onChangesTtl
  7650. * @description
  7651. *
  7652. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7653. * assuming that the model is unstable.
  7654. *
  7655. * The current default is 10 iterations.
  7656. *
  7657. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7658. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7659. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7660. * the `$onChanges` hook execution.
  7661. *
  7662. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7663. *
  7664. * @param {number} limit The number of `$onChanges` hook iterations.
  7665. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7666. */
  7667. this.onChangesTtl = function(value) {
  7668. if (arguments.length) {
  7669. TTL = value;
  7670. return this;
  7671. }
  7672. return TTL;
  7673. };
  7674. var commentDirectivesEnabledConfig = true;
  7675. /**
  7676. * @ngdoc method
  7677. * @name $compileProvider#commentDirectivesEnabled
  7678. * @description
  7679. *
  7680. * It indicates to the compiler
  7681. * whether or not directives on comments should be compiled.
  7682. * Defaults to `true`.
  7683. *
  7684. * Calling this function with false disables the compilation of directives
  7685. * on comments for the whole application.
  7686. * This results in a compilation performance gain,
  7687. * as the compiler doesn't have to check comments when looking for directives.
  7688. * This should however only be used if you are sure that no comment directives are used in
  7689. * the application (including any 3rd party directives).
  7690. *
  7691. * @param {boolean} enabled `false` if the compiler may ignore directives on comments
  7692. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7693. */
  7694. this.commentDirectivesEnabled = function(value) {
  7695. if (arguments.length) {
  7696. commentDirectivesEnabledConfig = value;
  7697. return this;
  7698. }
  7699. return commentDirectivesEnabledConfig;
  7700. };
  7701. var cssClassDirectivesEnabledConfig = true;
  7702. /**
  7703. * @ngdoc method
  7704. * @name $compileProvider#cssClassDirectivesEnabled
  7705. * @description
  7706. *
  7707. * It indicates to the compiler
  7708. * whether or not directives on element classes should be compiled.
  7709. * Defaults to `true`.
  7710. *
  7711. * Calling this function with false disables the compilation of directives
  7712. * on element classes for the whole application.
  7713. * This results in a compilation performance gain,
  7714. * as the compiler doesn't have to check element classes when looking for directives.
  7715. * This should however only be used if you are sure that no class directives are used in
  7716. * the application (including any 3rd party directives).
  7717. *
  7718. * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
  7719. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7720. */
  7721. this.cssClassDirectivesEnabled = function(value) {
  7722. if (arguments.length) {
  7723. cssClassDirectivesEnabledConfig = value;
  7724. return this;
  7725. }
  7726. return cssClassDirectivesEnabledConfig;
  7727. };
  7728. this.$get = [
  7729. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7730. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7731. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7732. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7733. var SIMPLE_ATTR_NAME = /^\w/;
  7734. var specialAttrHolder = window.document.createElement('div');
  7735. var commentDirectivesEnabled = commentDirectivesEnabledConfig;
  7736. var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
  7737. var onChangesTtl = TTL;
  7738. // The onChanges hooks should all be run together in a single digest
  7739. // When changes occur, the call to trigger their hooks will be added to this queue
  7740. var onChangesQueue;
  7741. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7742. function flushOnChangesQueue() {
  7743. try {
  7744. if (!(--onChangesTtl)) {
  7745. // We have hit the TTL limit so reset everything
  7746. onChangesQueue = undefined;
  7747. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7748. }
  7749. // We must run this hook in an apply since the $$postDigest runs outside apply
  7750. $rootScope.$apply(function() {
  7751. var errors = [];
  7752. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7753. try {
  7754. onChangesQueue[i]();
  7755. } catch (e) {
  7756. errors.push(e);
  7757. }
  7758. }
  7759. // Reset the queue to trigger a new schedule next time there is a change
  7760. onChangesQueue = undefined;
  7761. if (errors.length) {
  7762. throw errors;
  7763. }
  7764. });
  7765. } finally {
  7766. onChangesTtl++;
  7767. }
  7768. }
  7769. function Attributes(element, attributesToCopy) {
  7770. if (attributesToCopy) {
  7771. var keys = Object.keys(attributesToCopy);
  7772. var i, l, key;
  7773. for (i = 0, l = keys.length; i < l; i++) {
  7774. key = keys[i];
  7775. this[key] = attributesToCopy[key];
  7776. }
  7777. } else {
  7778. this.$attr = {};
  7779. }
  7780. this.$$element = element;
  7781. }
  7782. Attributes.prototype = {
  7783. /**
  7784. * @ngdoc method
  7785. * @name $compile.directive.Attributes#$normalize
  7786. * @kind function
  7787. *
  7788. * @description
  7789. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7790. * `data-`) to its normalized, camelCase form.
  7791. *
  7792. * Also there is special case for Moz prefix starting with upper case letter.
  7793. *
  7794. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7795. *
  7796. * @param {string} name Name to normalize
  7797. */
  7798. $normalize: directiveNormalize,
  7799. /**
  7800. * @ngdoc method
  7801. * @name $compile.directive.Attributes#$addClass
  7802. * @kind function
  7803. *
  7804. * @description
  7805. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7806. * are enabled then an animation will be triggered for the class addition.
  7807. *
  7808. * @param {string} classVal The className value that will be added to the element
  7809. */
  7810. $addClass: function(classVal) {
  7811. if (classVal && classVal.length > 0) {
  7812. $animate.addClass(this.$$element, classVal);
  7813. }
  7814. },
  7815. /**
  7816. * @ngdoc method
  7817. * @name $compile.directive.Attributes#$removeClass
  7818. * @kind function
  7819. *
  7820. * @description
  7821. * Removes the CSS class value specified by the classVal parameter from the element. If
  7822. * animations are enabled then an animation will be triggered for the class removal.
  7823. *
  7824. * @param {string} classVal The className value that will be removed from the element
  7825. */
  7826. $removeClass: function(classVal) {
  7827. if (classVal && classVal.length > 0) {
  7828. $animate.removeClass(this.$$element, classVal);
  7829. }
  7830. },
  7831. /**
  7832. * @ngdoc method
  7833. * @name $compile.directive.Attributes#$updateClass
  7834. * @kind function
  7835. *
  7836. * @description
  7837. * Adds and removes the appropriate CSS class values to the element based on the difference
  7838. * between the new and old CSS class values (specified as newClasses and oldClasses).
  7839. *
  7840. * @param {string} newClasses The current CSS className value
  7841. * @param {string} oldClasses The former CSS className value
  7842. */
  7843. $updateClass: function(newClasses, oldClasses) {
  7844. var toAdd = tokenDifference(newClasses, oldClasses);
  7845. if (toAdd && toAdd.length) {
  7846. $animate.addClass(this.$$element, toAdd);
  7847. }
  7848. var toRemove = tokenDifference(oldClasses, newClasses);
  7849. if (toRemove && toRemove.length) {
  7850. $animate.removeClass(this.$$element, toRemove);
  7851. }
  7852. },
  7853. /**
  7854. * Set a normalized attribute on the element in a way such that all directives
  7855. * can share the attribute. This function properly handles boolean attributes.
  7856. * @param {string} key Normalized key. (ie ngAttribute)
  7857. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  7858. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  7859. * Defaults to true.
  7860. * @param {string=} attrName Optional none normalized name. Defaults to key.
  7861. */
  7862. $set: function(key, value, writeAttr, attrName) {
  7863. // TODO: decide whether or not to throw an error if "class"
  7864. //is set through this function since it may cause $updateClass to
  7865. //become unstable.
  7866. var node = this.$$element[0],
  7867. booleanKey = getBooleanAttrName(node, key),
  7868. aliasedKey = getAliasedAttrName(key),
  7869. observer = key,
  7870. nodeName;
  7871. if (booleanKey) {
  7872. this.$$element.prop(key, value);
  7873. attrName = booleanKey;
  7874. } else if (aliasedKey) {
  7875. this[aliasedKey] = value;
  7876. observer = aliasedKey;
  7877. }
  7878. this[key] = value;
  7879. // translate normalized key to actual key
  7880. if (attrName) {
  7881. this.$attr[key] = attrName;
  7882. } else {
  7883. attrName = this.$attr[key];
  7884. if (!attrName) {
  7885. this.$attr[key] = attrName = snake_case(key, '-');
  7886. }
  7887. }
  7888. nodeName = nodeName_(this.$$element);
  7889. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  7890. (nodeName === 'img' && key === 'src')) {
  7891. // sanitize a[href] and img[src] values
  7892. this[key] = value = $$sanitizeUri(value, key === 'src');
  7893. } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
  7894. // sanitize img[srcset] values
  7895. var result = '';
  7896. // first check if there are spaces because it's not the same pattern
  7897. var trimmedSrcset = trim(value);
  7898. // ( 999x ,| 999w ,| ,|, )
  7899. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  7900. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  7901. // split srcset into tuple of uri and descriptor except for the last item
  7902. var rawUris = trimmedSrcset.split(pattern);
  7903. // for each tuples
  7904. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  7905. for (var i = 0; i < nbrUrisWith2parts; i++) {
  7906. var innerIdx = i * 2;
  7907. // sanitize the uri
  7908. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  7909. // add the descriptor
  7910. result += (' ' + trim(rawUris[innerIdx + 1]));
  7911. }
  7912. // split the last item into uri and descriptor
  7913. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  7914. // sanitize the last uri
  7915. result += $$sanitizeUri(trim(lastTuple[0]), true);
  7916. // and add the last descriptor if any
  7917. if (lastTuple.length === 2) {
  7918. result += (' ' + trim(lastTuple[1]));
  7919. }
  7920. this[key] = value = result;
  7921. }
  7922. if (writeAttr !== false) {
  7923. if (value === null || isUndefined(value)) {
  7924. this.$$element.removeAttr(attrName);
  7925. } else {
  7926. if (SIMPLE_ATTR_NAME.test(attrName)) {
  7927. this.$$element.attr(attrName, value);
  7928. } else {
  7929. setSpecialAttr(this.$$element[0], attrName, value);
  7930. }
  7931. }
  7932. }
  7933. // fire observers
  7934. var $$observers = this.$$observers;
  7935. if ($$observers) {
  7936. forEach($$observers[observer], function(fn) {
  7937. try {
  7938. fn(value);
  7939. } catch (e) {
  7940. $exceptionHandler(e);
  7941. }
  7942. });
  7943. }
  7944. },
  7945. /**
  7946. * @ngdoc method
  7947. * @name $compile.directive.Attributes#$observe
  7948. * @kind function
  7949. *
  7950. * @description
  7951. * Observes an interpolated attribute.
  7952. *
  7953. * The observer function will be invoked once during the next `$digest` following
  7954. * compilation. The observer is then invoked whenever the interpolated value
  7955. * changes.
  7956. *
  7957. * @param {string} key Normalized key. (ie ngAttribute) .
  7958. * @param {function(interpolatedValue)} fn Function that will be called whenever
  7959. the interpolated value of the attribute changes.
  7960. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  7961. * guide} for more info.
  7962. * @returns {function()} Returns a deregistration function for this observer.
  7963. */
  7964. $observe: function(key, fn) {
  7965. var attrs = this,
  7966. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  7967. listeners = ($$observers[key] || ($$observers[key] = []));
  7968. listeners.push(fn);
  7969. $rootScope.$evalAsync(function() {
  7970. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  7971. // no one registered attribute interpolation function, so lets call it manually
  7972. fn(attrs[key]);
  7973. }
  7974. });
  7975. return function() {
  7976. arrayRemove(listeners, fn);
  7977. };
  7978. }
  7979. };
  7980. function setSpecialAttr(element, attrName, value) {
  7981. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  7982. // so we have to jump through some hoops to get such an attribute
  7983. // https://github.com/angular/angular.js/pull/13318
  7984. specialAttrHolder.innerHTML = '<span ' + attrName + '>';
  7985. var attributes = specialAttrHolder.firstChild.attributes;
  7986. var attribute = attributes[0];
  7987. // We have to remove the attribute from its container element before we can add it to the destination element
  7988. attributes.removeNamedItem(attribute.name);
  7989. attribute.value = value;
  7990. element.attributes.setNamedItem(attribute);
  7991. }
  7992. function safeAddClass($element, className) {
  7993. try {
  7994. $element.addClass(className);
  7995. } catch (e) {
  7996. // ignore, since it means that we are trying to set class on
  7997. // SVG element, where class name is read-only.
  7998. }
  7999. }
  8000. var startSymbol = $interpolate.startSymbol(),
  8001. endSymbol = $interpolate.endSymbol(),
  8002. denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
  8003. ? identity
  8004. : function denormalizeTemplate(template) {
  8005. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  8006. },
  8007. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  8008. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  8009. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  8010. var bindings = $element.data('$binding') || [];
  8011. if (isArray(binding)) {
  8012. bindings = bindings.concat(binding);
  8013. } else {
  8014. bindings.push(binding);
  8015. }
  8016. $element.data('$binding', bindings);
  8017. } : noop;
  8018. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  8019. safeAddClass($element, 'ng-binding');
  8020. } : noop;
  8021. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  8022. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  8023. $element.data(dataName, scope);
  8024. } : noop;
  8025. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  8026. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  8027. } : noop;
  8028. compile.$$createComment = function(directiveName, comment) {
  8029. var content = '';
  8030. if (debugInfoEnabled) {
  8031. content = ' ' + (directiveName || '') + ': ';
  8032. if (comment) content += comment + ' ';
  8033. }
  8034. return window.document.createComment(content);
  8035. };
  8036. return compile;
  8037. //================================
  8038. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  8039. previousCompileContext) {
  8040. if (!($compileNodes instanceof jqLite)) {
  8041. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  8042. // modify it.
  8043. $compileNodes = jqLite($compileNodes);
  8044. }
  8045. var compositeLinkFn =
  8046. compileNodes($compileNodes, transcludeFn, $compileNodes,
  8047. maxPriority, ignoreDirective, previousCompileContext);
  8048. compile.$$addScopeClass($compileNodes);
  8049. var namespace = null;
  8050. return function publicLinkFn(scope, cloneConnectFn, options) {
  8051. if (!$compileNodes) {
  8052. throw $compileMinErr('multilink', 'This element has already been linked.');
  8053. }
  8054. assertArg(scope, 'scope');
  8055. if (previousCompileContext && previousCompileContext.needsNewScope) {
  8056. // A parent directive did a replace and a directive on this element asked
  8057. // for transclusion, which caused us to lose a layer of element on which
  8058. // we could hold the new transclusion scope, so we will create it manually
  8059. // here.
  8060. scope = scope.$parent.$new();
  8061. }
  8062. options = options || {};
  8063. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  8064. transcludeControllers = options.transcludeControllers,
  8065. futureParentElement = options.futureParentElement;
  8066. // When `parentBoundTranscludeFn` is passed, it is a
  8067. // `controllersBoundTransclude` function (it was previously passed
  8068. // as `transclude` to directive.link) so we must unwrap it to get
  8069. // its `boundTranscludeFn`
  8070. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  8071. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  8072. }
  8073. if (!namespace) {
  8074. namespace = detectNamespaceForChildElements(futureParentElement);
  8075. }
  8076. var $linkNode;
  8077. if (namespace !== 'html') {
  8078. // When using a directive with replace:true and templateUrl the $compileNodes
  8079. // (or a child element inside of them)
  8080. // might change, so we need to recreate the namespace adapted compileNodes
  8081. // for call to the link function.
  8082. // Note: This will already clone the nodes...
  8083. $linkNode = jqLite(
  8084. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  8085. );
  8086. } else if (cloneConnectFn) {
  8087. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  8088. // and sometimes changes the structure of the DOM.
  8089. $linkNode = JQLitePrototype.clone.call($compileNodes);
  8090. } else {
  8091. $linkNode = $compileNodes;
  8092. }
  8093. if (transcludeControllers) {
  8094. for (var controllerName in transcludeControllers) {
  8095. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  8096. }
  8097. }
  8098. compile.$$addScopeInfo($linkNode, scope);
  8099. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  8100. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  8101. if (!cloneConnectFn) {
  8102. $compileNodes = compositeLinkFn = null;
  8103. }
  8104. return $linkNode;
  8105. };
  8106. }
  8107. function detectNamespaceForChildElements(parentElement) {
  8108. // TODO: Make this detect MathML as well...
  8109. var node = parentElement && parentElement[0];
  8110. if (!node) {
  8111. return 'html';
  8112. } else {
  8113. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  8114. }
  8115. }
  8116. /**
  8117. * Compile function matches each node in nodeList against the directives. Once all directives
  8118. * for a particular node are collected their compile functions are executed. The compile
  8119. * functions return values - the linking functions - are combined into a composite linking
  8120. * function, which is the a linking function for the node.
  8121. *
  8122. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  8123. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8124. * scope argument is auto-generated to the new child of the transcluded parent scope.
  8125. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  8126. * the rootElement must be set the jqLite collection of the compile root. This is
  8127. * needed so that the jqLite collection items can be replaced with widgets.
  8128. * @param {number=} maxPriority Max directive priority.
  8129. * @returns {Function} A composite linking function of all of the matched directives or null.
  8130. */
  8131. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  8132. previousCompileContext) {
  8133. var linkFns = [],
  8134. // `nodeList` can be either an element's `.childNodes` (live NodeList)
  8135. // or a jqLite/jQuery collection or an array
  8136. notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
  8137. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  8138. for (var i = 0; i < nodeList.length; i++) {
  8139. attrs = new Attributes();
  8140. // Support: IE 11 only
  8141. // Workaround for #11781 and #14924
  8142. if (msie === 11) {
  8143. mergeConsecutiveTextNodes(nodeList, i, notLiveList);
  8144. }
  8145. // We must always refer to `nodeList[i]` hereafter,
  8146. // since the nodes can be replaced underneath us.
  8147. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  8148. ignoreDirective);
  8149. nodeLinkFn = (directives.length)
  8150. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  8151. null, [], [], previousCompileContext)
  8152. : null;
  8153. if (nodeLinkFn && nodeLinkFn.scope) {
  8154. compile.$$addScopeClass(attrs.$$element);
  8155. }
  8156. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  8157. !(childNodes = nodeList[i].childNodes) ||
  8158. !childNodes.length)
  8159. ? null
  8160. : compileNodes(childNodes,
  8161. nodeLinkFn ? (
  8162. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  8163. && nodeLinkFn.transclude) : transcludeFn);
  8164. if (nodeLinkFn || childLinkFn) {
  8165. linkFns.push(i, nodeLinkFn, childLinkFn);
  8166. linkFnFound = true;
  8167. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  8168. }
  8169. //use the previous context only for the first element in the virtual group
  8170. previousCompileContext = null;
  8171. }
  8172. // return a linking function if we have found anything, null otherwise
  8173. return linkFnFound ? compositeLinkFn : null;
  8174. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  8175. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  8176. var stableNodeList;
  8177. if (nodeLinkFnFound) {
  8178. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  8179. // offsets don't get screwed up
  8180. var nodeListLength = nodeList.length;
  8181. stableNodeList = new Array(nodeListLength);
  8182. // create a sparse array by only copying the elements which have a linkFn
  8183. for (i = 0; i < linkFns.length; i += 3) {
  8184. idx = linkFns[i];
  8185. stableNodeList[idx] = nodeList[idx];
  8186. }
  8187. } else {
  8188. stableNodeList = nodeList;
  8189. }
  8190. for (i = 0, ii = linkFns.length; i < ii;) {
  8191. node = stableNodeList[linkFns[i++]];
  8192. nodeLinkFn = linkFns[i++];
  8193. childLinkFn = linkFns[i++];
  8194. if (nodeLinkFn) {
  8195. if (nodeLinkFn.scope) {
  8196. childScope = scope.$new();
  8197. compile.$$addScopeInfo(jqLite(node), childScope);
  8198. } else {
  8199. childScope = scope;
  8200. }
  8201. if (nodeLinkFn.transcludeOnThisElement) {
  8202. childBoundTranscludeFn = createBoundTranscludeFn(
  8203. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  8204. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  8205. childBoundTranscludeFn = parentBoundTranscludeFn;
  8206. } else if (!parentBoundTranscludeFn && transcludeFn) {
  8207. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  8208. } else {
  8209. childBoundTranscludeFn = null;
  8210. }
  8211. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  8212. } else if (childLinkFn) {
  8213. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  8214. }
  8215. }
  8216. }
  8217. }
  8218. function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
  8219. var node = nodeList[idx];
  8220. var parent = node.parentNode;
  8221. var sibling;
  8222. if (node.nodeType !== NODE_TYPE_TEXT) {
  8223. return;
  8224. }
  8225. while (true) {
  8226. sibling = parent ? node.nextSibling : nodeList[idx + 1];
  8227. if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
  8228. break;
  8229. }
  8230. node.nodeValue = node.nodeValue + sibling.nodeValue;
  8231. if (sibling.parentNode) {
  8232. sibling.parentNode.removeChild(sibling);
  8233. }
  8234. if (notLiveList && sibling === nodeList[idx + 1]) {
  8235. nodeList.splice(idx + 1, 1);
  8236. }
  8237. }
  8238. }
  8239. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  8240. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  8241. if (!transcludedScope) {
  8242. transcludedScope = scope.$new(false, containingScope);
  8243. transcludedScope.$$transcluded = true;
  8244. }
  8245. return transcludeFn(transcludedScope, cloneFn, {
  8246. parentBoundTranscludeFn: previousBoundTranscludeFn,
  8247. transcludeControllers: controllers,
  8248. futureParentElement: futureParentElement
  8249. });
  8250. }
  8251. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  8252. // so that they are available inside the `controllersBoundTransclude` function
  8253. var boundSlots = boundTranscludeFn.$$slots = createMap();
  8254. for (var slotName in transcludeFn.$$slots) {
  8255. if (transcludeFn.$$slots[slotName]) {
  8256. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  8257. } else {
  8258. boundSlots[slotName] = null;
  8259. }
  8260. }
  8261. return boundTranscludeFn;
  8262. }
  8263. /**
  8264. * Looks for directives on the given node and adds them to the directive collection which is
  8265. * sorted.
  8266. *
  8267. * @param node Node to search.
  8268. * @param directives An array to which the directives are added to. This array is sorted before
  8269. * the function returns.
  8270. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  8271. * @param {number=} maxPriority Max directive priority.
  8272. */
  8273. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8274. var nodeType = node.nodeType,
  8275. attrsMap = attrs.$attr,
  8276. match,
  8277. nodeName,
  8278. className;
  8279. switch (nodeType) {
  8280. case NODE_TYPE_ELEMENT: /* Element */
  8281. nodeName = nodeName_(node);
  8282. // use the node name: <directive>
  8283. addDirective(directives,
  8284. directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
  8285. // iterate over the attributes
  8286. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  8287. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  8288. var attrStartName = false;
  8289. var attrEndName = false;
  8290. attr = nAttrs[j];
  8291. name = attr.name;
  8292. value = attr.value;
  8293. // support ngAttr attribute binding
  8294. ngAttrName = directiveNormalize(name);
  8295. isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
  8296. if (isNgAttr) {
  8297. name = name.replace(PREFIX_REGEXP, '')
  8298. .substr(8).replace(/_(.)/g, function(match, letter) {
  8299. return letter.toUpperCase();
  8300. });
  8301. }
  8302. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  8303. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  8304. attrStartName = name;
  8305. attrEndName = name.substr(0, name.length - 5) + 'end';
  8306. name = name.substr(0, name.length - 6);
  8307. }
  8308. nName = directiveNormalize(name.toLowerCase());
  8309. attrsMap[nName] = name;
  8310. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  8311. attrs[nName] = value;
  8312. if (getBooleanAttrName(node, nName)) {
  8313. attrs[nName] = true; // presence means true
  8314. }
  8315. }
  8316. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  8317. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  8318. attrEndName);
  8319. }
  8320. if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
  8321. // Hidden input elements can have strange behaviour when navigating back to the page
  8322. // This tells the browser not to try to cache and reinstate previous values
  8323. node.setAttribute('autocomplete', 'off');
  8324. }
  8325. // use class as directive
  8326. if (!cssClassDirectivesEnabled) break;
  8327. className = node.className;
  8328. if (isObject(className)) {
  8329. // Maybe SVGAnimatedString
  8330. className = className.animVal;
  8331. }
  8332. if (isString(className) && className !== '') {
  8333. while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
  8334. nName = directiveNormalize(match[2]);
  8335. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  8336. attrs[nName] = trim(match[3]);
  8337. }
  8338. className = className.substr(match.index + match[0].length);
  8339. }
  8340. }
  8341. break;
  8342. case NODE_TYPE_TEXT: /* Text Node */
  8343. addTextInterpolateDirective(directives, node.nodeValue);
  8344. break;
  8345. case NODE_TYPE_COMMENT: /* Comment */
  8346. if (!commentDirectivesEnabled) break;
  8347. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  8348. break;
  8349. }
  8350. directives.sort(byPriority);
  8351. return directives;
  8352. }
  8353. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8354. // function created because of performance, try/catch disables
  8355. // the optimization of the whole function #14848
  8356. try {
  8357. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  8358. if (match) {
  8359. var nName = directiveNormalize(match[1]);
  8360. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  8361. attrs[nName] = trim(match[2]);
  8362. }
  8363. }
  8364. } catch (e) {
  8365. // turns out that under some circumstances IE9 throws errors when one attempts to read
  8366. // comment's node value.
  8367. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  8368. }
  8369. }
  8370. /**
  8371. * Given a node with a directive-start it collects all of the siblings until it finds
  8372. * directive-end.
  8373. * @param node
  8374. * @param attrStart
  8375. * @param attrEnd
  8376. * @returns {*}
  8377. */
  8378. function groupScan(node, attrStart, attrEnd) {
  8379. var nodes = [];
  8380. var depth = 0;
  8381. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  8382. do {
  8383. if (!node) {
  8384. throw $compileMinErr('uterdir',
  8385. 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
  8386. attrStart, attrEnd);
  8387. }
  8388. if (node.nodeType === NODE_TYPE_ELEMENT) {
  8389. if (node.hasAttribute(attrStart)) depth++;
  8390. if (node.hasAttribute(attrEnd)) depth--;
  8391. }
  8392. nodes.push(node);
  8393. node = node.nextSibling;
  8394. } while (depth > 0);
  8395. } else {
  8396. nodes.push(node);
  8397. }
  8398. return jqLite(nodes);
  8399. }
  8400. /**
  8401. * Wrapper for linking function which converts normal linking function into a grouped
  8402. * linking function.
  8403. * @param linkFn
  8404. * @param attrStart
  8405. * @param attrEnd
  8406. * @returns {Function}
  8407. */
  8408. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  8409. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  8410. element = groupScan(element[0], attrStart, attrEnd);
  8411. return linkFn(scope, element, attrs, controllers, transcludeFn);
  8412. };
  8413. }
  8414. /**
  8415. * A function generator that is used to support both eager and lazy compilation
  8416. * linking function.
  8417. * @param eager
  8418. * @param $compileNodes
  8419. * @param transcludeFn
  8420. * @param maxPriority
  8421. * @param ignoreDirective
  8422. * @param previousCompileContext
  8423. * @returns {Function}
  8424. */
  8425. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  8426. var compiled;
  8427. if (eager) {
  8428. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8429. }
  8430. return /** @this */ function lazyCompilation() {
  8431. if (!compiled) {
  8432. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8433. // Null out all of these references in order to make them eligible for garbage collection
  8434. // since this is a potentially long lived closure
  8435. $compileNodes = transcludeFn = previousCompileContext = null;
  8436. }
  8437. return compiled.apply(this, arguments);
  8438. };
  8439. }
  8440. /**
  8441. * Once the directives have been collected, their compile functions are executed. This method
  8442. * is responsible for inlining directive templates as well as terminating the application
  8443. * of the directives if the terminal directive has been reached.
  8444. *
  8445. * @param {Array} directives Array of collected directives to execute their compile function.
  8446. * this needs to be pre-sorted by priority order.
  8447. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  8448. * @param {Object} templateAttrs The shared attribute function
  8449. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8450. * scope argument is auto-generated to the new
  8451. * child of the transcluded parent scope.
  8452. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  8453. * argument has the root jqLite array so that we can replace nodes
  8454. * on it.
  8455. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  8456. * compiling the transclusion.
  8457. * @param {Array.<Function>} preLinkFns
  8458. * @param {Array.<Function>} postLinkFns
  8459. * @param {Object} previousCompileContext Context used for previous compilation of the current
  8460. * node
  8461. * @returns {Function} linkFn
  8462. */
  8463. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  8464. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  8465. previousCompileContext) {
  8466. previousCompileContext = previousCompileContext || {};
  8467. var terminalPriority = -Number.MAX_VALUE,
  8468. newScopeDirective = previousCompileContext.newScopeDirective,
  8469. controllerDirectives = previousCompileContext.controllerDirectives,
  8470. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  8471. templateDirective = previousCompileContext.templateDirective,
  8472. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  8473. hasTranscludeDirective = false,
  8474. hasTemplate = false,
  8475. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  8476. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  8477. directive,
  8478. directiveName,
  8479. $template,
  8480. replaceDirective = originalReplaceDirective,
  8481. childTranscludeFn = transcludeFn,
  8482. linkFn,
  8483. didScanForMultipleTransclusion = false,
  8484. mightHaveMultipleTransclusionError = false,
  8485. directiveValue;
  8486. // executes all directives on the current element
  8487. for (var i = 0, ii = directives.length; i < ii; i++) {
  8488. directive = directives[i];
  8489. var attrStart = directive.$$start;
  8490. var attrEnd = directive.$$end;
  8491. // collect multiblock sections
  8492. if (attrStart) {
  8493. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  8494. }
  8495. $template = undefined;
  8496. if (terminalPriority > directive.priority) {
  8497. break; // prevent further processing of directives
  8498. }
  8499. directiveValue = directive.scope;
  8500. if (directiveValue) {
  8501. // skip the check for directives with async templates, we'll check the derived sync
  8502. // directive when the template arrives
  8503. if (!directive.templateUrl) {
  8504. if (isObject(directiveValue)) {
  8505. // This directive is trying to add an isolated scope.
  8506. // Check that there is no scope of any kind already
  8507. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  8508. directive, $compileNode);
  8509. newIsolateScopeDirective = directive;
  8510. } else {
  8511. // This directive is trying to add a child scope.
  8512. // Check that there is no isolated scope already
  8513. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  8514. $compileNode);
  8515. }
  8516. }
  8517. newScopeDirective = newScopeDirective || directive;
  8518. }
  8519. directiveName = directive.name;
  8520. // If we encounter a condition that can result in transclusion on the directive,
  8521. // then scan ahead in the remaining directives for others that may cause a multiple
  8522. // transclusion error to be thrown during the compilation process. If a matching directive
  8523. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  8524. // compile the `transclude` function rather than doing it lazily in order to throw
  8525. // exceptions at the correct time
  8526. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  8527. || (directive.transclude && !directive.$$tlb))) {
  8528. var candidateDirective;
  8529. for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
  8530. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  8531. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  8532. mightHaveMultipleTransclusionError = true;
  8533. break;
  8534. }
  8535. }
  8536. didScanForMultipleTransclusion = true;
  8537. }
  8538. if (!directive.templateUrl && directive.controller) {
  8539. controllerDirectives = controllerDirectives || createMap();
  8540. assertNoDuplicate('\'' + directiveName + '\' controller',
  8541. controllerDirectives[directiveName], directive, $compileNode);
  8542. controllerDirectives[directiveName] = directive;
  8543. }
  8544. directiveValue = directive.transclude;
  8545. if (directiveValue) {
  8546. hasTranscludeDirective = true;
  8547. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  8548. // This option should only be used by directives that know how to safely handle element transclusion,
  8549. // where the transcluded nodes are added or replaced after linking.
  8550. if (!directive.$$tlb) {
  8551. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  8552. nonTlbTranscludeDirective = directive;
  8553. }
  8554. if (directiveValue === 'element') {
  8555. hasElementTranscludeDirective = true;
  8556. terminalPriority = directive.priority;
  8557. $template = $compileNode;
  8558. $compileNode = templateAttrs.$$element =
  8559. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  8560. compileNode = $compileNode[0];
  8561. replaceWith(jqCollection, sliceArgs($template), compileNode);
  8562. // Support: Chrome < 50
  8563. // https://github.com/angular/angular.js/issues/14041
  8564. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  8565. // in the `replaceWith` function is improperly garbage collected despite still
  8566. // being referenced by the `parentNode` property of all of the child nodes. By adding
  8567. // a reference to the fragment via a different property, we can avoid that incorrect
  8568. // behavior.
  8569. // TODO: remove this line after Chrome 50 has been released
  8570. $template[0].$$parentNode = $template[0].parentNode;
  8571. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  8572. replaceDirective && replaceDirective.name, {
  8573. // Don't pass in:
  8574. // - controllerDirectives - otherwise we'll create duplicates controllers
  8575. // - newIsolateScopeDirective or templateDirective - combining templates with
  8576. // element transclusion doesn't make sense.
  8577. //
  8578. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  8579. // on the same element more than once.
  8580. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8581. });
  8582. } else {
  8583. var slots = createMap();
  8584. if (!isObject(directiveValue)) {
  8585. $template = jqLite(jqLiteClone(compileNode)).contents();
  8586. } else {
  8587. // We have transclusion slots,
  8588. // collect them up, compile them and store their transclusion functions
  8589. $template = [];
  8590. var slotMap = createMap();
  8591. var filledSlots = createMap();
  8592. // Parse the element selectors
  8593. forEach(directiveValue, function(elementSelector, slotName) {
  8594. // If an element selector starts with a ? then it is optional
  8595. var optional = (elementSelector.charAt(0) === '?');
  8596. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  8597. slotMap[elementSelector] = slotName;
  8598. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  8599. // Later when calling boundTransclusion functions with a slot name we only error if the
  8600. // slot is `undefined`
  8601. slots[slotName] = null;
  8602. // filledSlots contains `true` for all slots that are either optional or have been
  8603. // filled. This is used to check that we have not missed any required slots
  8604. filledSlots[slotName] = optional;
  8605. });
  8606. // Add the matching elements into their slot
  8607. forEach($compileNode.contents(), function(node) {
  8608. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  8609. if (slotName) {
  8610. filledSlots[slotName] = true;
  8611. slots[slotName] = slots[slotName] || [];
  8612. slots[slotName].push(node);
  8613. } else {
  8614. $template.push(node);
  8615. }
  8616. });
  8617. // Check for required slots that were not filled
  8618. forEach(filledSlots, function(filled, slotName) {
  8619. if (!filled) {
  8620. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  8621. }
  8622. });
  8623. for (var slotName in slots) {
  8624. if (slots[slotName]) {
  8625. // Only define a transclusion function if the slot was filled
  8626. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  8627. }
  8628. }
  8629. }
  8630. $compileNode.empty(); // clear contents
  8631. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  8632. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  8633. childTranscludeFn.$$slots = slots;
  8634. }
  8635. }
  8636. if (directive.template) {
  8637. hasTemplate = true;
  8638. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8639. templateDirective = directive;
  8640. directiveValue = (isFunction(directive.template))
  8641. ? directive.template($compileNode, templateAttrs)
  8642. : directive.template;
  8643. directiveValue = denormalizeTemplate(directiveValue);
  8644. if (directive.replace) {
  8645. replaceDirective = directive;
  8646. if (jqLiteIsTextNode(directiveValue)) {
  8647. $template = [];
  8648. } else {
  8649. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  8650. }
  8651. compileNode = $template[0];
  8652. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8653. throw $compileMinErr('tplrt',
  8654. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8655. directiveName, '');
  8656. }
  8657. replaceWith(jqCollection, $compileNode, compileNode);
  8658. var newTemplateAttrs = {$attr: {}};
  8659. // combine directives from the original node and from the template:
  8660. // - take the array of directives for this element
  8661. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  8662. // - collect directives from the template and sort them by priority
  8663. // - combine directives as: processed + template + unprocessed
  8664. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  8665. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  8666. if (newIsolateScopeDirective || newScopeDirective) {
  8667. // The original directive caused the current element to be replaced but this element
  8668. // also needs to have a new scope, so we need to tell the template directives
  8669. // that they would need to get their scope from further up, if they require transclusion
  8670. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  8671. }
  8672. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  8673. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  8674. ii = directives.length;
  8675. } else {
  8676. $compileNode.html(directiveValue);
  8677. }
  8678. }
  8679. if (directive.templateUrl) {
  8680. hasTemplate = true;
  8681. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8682. templateDirective = directive;
  8683. if (directive.replace) {
  8684. replaceDirective = directive;
  8685. }
  8686. // eslint-disable-next-line no-func-assign
  8687. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  8688. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  8689. controllerDirectives: controllerDirectives,
  8690. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  8691. newIsolateScopeDirective: newIsolateScopeDirective,
  8692. templateDirective: templateDirective,
  8693. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8694. });
  8695. ii = directives.length;
  8696. } else if (directive.compile) {
  8697. try {
  8698. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  8699. var context = directive.$$originalDirective || directive;
  8700. if (isFunction(linkFn)) {
  8701. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  8702. } else if (linkFn) {
  8703. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  8704. }
  8705. } catch (e) {
  8706. $exceptionHandler(e, startingTag($compileNode));
  8707. }
  8708. }
  8709. if (directive.terminal) {
  8710. nodeLinkFn.terminal = true;
  8711. terminalPriority = Math.max(terminalPriority, directive.priority);
  8712. }
  8713. }
  8714. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8715. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8716. nodeLinkFn.templateOnThisElement = hasTemplate;
  8717. nodeLinkFn.transclude = childTranscludeFn;
  8718. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8719. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8720. return nodeLinkFn;
  8721. ////////////////////
  8722. function addLinkFns(pre, post, attrStart, attrEnd) {
  8723. if (pre) {
  8724. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8725. pre.require = directive.require;
  8726. pre.directiveName = directiveName;
  8727. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8728. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8729. }
  8730. preLinkFns.push(pre);
  8731. }
  8732. if (post) {
  8733. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8734. post.require = directive.require;
  8735. post.directiveName = directiveName;
  8736. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8737. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8738. }
  8739. postLinkFns.push(post);
  8740. }
  8741. }
  8742. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8743. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8744. attrs, scopeBindingInfo;
  8745. if (compileNode === linkNode) {
  8746. attrs = templateAttrs;
  8747. $element = templateAttrs.$$element;
  8748. } else {
  8749. $element = jqLite(linkNode);
  8750. attrs = new Attributes($element, templateAttrs);
  8751. }
  8752. controllerScope = scope;
  8753. if (newIsolateScopeDirective) {
  8754. isolateScope = scope.$new(true);
  8755. } else if (newScopeDirective) {
  8756. controllerScope = scope.$parent;
  8757. }
  8758. if (boundTranscludeFn) {
  8759. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8760. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8761. transcludeFn = controllersBoundTransclude;
  8762. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8763. // expose the slots on the `$transclude` function
  8764. transcludeFn.isSlotFilled = function(slotName) {
  8765. return !!boundTranscludeFn.$$slots[slotName];
  8766. };
  8767. }
  8768. if (controllerDirectives) {
  8769. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8770. }
  8771. if (newIsolateScopeDirective) {
  8772. // Initialize isolate scope bindings for new isolate scope directive.
  8773. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8774. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8775. compile.$$addScopeClass($element, true);
  8776. isolateScope.$$isolateBindings =
  8777. newIsolateScopeDirective.$$isolateBindings;
  8778. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  8779. isolateScope.$$isolateBindings,
  8780. newIsolateScopeDirective);
  8781. if (scopeBindingInfo.removeWatches) {
  8782. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  8783. }
  8784. }
  8785. // Initialize bindToController bindings
  8786. for (var name in elementControllers) {
  8787. var controllerDirective = controllerDirectives[name];
  8788. var controller = elementControllers[name];
  8789. var bindings = controllerDirective.$$bindings.bindToController;
  8790. if (preAssignBindingsEnabled) {
  8791. if (bindings) {
  8792. controller.bindingInfo =
  8793. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8794. } else {
  8795. controller.bindingInfo = {};
  8796. }
  8797. var controllerResult = controller();
  8798. if (controllerResult !== controller.instance) {
  8799. // If the controller constructor has a return value, overwrite the instance
  8800. // from setupControllers
  8801. controller.instance = controllerResult;
  8802. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8803. if (controller.bindingInfo.removeWatches) {
  8804. controller.bindingInfo.removeWatches();
  8805. }
  8806. controller.bindingInfo =
  8807. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8808. }
  8809. } else {
  8810. controller.instance = controller();
  8811. $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
  8812. controller.bindingInfo =
  8813. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8814. }
  8815. }
  8816. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8817. forEach(controllerDirectives, function(controllerDirective, name) {
  8818. var require = controllerDirective.require;
  8819. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8820. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8821. }
  8822. });
  8823. // Handle the init and destroy lifecycle hooks on all controllers that have them
  8824. forEach(elementControllers, function(controller) {
  8825. var controllerInstance = controller.instance;
  8826. if (isFunction(controllerInstance.$onChanges)) {
  8827. try {
  8828. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  8829. } catch (e) {
  8830. $exceptionHandler(e);
  8831. }
  8832. }
  8833. if (isFunction(controllerInstance.$onInit)) {
  8834. try {
  8835. controllerInstance.$onInit();
  8836. } catch (e) {
  8837. $exceptionHandler(e);
  8838. }
  8839. }
  8840. if (isFunction(controllerInstance.$doCheck)) {
  8841. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  8842. controllerInstance.$doCheck();
  8843. }
  8844. if (isFunction(controllerInstance.$onDestroy)) {
  8845. controllerScope.$on('$destroy', function callOnDestroyHook() {
  8846. controllerInstance.$onDestroy();
  8847. });
  8848. }
  8849. });
  8850. // PRELINKING
  8851. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  8852. linkFn = preLinkFns[i];
  8853. invokeLinkFn(linkFn,
  8854. linkFn.isolateScope ? isolateScope : scope,
  8855. $element,
  8856. attrs,
  8857. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8858. transcludeFn
  8859. );
  8860. }
  8861. // RECURSION
  8862. // We only pass the isolate scope, if the isolate directive has a template,
  8863. // otherwise the child elements do not belong to the isolate directive.
  8864. var scopeToChild = scope;
  8865. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  8866. scopeToChild = isolateScope;
  8867. }
  8868. if (childLinkFn) {
  8869. childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  8870. }
  8871. // POSTLINKING
  8872. for (i = postLinkFns.length - 1; i >= 0; i--) {
  8873. linkFn = postLinkFns[i];
  8874. invokeLinkFn(linkFn,
  8875. linkFn.isolateScope ? isolateScope : scope,
  8876. $element,
  8877. attrs,
  8878. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8879. transcludeFn
  8880. );
  8881. }
  8882. // Trigger $postLink lifecycle hooks
  8883. forEach(elementControllers, function(controller) {
  8884. var controllerInstance = controller.instance;
  8885. if (isFunction(controllerInstance.$postLink)) {
  8886. controllerInstance.$postLink();
  8887. }
  8888. });
  8889. // This is the function that is injected as `$transclude`.
  8890. // Note: all arguments are optional!
  8891. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  8892. var transcludeControllers;
  8893. // No scope passed in:
  8894. if (!isScope(scope)) {
  8895. slotName = futureParentElement;
  8896. futureParentElement = cloneAttachFn;
  8897. cloneAttachFn = scope;
  8898. scope = undefined;
  8899. }
  8900. if (hasElementTranscludeDirective) {
  8901. transcludeControllers = elementControllers;
  8902. }
  8903. if (!futureParentElement) {
  8904. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  8905. }
  8906. if (slotName) {
  8907. // slotTranscludeFn can be one of three things:
  8908. // * a transclude function - a filled slot
  8909. // * `null` - an optional slot that was not filled
  8910. // * `undefined` - a slot that was not declared (i.e. invalid)
  8911. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  8912. if (slotTranscludeFn) {
  8913. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8914. } else if (isUndefined(slotTranscludeFn)) {
  8915. throw $compileMinErr('noslot',
  8916. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  8917. 'Element: {1}',
  8918. slotName, startingTag($element));
  8919. }
  8920. } else {
  8921. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8922. }
  8923. }
  8924. }
  8925. }
  8926. function getControllers(directiveName, require, $element, elementControllers) {
  8927. var value;
  8928. if (isString(require)) {
  8929. var match = require.match(REQUIRE_PREFIX_REGEXP);
  8930. var name = require.substring(match[0].length);
  8931. var inheritType = match[1] || match[3];
  8932. var optional = match[2] === '?';
  8933. //If only parents then start at the parent element
  8934. if (inheritType === '^^') {
  8935. $element = $element.parent();
  8936. //Otherwise attempt getting the controller from elementControllers in case
  8937. //the element is transcluded (and has no data) and to avoid .data if possible
  8938. } else {
  8939. value = elementControllers && elementControllers[name];
  8940. value = value && value.instance;
  8941. }
  8942. if (!value) {
  8943. var dataName = '$' + name + 'Controller';
  8944. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  8945. }
  8946. if (!value && !optional) {
  8947. throw $compileMinErr('ctreq',
  8948. 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
  8949. name, directiveName);
  8950. }
  8951. } else if (isArray(require)) {
  8952. value = [];
  8953. for (var i = 0, ii = require.length; i < ii; i++) {
  8954. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  8955. }
  8956. } else if (isObject(require)) {
  8957. value = {};
  8958. forEach(require, function(controller, property) {
  8959. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  8960. });
  8961. }
  8962. return value || null;
  8963. }
  8964. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  8965. var elementControllers = createMap();
  8966. for (var controllerKey in controllerDirectives) {
  8967. var directive = controllerDirectives[controllerKey];
  8968. var locals = {
  8969. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  8970. $element: $element,
  8971. $attrs: attrs,
  8972. $transclude: transcludeFn
  8973. };
  8974. var controller = directive.controller;
  8975. if (controller === '@') {
  8976. controller = attrs[directive.name];
  8977. }
  8978. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  8979. // For directives with element transclusion the element is a comment.
  8980. // In this case .data will not attach any data.
  8981. // Instead, we save the controllers for the element in a local hash and attach to .data
  8982. // later, once we have the actual element.
  8983. elementControllers[directive.name] = controllerInstance;
  8984. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  8985. }
  8986. return elementControllers;
  8987. }
  8988. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  8989. // or child scope created. For instance:
  8990. // * if the directive has been pulled into a template because another directive with a higher priority
  8991. // asked for element transclusion
  8992. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  8993. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  8994. function markDirectiveScope(directives, isolateScope, newScope) {
  8995. for (var j = 0, jj = directives.length; j < jj; j++) {
  8996. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  8997. }
  8998. }
  8999. /**
  9000. * looks up the directive and decorates it with exception handling and proper parameters. We
  9001. * call this the boundDirective.
  9002. *
  9003. * @param {string} name name of the directive to look up.
  9004. * @param {string} location The directive must be found in specific format.
  9005. * String containing any of theses characters:
  9006. *
  9007. * * `E`: element name
  9008. * * `A': attribute
  9009. * * `C`: class
  9010. * * `M`: comment
  9011. * @returns {boolean} true if directive was added.
  9012. */
  9013. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  9014. endAttrName) {
  9015. if (name === ignoreDirective) return null;
  9016. var match = null;
  9017. if (hasDirectives.hasOwnProperty(name)) {
  9018. for (var directive, directives = $injector.get(name + Suffix),
  9019. i = 0, ii = directives.length; i < ii; i++) {
  9020. directive = directives[i];
  9021. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  9022. directive.restrict.indexOf(location) !== -1) {
  9023. if (startAttrName) {
  9024. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  9025. }
  9026. if (!directive.$$bindings) {
  9027. var bindings = directive.$$bindings =
  9028. parseDirectiveBindings(directive, directive.name);
  9029. if (isObject(bindings.isolateScope)) {
  9030. directive.$$isolateBindings = bindings.isolateScope;
  9031. }
  9032. }
  9033. tDirectives.push(directive);
  9034. match = directive;
  9035. }
  9036. }
  9037. }
  9038. return match;
  9039. }
  9040. /**
  9041. * looks up the directive and returns true if it is a multi-element directive,
  9042. * and therefore requires DOM nodes between -start and -end markers to be grouped
  9043. * together.
  9044. *
  9045. * @param {string} name name of the directive to look up.
  9046. * @returns true if directive was registered as multi-element.
  9047. */
  9048. function directiveIsMultiElement(name) {
  9049. if (hasDirectives.hasOwnProperty(name)) {
  9050. for (var directive, directives = $injector.get(name + Suffix),
  9051. i = 0, ii = directives.length; i < ii; i++) {
  9052. directive = directives[i];
  9053. if (directive.multiElement) {
  9054. return true;
  9055. }
  9056. }
  9057. }
  9058. return false;
  9059. }
  9060. /**
  9061. * When the element is replaced with HTML template then the new attributes
  9062. * on the template need to be merged with the existing attributes in the DOM.
  9063. * The desired effect is to have both of the attributes present.
  9064. *
  9065. * @param {object} dst destination attributes (original DOM)
  9066. * @param {object} src source attributes (from the directive template)
  9067. */
  9068. function mergeTemplateAttributes(dst, src) {
  9069. var srcAttr = src.$attr,
  9070. dstAttr = dst.$attr;
  9071. // reapply the old attributes to the new element
  9072. forEach(dst, function(value, key) {
  9073. if (key.charAt(0) !== '$') {
  9074. if (src[key] && src[key] !== value) {
  9075. if (value.length) {
  9076. value += (key === 'style' ? ';' : ' ') + src[key];
  9077. } else {
  9078. value = src[key];
  9079. }
  9080. }
  9081. dst.$set(key, value, true, srcAttr[key]);
  9082. }
  9083. });
  9084. // copy the new attributes on the old attrs object
  9085. forEach(src, function(value, key) {
  9086. // Check if we already set this attribute in the loop above.
  9087. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  9088. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  9089. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  9090. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  9091. dst[key] = value;
  9092. if (key !== 'class' && key !== 'style') {
  9093. dstAttr[key] = srcAttr[key];
  9094. }
  9095. }
  9096. });
  9097. }
  9098. function compileTemplateUrl(directives, $compileNode, tAttrs,
  9099. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  9100. var linkQueue = [],
  9101. afterTemplateNodeLinkFn,
  9102. afterTemplateChildLinkFn,
  9103. beforeTemplateCompileNode = $compileNode[0],
  9104. origAsyncDirective = directives.shift(),
  9105. derivedSyncDirective = inherit(origAsyncDirective, {
  9106. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  9107. }),
  9108. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  9109. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  9110. : origAsyncDirective.templateUrl,
  9111. templateNamespace = origAsyncDirective.templateNamespace;
  9112. $compileNode.empty();
  9113. $templateRequest(templateUrl)
  9114. .then(function(content) {
  9115. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  9116. content = denormalizeTemplate(content);
  9117. if (origAsyncDirective.replace) {
  9118. if (jqLiteIsTextNode(content)) {
  9119. $template = [];
  9120. } else {
  9121. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  9122. }
  9123. compileNode = $template[0];
  9124. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  9125. throw $compileMinErr('tplrt',
  9126. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  9127. origAsyncDirective.name, templateUrl);
  9128. }
  9129. tempTemplateAttrs = {$attr: {}};
  9130. replaceWith($rootElement, $compileNode, compileNode);
  9131. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  9132. if (isObject(origAsyncDirective.scope)) {
  9133. // the original directive that caused the template to be loaded async required
  9134. // an isolate scope
  9135. markDirectiveScope(templateDirectives, true);
  9136. }
  9137. directives = templateDirectives.concat(directives);
  9138. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  9139. } else {
  9140. compileNode = beforeTemplateCompileNode;
  9141. $compileNode.html(content);
  9142. }
  9143. directives.unshift(derivedSyncDirective);
  9144. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  9145. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  9146. previousCompileContext);
  9147. forEach($rootElement, function(node, i) {
  9148. if (node === compileNode) {
  9149. $rootElement[i] = $compileNode[0];
  9150. }
  9151. });
  9152. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  9153. while (linkQueue.length) {
  9154. var scope = linkQueue.shift(),
  9155. beforeTemplateLinkNode = linkQueue.shift(),
  9156. linkRootElement = linkQueue.shift(),
  9157. boundTranscludeFn = linkQueue.shift(),
  9158. linkNode = $compileNode[0];
  9159. if (scope.$$destroyed) continue;
  9160. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  9161. var oldClasses = beforeTemplateLinkNode.className;
  9162. if (!(previousCompileContext.hasElementTranscludeDirective &&
  9163. origAsyncDirective.replace)) {
  9164. // it was cloned therefore we have to clone as well.
  9165. linkNode = jqLiteClone(compileNode);
  9166. }
  9167. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  9168. // Copy in CSS classes from original node
  9169. safeAddClass(jqLite(linkNode), oldClasses);
  9170. }
  9171. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9172. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9173. } else {
  9174. childBoundTranscludeFn = boundTranscludeFn;
  9175. }
  9176. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  9177. childBoundTranscludeFn);
  9178. }
  9179. linkQueue = null;
  9180. }).catch(function(error) {
  9181. if (error instanceof Error) {
  9182. $exceptionHandler(error);
  9183. }
  9184. });
  9185. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  9186. var childBoundTranscludeFn = boundTranscludeFn;
  9187. if (scope.$$destroyed) return;
  9188. if (linkQueue) {
  9189. linkQueue.push(scope,
  9190. node,
  9191. rootElement,
  9192. childBoundTranscludeFn);
  9193. } else {
  9194. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9195. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9196. }
  9197. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  9198. }
  9199. };
  9200. }
  9201. /**
  9202. * Sorting function for bound directives.
  9203. */
  9204. function byPriority(a, b) {
  9205. var diff = b.priority - a.priority;
  9206. if (diff !== 0) return diff;
  9207. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  9208. return a.index - b.index;
  9209. }
  9210. function assertNoDuplicate(what, previousDirective, directive, element) {
  9211. function wrapModuleNameIfDefined(moduleName) {
  9212. return moduleName ?
  9213. (' (module: ' + moduleName + ')') :
  9214. '';
  9215. }
  9216. if (previousDirective) {
  9217. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  9218. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  9219. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  9220. }
  9221. }
  9222. function addTextInterpolateDirective(directives, text) {
  9223. var interpolateFn = $interpolate(text, true);
  9224. if (interpolateFn) {
  9225. directives.push({
  9226. priority: 0,
  9227. compile: function textInterpolateCompileFn(templateNode) {
  9228. var templateNodeParent = templateNode.parent(),
  9229. hasCompileParent = !!templateNodeParent.length;
  9230. // When transcluding a template that has bindings in the root
  9231. // we don't have a parent and thus need to add the class during linking fn.
  9232. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  9233. return function textInterpolateLinkFn(scope, node) {
  9234. var parent = node.parent();
  9235. if (!hasCompileParent) compile.$$addBindingClass(parent);
  9236. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  9237. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  9238. node[0].nodeValue = value;
  9239. });
  9240. };
  9241. }
  9242. });
  9243. }
  9244. }
  9245. function wrapTemplate(type, template) {
  9246. type = lowercase(type || 'html');
  9247. switch (type) {
  9248. case 'svg':
  9249. case 'math':
  9250. var wrapper = window.document.createElement('div');
  9251. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  9252. return wrapper.childNodes[0].childNodes;
  9253. default:
  9254. return template;
  9255. }
  9256. }
  9257. function getTrustedContext(node, attrNormalizedName) {
  9258. if (attrNormalizedName === 'srcdoc') {
  9259. return $sce.HTML;
  9260. }
  9261. var tag = nodeName_(node);
  9262. // All tags with src attributes require a RESOURCE_URL value, except for
  9263. // img and various html5 media tags.
  9264. if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
  9265. if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {
  9266. return $sce.RESOURCE_URL;
  9267. }
  9268. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  9269. } else if (attrNormalizedName === 'xlinkHref' ||
  9270. (tag === 'form' && attrNormalizedName === 'action') ||
  9271. // links can be stylesheets or imports, which can run script in the current origin
  9272. (tag === 'link' && attrNormalizedName === 'href')
  9273. ) {
  9274. return $sce.RESOURCE_URL;
  9275. }
  9276. }
  9277. function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
  9278. var trustedContext = getTrustedContext(node, name);
  9279. var mustHaveExpression = !isNgAttr;
  9280. var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
  9281. var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
  9282. // no interpolation found -> ignore
  9283. if (!interpolateFn) return;
  9284. if (name === 'multiple' && nodeName_(node) === 'select') {
  9285. throw $compileMinErr('selmulti',
  9286. 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
  9287. startingTag(node));
  9288. }
  9289. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  9290. throw $compileMinErr('nodomevents',
  9291. 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +
  9292. 'ng- versions (such as ng-click instead of onclick) instead.');
  9293. }
  9294. directives.push({
  9295. priority: 100,
  9296. compile: function() {
  9297. return {
  9298. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  9299. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  9300. // If the attribute has changed since last $interpolate()ed
  9301. var newValue = attr[name];
  9302. if (newValue !== value) {
  9303. // we need to interpolate again since the attribute value has been updated
  9304. // (e.g. by another directive's compile function)
  9305. // ensure unset/empty values make interpolateFn falsy
  9306. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  9307. value = newValue;
  9308. }
  9309. // if attribute was updated so that there is no interpolation going on we don't want to
  9310. // register any observers
  9311. if (!interpolateFn) return;
  9312. // initialize attr object so that it's ready in case we need the value for isolate
  9313. // scope initialization, otherwise the value would not be available from isolate
  9314. // directive's linking fn during linking phase
  9315. attr[name] = interpolateFn(scope);
  9316. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  9317. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  9318. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  9319. //special case for class attribute addition + removal
  9320. //so that class changes can tap into the animation
  9321. //hooks provided by the $animate service. Be sure to
  9322. //skip animations when the first digest occurs (when
  9323. //both the new and the old values are the same) since
  9324. //the CSS classes are the non-interpolated values
  9325. if (name === 'class' && newValue !== oldValue) {
  9326. attr.$updateClass(newValue, oldValue);
  9327. } else {
  9328. attr.$set(name, newValue);
  9329. }
  9330. });
  9331. }
  9332. };
  9333. }
  9334. });
  9335. }
  9336. /**
  9337. * This is a special jqLite.replaceWith, which can replace items which
  9338. * have no parents, provided that the containing jqLite collection is provided.
  9339. *
  9340. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  9341. * in the root of the tree.
  9342. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  9343. * the shell, but replace its DOM node reference.
  9344. * @param {Node} newNode The new DOM node.
  9345. */
  9346. function replaceWith($rootElement, elementsToRemove, newNode) {
  9347. var firstElementToRemove = elementsToRemove[0],
  9348. removeCount = elementsToRemove.length,
  9349. parent = firstElementToRemove.parentNode,
  9350. i, ii;
  9351. if ($rootElement) {
  9352. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  9353. if ($rootElement[i] === firstElementToRemove) {
  9354. $rootElement[i++] = newNode;
  9355. for (var j = i, j2 = j + removeCount - 1,
  9356. jj = $rootElement.length;
  9357. j < jj; j++, j2++) {
  9358. if (j2 < jj) {
  9359. $rootElement[j] = $rootElement[j2];
  9360. } else {
  9361. delete $rootElement[j];
  9362. }
  9363. }
  9364. $rootElement.length -= removeCount - 1;
  9365. // If the replaced element is also the jQuery .context then replace it
  9366. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  9367. // http://api.jquery.com/context/
  9368. if ($rootElement.context === firstElementToRemove) {
  9369. $rootElement.context = newNode;
  9370. }
  9371. break;
  9372. }
  9373. }
  9374. }
  9375. if (parent) {
  9376. parent.replaceChild(newNode, firstElementToRemove);
  9377. }
  9378. // Append all the `elementsToRemove` to a fragment. This will...
  9379. // - remove them from the DOM
  9380. // - allow them to still be traversed with .nextSibling
  9381. // - allow a single fragment.qSA to fetch all elements being removed
  9382. var fragment = window.document.createDocumentFragment();
  9383. for (i = 0; i < removeCount; i++) {
  9384. fragment.appendChild(elementsToRemove[i]);
  9385. }
  9386. if (jqLite.hasData(firstElementToRemove)) {
  9387. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  9388. // data here because there's no public interface in jQuery to do that and copying over
  9389. // event listeners (which is the main use of private data) wouldn't work anyway.
  9390. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  9391. // Remove $destroy event listeners from `firstElementToRemove`
  9392. jqLite(firstElementToRemove).off('$destroy');
  9393. }
  9394. // Cleanup any data/listeners on the elements and children.
  9395. // This includes invoking the $destroy event on any elements with listeners.
  9396. jqLite.cleanData(fragment.querySelectorAll('*'));
  9397. // Update the jqLite collection to only contain the `newNode`
  9398. for (i = 1; i < removeCount; i++) {
  9399. delete elementsToRemove[i];
  9400. }
  9401. elementsToRemove[0] = newNode;
  9402. elementsToRemove.length = 1;
  9403. }
  9404. function cloneAndAnnotateFn(fn, annotation) {
  9405. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  9406. }
  9407. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  9408. try {
  9409. linkFn(scope, $element, attrs, controllers, transcludeFn);
  9410. } catch (e) {
  9411. $exceptionHandler(e, startingTag($element));
  9412. }
  9413. }
  9414. // Set up $watches for isolate scope and controller bindings.
  9415. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  9416. var removeWatchCollection = [];
  9417. var initialChanges = {};
  9418. var changes;
  9419. forEach(bindings, function initializeBinding(definition, scopeName) {
  9420. var attrName = definition.attrName,
  9421. optional = definition.optional,
  9422. mode = definition.mode, // @, =, <, or &
  9423. lastValue,
  9424. parentGet, parentSet, compare, removeWatch;
  9425. switch (mode) {
  9426. case '@':
  9427. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9428. destination[scopeName] = attrs[attrName] = undefined;
  9429. }
  9430. removeWatch = attrs.$observe(attrName, function(value) {
  9431. if (isString(value) || isBoolean(value)) {
  9432. var oldValue = destination[scopeName];
  9433. recordChanges(scopeName, value, oldValue);
  9434. destination[scopeName] = value;
  9435. }
  9436. });
  9437. attrs.$$observers[attrName].$$scope = scope;
  9438. lastValue = attrs[attrName];
  9439. if (isString(lastValue)) {
  9440. // If the attribute has been provided then we trigger an interpolation to ensure
  9441. // the value is there for use in the link fn
  9442. destination[scopeName] = $interpolate(lastValue)(scope);
  9443. } else if (isBoolean(lastValue)) {
  9444. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  9445. // the value to boolean rather than a string, so we special case this situation
  9446. destination[scopeName] = lastValue;
  9447. }
  9448. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9449. removeWatchCollection.push(removeWatch);
  9450. break;
  9451. case '=':
  9452. if (!hasOwnProperty.call(attrs, attrName)) {
  9453. if (optional) break;
  9454. attrs[attrName] = undefined;
  9455. }
  9456. if (optional && !attrs[attrName]) break;
  9457. parentGet = $parse(attrs[attrName]);
  9458. if (parentGet.literal) {
  9459. compare = equals;
  9460. } else {
  9461. compare = simpleCompare;
  9462. }
  9463. parentSet = parentGet.assign || function() {
  9464. // reset the change, or we will throw this exception on every $digest
  9465. lastValue = destination[scopeName] = parentGet(scope);
  9466. throw $compileMinErr('nonassign',
  9467. 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
  9468. attrs[attrName], attrName, directive.name);
  9469. };
  9470. lastValue = destination[scopeName] = parentGet(scope);
  9471. var parentValueWatch = function parentValueWatch(parentValue) {
  9472. if (!compare(parentValue, destination[scopeName])) {
  9473. // we are out of sync and need to copy
  9474. if (!compare(parentValue, lastValue)) {
  9475. // parent changed and it has precedence
  9476. destination[scopeName] = parentValue;
  9477. } else {
  9478. // if the parent can be assigned then do so
  9479. parentSet(scope, parentValue = destination[scopeName]);
  9480. }
  9481. }
  9482. lastValue = parentValue;
  9483. return lastValue;
  9484. };
  9485. parentValueWatch.$stateful = true;
  9486. if (definition.collection) {
  9487. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  9488. } else {
  9489. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  9490. }
  9491. removeWatchCollection.push(removeWatch);
  9492. break;
  9493. case '<':
  9494. if (!hasOwnProperty.call(attrs, attrName)) {
  9495. if (optional) break;
  9496. attrs[attrName] = undefined;
  9497. }
  9498. if (optional && !attrs[attrName]) break;
  9499. parentGet = $parse(attrs[attrName]);
  9500. var deepWatch = parentGet.literal;
  9501. var initialValue = destination[scopeName] = parentGet(scope);
  9502. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9503. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
  9504. if (oldValue === newValue) {
  9505. if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {
  9506. return;
  9507. }
  9508. oldValue = initialValue;
  9509. }
  9510. recordChanges(scopeName, newValue, oldValue);
  9511. destination[scopeName] = newValue;
  9512. }, deepWatch);
  9513. removeWatchCollection.push(removeWatch);
  9514. break;
  9515. case '&':
  9516. // Don't assign Object.prototype method to scope
  9517. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  9518. // Don't assign noop to destination if expression is not valid
  9519. if (parentGet === noop && optional) break;
  9520. destination[scopeName] = function(locals) {
  9521. return parentGet(scope, locals);
  9522. };
  9523. break;
  9524. }
  9525. });
  9526. function recordChanges(key, currentValue, previousValue) {
  9527. if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) {
  9528. // If we have not already scheduled the top level onChangesQueue handler then do so now
  9529. if (!onChangesQueue) {
  9530. scope.$$postDigest(flushOnChangesQueue);
  9531. onChangesQueue = [];
  9532. }
  9533. // If we have not already queued a trigger of onChanges for this controller then do so now
  9534. if (!changes) {
  9535. changes = {};
  9536. onChangesQueue.push(triggerOnChangesHook);
  9537. }
  9538. // If the has been a change on this property already then we need to reuse the previous value
  9539. if (changes[key]) {
  9540. previousValue = changes[key].previousValue;
  9541. }
  9542. // Store this change
  9543. changes[key] = new SimpleChange(previousValue, currentValue);
  9544. }
  9545. }
  9546. function triggerOnChangesHook() {
  9547. destination.$onChanges(changes);
  9548. // Now clear the changes so that we schedule onChanges when more changes arrive
  9549. changes = undefined;
  9550. }
  9551. return {
  9552. initialChanges: initialChanges,
  9553. removeWatches: removeWatchCollection.length && function removeWatches() {
  9554. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  9555. removeWatchCollection[i]();
  9556. }
  9557. }
  9558. };
  9559. }
  9560. }];
  9561. }
  9562. function SimpleChange(previous, current) {
  9563. this.previousValue = previous;
  9564. this.currentValue = current;
  9565. }
  9566. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  9567. var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
  9568. var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
  9569. /**
  9570. * Converts all accepted directives format into proper directive name.
  9571. * @param name Name to normalize
  9572. */
  9573. function directiveNormalize(name) {
  9574. return name
  9575. .replace(PREFIX_REGEXP, '')
  9576. .replace(SPECIAL_CHARS_REGEXP, fnCamelCaseReplace);
  9577. }
  9578. /**
  9579. * @ngdoc type
  9580. * @name $compile.directive.Attributes
  9581. *
  9582. * @description
  9583. * A shared object between directive compile / linking functions which contains normalized DOM
  9584. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  9585. * needed since all of these are treated as equivalent in Angular:
  9586. *
  9587. * ```
  9588. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  9589. * ```
  9590. */
  9591. /**
  9592. * @ngdoc property
  9593. * @name $compile.directive.Attributes#$attr
  9594. *
  9595. * @description
  9596. * A map of DOM element attribute names to the normalized name. This is
  9597. * needed to do reverse lookup from normalized name back to actual name.
  9598. */
  9599. /**
  9600. * @ngdoc method
  9601. * @name $compile.directive.Attributes#$set
  9602. * @kind function
  9603. *
  9604. * @description
  9605. * Set DOM element attribute value.
  9606. *
  9607. *
  9608. * @param {string} name Normalized element attribute name of the property to modify. The name is
  9609. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  9610. * property to the original name.
  9611. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  9612. */
  9613. /**
  9614. * Closure compiler type information
  9615. */
  9616. function nodesetLinkingFn(
  9617. /* angular.Scope */ scope,
  9618. /* NodeList */ nodeList,
  9619. /* Element */ rootElement,
  9620. /* function(Function) */ boundTranscludeFn
  9621. ) {}
  9622. function directiveLinkingFn(
  9623. /* nodesetLinkingFn */ nodesetLinkingFn,
  9624. /* angular.Scope */ scope,
  9625. /* Node */ node,
  9626. /* Element */ rootElement,
  9627. /* function(Function) */ boundTranscludeFn
  9628. ) {}
  9629. function tokenDifference(str1, str2) {
  9630. var values = '',
  9631. tokens1 = str1.split(/\s+/),
  9632. tokens2 = str2.split(/\s+/);
  9633. outer:
  9634. for (var i = 0; i < tokens1.length; i++) {
  9635. var token = tokens1[i];
  9636. for (var j = 0; j < tokens2.length; j++) {
  9637. if (token === tokens2[j]) continue outer;
  9638. }
  9639. values += (values.length > 0 ? ' ' : '') + token;
  9640. }
  9641. return values;
  9642. }
  9643. function removeComments(jqNodes) {
  9644. jqNodes = jqLite(jqNodes);
  9645. var i = jqNodes.length;
  9646. if (i <= 1) {
  9647. return jqNodes;
  9648. }
  9649. while (i--) {
  9650. var node = jqNodes[i];
  9651. if (node.nodeType === NODE_TYPE_COMMENT ||
  9652. (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
  9653. splice.call(jqNodes, i, 1);
  9654. }
  9655. }
  9656. return jqNodes;
  9657. }
  9658. var $controllerMinErr = minErr('$controller');
  9659. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  9660. function identifierForController(controller, ident) {
  9661. if (ident && isString(ident)) return ident;
  9662. if (isString(controller)) {
  9663. var match = CNTRL_REG.exec(controller);
  9664. if (match) return match[3];
  9665. }
  9666. }
  9667. /**
  9668. * @ngdoc provider
  9669. * @name $controllerProvider
  9670. * @this
  9671. *
  9672. * @description
  9673. * The {@link ng.$controller $controller service} is used by Angular to create new
  9674. * controllers.
  9675. *
  9676. * This provider allows controller registration via the
  9677. * {@link ng.$controllerProvider#register register} method.
  9678. */
  9679. function $ControllerProvider() {
  9680. var controllers = {},
  9681. globals = false;
  9682. /**
  9683. * @ngdoc method
  9684. * @name $controllerProvider#has
  9685. * @param {string} name Controller name to check.
  9686. */
  9687. this.has = function(name) {
  9688. return controllers.hasOwnProperty(name);
  9689. };
  9690. /**
  9691. * @ngdoc method
  9692. * @name $controllerProvider#register
  9693. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  9694. * the names and the values are the constructors.
  9695. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  9696. * annotations in the array notation).
  9697. */
  9698. this.register = function(name, constructor) {
  9699. assertNotHasOwnProperty(name, 'controller');
  9700. if (isObject(name)) {
  9701. extend(controllers, name);
  9702. } else {
  9703. controllers[name] = constructor;
  9704. }
  9705. };
  9706. /**
  9707. * @ngdoc method
  9708. * @name $controllerProvider#allowGlobals
  9709. * @description If called, allows `$controller` to find controller constructors on `window`
  9710. *
  9711. * @deprecated
  9712. * sinceVersion="v1.3.0"
  9713. * removeVersion="v1.7.0"
  9714. * This method of finding controllers has been deprecated.
  9715. */
  9716. this.allowGlobals = function() {
  9717. globals = true;
  9718. };
  9719. this.$get = ['$injector', '$window', function($injector, $window) {
  9720. /**
  9721. * @ngdoc service
  9722. * @name $controller
  9723. * @requires $injector
  9724. *
  9725. * @param {Function|string} constructor If called with a function then it's considered to be the
  9726. * controller constructor function. Otherwise it's considered to be a string which is used
  9727. * to retrieve the controller constructor using the following steps:
  9728. *
  9729. * * check if a controller with given name is registered via `$controllerProvider`
  9730. * * check if evaluating the string on the current scope returns a constructor
  9731. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  9732. * `window` object (deprecated, not recommended)
  9733. *
  9734. * The string can use the `controller as property` syntax, where the controller instance is published
  9735. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  9736. * to work correctly.
  9737. *
  9738. * @param {Object} locals Injection locals for Controller.
  9739. * @return {Object} Instance of given controller.
  9740. *
  9741. * @description
  9742. * `$controller` service is responsible for instantiating controllers.
  9743. *
  9744. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  9745. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  9746. */
  9747. return function $controller(expression, locals, later, ident) {
  9748. // PRIVATE API:
  9749. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  9750. // If true, $controller will allocate the object with the correct
  9751. // prototype chain, but will not invoke the controller until a returned
  9752. // callback is invoked.
  9753. // param `ident` --- An optional label which overrides the label parsed from the controller
  9754. // expression, if any.
  9755. var instance, match, constructor, identifier;
  9756. later = later === true;
  9757. if (ident && isString(ident)) {
  9758. identifier = ident;
  9759. }
  9760. if (isString(expression)) {
  9761. match = expression.match(CNTRL_REG);
  9762. if (!match) {
  9763. throw $controllerMinErr('ctrlfmt',
  9764. 'Badly formed controller string \'{0}\'. ' +
  9765. 'Must match `__name__ as __id__` or `__name__`.', expression);
  9766. }
  9767. constructor = match[1];
  9768. identifier = identifier || match[3];
  9769. expression = controllers.hasOwnProperty(constructor)
  9770. ? controllers[constructor]
  9771. : getter(locals.$scope, constructor, true) ||
  9772. (globals ? getter($window, constructor, true) : undefined);
  9773. if (!expression) {
  9774. throw $controllerMinErr('ctrlreg',
  9775. 'The controller with the name \'{0}\' is not registered.', constructor);
  9776. }
  9777. assertArgFn(expression, constructor, true);
  9778. }
  9779. if (later) {
  9780. // Instantiate controller later:
  9781. // This machinery is used to create an instance of the object before calling the
  9782. // controller's constructor itself.
  9783. //
  9784. // This allows properties to be added to the controller before the constructor is
  9785. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9786. //
  9787. // This feature is not intended for use by applications, and is thus not documented
  9788. // publicly.
  9789. // Object creation: http://jsperf.com/create-constructor/2
  9790. var controllerPrototype = (isArray(expression) ?
  9791. expression[expression.length - 1] : expression).prototype;
  9792. instance = Object.create(controllerPrototype || null);
  9793. if (identifier) {
  9794. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9795. }
  9796. return extend(function $controllerInit() {
  9797. var result = $injector.invoke(expression, instance, locals, constructor);
  9798. if (result !== instance && (isObject(result) || isFunction(result))) {
  9799. instance = result;
  9800. if (identifier) {
  9801. // If result changed, re-assign controllerAs value to scope.
  9802. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9803. }
  9804. }
  9805. return instance;
  9806. }, {
  9807. instance: instance,
  9808. identifier: identifier
  9809. });
  9810. }
  9811. instance = $injector.instantiate(expression, locals, constructor);
  9812. if (identifier) {
  9813. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9814. }
  9815. return instance;
  9816. };
  9817. function addIdentifier(locals, identifier, instance, name) {
  9818. if (!(locals && isObject(locals.$scope))) {
  9819. throw minErr('$controller')('noscp',
  9820. 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
  9821. name, identifier);
  9822. }
  9823. locals.$scope[identifier] = instance;
  9824. }
  9825. }];
  9826. }
  9827. /**
  9828. * @ngdoc service
  9829. * @name $document
  9830. * @requires $window
  9831. * @this
  9832. *
  9833. * @description
  9834. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  9835. *
  9836. * @example
  9837. <example module="documentExample" name="document">
  9838. <file name="index.html">
  9839. <div ng-controller="ExampleController">
  9840. <p>$document title: <b ng-bind="title"></b></p>
  9841. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  9842. </div>
  9843. </file>
  9844. <file name="script.js">
  9845. angular.module('documentExample', [])
  9846. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  9847. $scope.title = $document[0].title;
  9848. $scope.windowTitle = angular.element(window.document)[0].title;
  9849. }]);
  9850. </file>
  9851. </example>
  9852. */
  9853. function $DocumentProvider() {
  9854. this.$get = ['$window', function(window) {
  9855. return jqLite(window.document);
  9856. }];
  9857. }
  9858. /**
  9859. * @private
  9860. * @this
  9861. * Listens for document visibility change and makes the current status accessible.
  9862. */
  9863. function $$IsDocumentHiddenProvider() {
  9864. this.$get = ['$document', '$rootScope', function($document, $rootScope) {
  9865. var doc = $document[0];
  9866. var hidden = doc && doc.hidden;
  9867. $document.on('visibilitychange', changeListener);
  9868. $rootScope.$on('$destroy', function() {
  9869. $document.off('visibilitychange', changeListener);
  9870. });
  9871. function changeListener() {
  9872. hidden = doc.hidden;
  9873. }
  9874. return function() {
  9875. return hidden;
  9876. };
  9877. }];
  9878. }
  9879. /**
  9880. * @ngdoc service
  9881. * @name $exceptionHandler
  9882. * @requires ng.$log
  9883. * @this
  9884. *
  9885. * @description
  9886. * Any uncaught exception in angular expressions is delegated to this service.
  9887. * The default implementation simply delegates to `$log.error` which logs it into
  9888. * the browser console.
  9889. *
  9890. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  9891. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  9892. *
  9893. * ## Example:
  9894. *
  9895. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  9896. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  9897. * of `$log.error()`.
  9898. *
  9899. * ```js
  9900. * angular.
  9901. * module('exceptionOverwrite', []).
  9902. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  9903. * return function myExceptionHandler(exception, cause) {
  9904. * logErrorsToBackend(exception, cause);
  9905. * $log.warn(exception, cause);
  9906. * };
  9907. * }]);
  9908. * ```
  9909. *
  9910. * <hr />
  9911. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  9912. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  9913. * (unless executed during a digest).
  9914. *
  9915. * If you wish, you can manually delegate exceptions, e.g.
  9916. * `try { ... } catch(e) { $exceptionHandler(e); }`
  9917. *
  9918. * @param {Error} exception Exception associated with the error.
  9919. * @param {string=} cause Optional information about the context in which
  9920. * the error was thrown.
  9921. *
  9922. */
  9923. function $ExceptionHandlerProvider() {
  9924. this.$get = ['$log', function($log) {
  9925. return function(exception, cause) {
  9926. $log.error.apply($log, arguments);
  9927. };
  9928. }];
  9929. }
  9930. var $$ForceReflowProvider = /** @this */ function() {
  9931. this.$get = ['$document', function($document) {
  9932. return function(domNode) {
  9933. //the line below will force the browser to perform a repaint so
  9934. //that all the animated elements within the animation frame will
  9935. //be properly updated and drawn on screen. This is required to
  9936. //ensure that the preparation animation is properly flushed so that
  9937. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  9938. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  9939. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  9940. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  9941. if (domNode) {
  9942. if (!domNode.nodeType && domNode instanceof jqLite) {
  9943. domNode = domNode[0];
  9944. }
  9945. } else {
  9946. domNode = $document[0].body;
  9947. }
  9948. return domNode.offsetWidth + 1;
  9949. };
  9950. }];
  9951. };
  9952. var APPLICATION_JSON = 'application/json';
  9953. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  9954. var JSON_START = /^\[|^\{(?!\{)/;
  9955. var JSON_ENDS = {
  9956. '[': /]$/,
  9957. '{': /}$/
  9958. };
  9959. var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
  9960. var $httpMinErr = minErr('$http');
  9961. function serializeValue(v) {
  9962. if (isObject(v)) {
  9963. return isDate(v) ? v.toISOString() : toJson(v);
  9964. }
  9965. return v;
  9966. }
  9967. /** @this */
  9968. function $HttpParamSerializerProvider() {
  9969. /**
  9970. * @ngdoc service
  9971. * @name $httpParamSerializer
  9972. * @description
  9973. *
  9974. * Default {@link $http `$http`} params serializer that converts objects to strings
  9975. * according to the following rules:
  9976. *
  9977. * * `{'foo': 'bar'}` results in `foo=bar`
  9978. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  9979. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  9980. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  9981. *
  9982. * Note that serializer will sort the request parameters alphabetically.
  9983. * */
  9984. this.$get = function() {
  9985. return function ngParamSerializer(params) {
  9986. if (!params) return '';
  9987. var parts = [];
  9988. forEachSorted(params, function(value, key) {
  9989. if (value === null || isUndefined(value)) return;
  9990. if (isArray(value)) {
  9991. forEach(value, function(v) {
  9992. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  9993. });
  9994. } else {
  9995. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  9996. }
  9997. });
  9998. return parts.join('&');
  9999. };
  10000. };
  10001. }
  10002. /** @this */
  10003. function $HttpParamSerializerJQLikeProvider() {
  10004. /**
  10005. * @ngdoc service
  10006. * @name $httpParamSerializerJQLike
  10007. *
  10008. * @description
  10009. *
  10010. * Alternative {@link $http `$http`} params serializer that follows
  10011. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  10012. * The serializer will also sort the params alphabetically.
  10013. *
  10014. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  10015. *
  10016. * ```js
  10017. * $http({
  10018. * url: myUrl,
  10019. * method: 'GET',
  10020. * params: myParams,
  10021. * paramSerializer: '$httpParamSerializerJQLike'
  10022. * });
  10023. * ```
  10024. *
  10025. * It is also possible to set it as the default `paramSerializer` in the
  10026. * {@link $httpProvider#defaults `$httpProvider`}.
  10027. *
  10028. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  10029. * form data for submission:
  10030. *
  10031. * ```js
  10032. * .controller(function($http, $httpParamSerializerJQLike) {
  10033. * //...
  10034. *
  10035. * $http({
  10036. * url: myUrl,
  10037. * method: 'POST',
  10038. * data: $httpParamSerializerJQLike(myData),
  10039. * headers: {
  10040. * 'Content-Type': 'application/x-www-form-urlencoded'
  10041. * }
  10042. * });
  10043. *
  10044. * });
  10045. * ```
  10046. *
  10047. * */
  10048. this.$get = function() {
  10049. return function jQueryLikeParamSerializer(params) {
  10050. if (!params) return '';
  10051. var parts = [];
  10052. serialize(params, '', true);
  10053. return parts.join('&');
  10054. function serialize(toSerialize, prefix, topLevel) {
  10055. if (toSerialize === null || isUndefined(toSerialize)) return;
  10056. if (isArray(toSerialize)) {
  10057. forEach(toSerialize, function(value, index) {
  10058. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  10059. });
  10060. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  10061. forEachSorted(toSerialize, function(value, key) {
  10062. serialize(value, prefix +
  10063. (topLevel ? '' : '[') +
  10064. key +
  10065. (topLevel ? '' : ']'));
  10066. });
  10067. } else {
  10068. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  10069. }
  10070. }
  10071. };
  10072. };
  10073. }
  10074. function defaultHttpResponseTransform(data, headers) {
  10075. if (isString(data)) {
  10076. // Strip json vulnerability protection prefix and trim whitespace
  10077. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  10078. if (tempData) {
  10079. var contentType = headers('Content-Type');
  10080. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  10081. try {
  10082. data = fromJson(tempData);
  10083. } catch (e) {
  10084. throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' +
  10085. 'Parse error: "{1}"', data, e);
  10086. }
  10087. }
  10088. }
  10089. }
  10090. return data;
  10091. }
  10092. function isJsonLike(str) {
  10093. var jsonStart = str.match(JSON_START);
  10094. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  10095. }
  10096. /**
  10097. * Parse headers into key value object
  10098. *
  10099. * @param {string} headers Raw headers as a string
  10100. * @returns {Object} Parsed headers as key value object
  10101. */
  10102. function parseHeaders(headers) {
  10103. var parsed = createMap(), i;
  10104. function fillInParsed(key, val) {
  10105. if (key) {
  10106. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  10107. }
  10108. }
  10109. if (isString(headers)) {
  10110. forEach(headers.split('\n'), function(line) {
  10111. i = line.indexOf(':');
  10112. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  10113. });
  10114. } else if (isObject(headers)) {
  10115. forEach(headers, function(headerVal, headerKey) {
  10116. fillInParsed(lowercase(headerKey), trim(headerVal));
  10117. });
  10118. }
  10119. return parsed;
  10120. }
  10121. /**
  10122. * Returns a function that provides access to parsed headers.
  10123. *
  10124. * Headers are lazy parsed when first requested.
  10125. * @see parseHeaders
  10126. *
  10127. * @param {(string|Object)} headers Headers to provide access to.
  10128. * @returns {function(string=)} Returns a getter function which if called with:
  10129. *
  10130. * - if called with an argument returns a single header value or null
  10131. * - if called with no arguments returns an object containing all headers.
  10132. */
  10133. function headersGetter(headers) {
  10134. var headersObj;
  10135. return function(name) {
  10136. if (!headersObj) headersObj = parseHeaders(headers);
  10137. if (name) {
  10138. var value = headersObj[lowercase(name)];
  10139. if (value === undefined) {
  10140. value = null;
  10141. }
  10142. return value;
  10143. }
  10144. return headersObj;
  10145. };
  10146. }
  10147. /**
  10148. * Chain all given functions
  10149. *
  10150. * This function is used for both request and response transforming
  10151. *
  10152. * @param {*} data Data to transform.
  10153. * @param {function(string=)} headers HTTP headers getter fn.
  10154. * @param {number} status HTTP status code of the response.
  10155. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  10156. * @returns {*} Transformed data.
  10157. */
  10158. function transformData(data, headers, status, fns) {
  10159. if (isFunction(fns)) {
  10160. return fns(data, headers, status);
  10161. }
  10162. forEach(fns, function(fn) {
  10163. data = fn(data, headers, status);
  10164. });
  10165. return data;
  10166. }
  10167. function isSuccess(status) {
  10168. return 200 <= status && status < 300;
  10169. }
  10170. /**
  10171. * @ngdoc provider
  10172. * @name $httpProvider
  10173. * @this
  10174. *
  10175. * @description
  10176. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  10177. * */
  10178. function $HttpProvider() {
  10179. /**
  10180. * @ngdoc property
  10181. * @name $httpProvider#defaults
  10182. * @description
  10183. *
  10184. * Object containing default values for all {@link ng.$http $http} requests.
  10185. *
  10186. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  10187. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  10188. * by default. See {@link $http#caching $http Caching} for more information.
  10189. *
  10190. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  10191. * Defaults value is `'XSRF-TOKEN'`.
  10192. *
  10193. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  10194. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  10195. *
  10196. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  10197. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  10198. * setting default headers.
  10199. * - **`defaults.headers.common`**
  10200. * - **`defaults.headers.post`**
  10201. * - **`defaults.headers.put`**
  10202. * - **`defaults.headers.patch`**
  10203. *
  10204. *
  10205. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  10206. * used to the prepare string representation of request parameters (specified as an object).
  10207. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  10208. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  10209. *
  10210. * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the
  10211. * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the
  10212. * {@link $jsonpCallbacks} service. Defaults to `'callback'`.
  10213. *
  10214. **/
  10215. var defaults = this.defaults = {
  10216. // transform incoming response data
  10217. transformResponse: [defaultHttpResponseTransform],
  10218. // transform outgoing request data
  10219. transformRequest: [function(d) {
  10220. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  10221. }],
  10222. // default headers
  10223. headers: {
  10224. common: {
  10225. 'Accept': 'application/json, text/plain, */*'
  10226. },
  10227. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10228. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10229. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  10230. },
  10231. xsrfCookieName: 'XSRF-TOKEN',
  10232. xsrfHeaderName: 'X-XSRF-TOKEN',
  10233. paramSerializer: '$httpParamSerializer',
  10234. jsonpCallbackParam: 'callback'
  10235. };
  10236. var useApplyAsync = false;
  10237. /**
  10238. * @ngdoc method
  10239. * @name $httpProvider#useApplyAsync
  10240. * @description
  10241. *
  10242. * Configure $http service to combine processing of multiple http responses received at around
  10243. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  10244. * significant performance improvement for bigger applications that make many HTTP requests
  10245. * concurrently (common during application bootstrap).
  10246. *
  10247. * Defaults to false. If no value is specified, returns the current configured value.
  10248. *
  10249. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  10250. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  10251. * to load and share the same digest cycle.
  10252. *
  10253. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  10254. * otherwise, returns the current configured value.
  10255. **/
  10256. this.useApplyAsync = function(value) {
  10257. if (isDefined(value)) {
  10258. useApplyAsync = !!value;
  10259. return this;
  10260. }
  10261. return useApplyAsync;
  10262. };
  10263. /**
  10264. * @ngdoc property
  10265. * @name $httpProvider#interceptors
  10266. * @description
  10267. *
  10268. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  10269. * pre-processing of request or postprocessing of responses.
  10270. *
  10271. * These service factories are ordered by request, i.e. they are applied in the same order as the
  10272. * array, on request, but reverse order, on response.
  10273. *
  10274. * {@link ng.$http#interceptors Interceptors detailed info}
  10275. **/
  10276. var interceptorFactories = this.interceptors = [];
  10277. this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
  10278. function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
  10279. var defaultCache = $cacheFactory('$http');
  10280. /**
  10281. * Make sure that default param serializer is exposed as a function
  10282. */
  10283. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  10284. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  10285. /**
  10286. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  10287. * The reversal is needed so that we can build up the interception chain around the
  10288. * server request.
  10289. */
  10290. var reversedInterceptors = [];
  10291. forEach(interceptorFactories, function(interceptorFactory) {
  10292. reversedInterceptors.unshift(isString(interceptorFactory)
  10293. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  10294. });
  10295. /**
  10296. * @ngdoc service
  10297. * @kind function
  10298. * @name $http
  10299. * @requires ng.$httpBackend
  10300. * @requires $cacheFactory
  10301. * @requires $rootScope
  10302. * @requires $q
  10303. * @requires $injector
  10304. *
  10305. * @description
  10306. * The `$http` service is a core Angular service that facilitates communication with the remote
  10307. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  10308. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  10309. *
  10310. * For unit testing applications that use `$http` service, see
  10311. * {@link ngMock.$httpBackend $httpBackend mock}.
  10312. *
  10313. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  10314. * $resource} service.
  10315. *
  10316. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  10317. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  10318. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  10319. *
  10320. *
  10321. * ## General usage
  10322. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  10323. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  10324. *
  10325. * ```js
  10326. * // Simple GET request example:
  10327. * $http({
  10328. * method: 'GET',
  10329. * url: '/someUrl'
  10330. * }).then(function successCallback(response) {
  10331. * // this callback will be called asynchronously
  10332. * // when the response is available
  10333. * }, function errorCallback(response) {
  10334. * // called asynchronously if an error occurs
  10335. * // or server returns response with an error status.
  10336. * });
  10337. * ```
  10338. *
  10339. * The response object has these properties:
  10340. *
  10341. * - **data** – `{string|Object}` – The response body transformed with the transform
  10342. * functions.
  10343. * - **status** – `{number}` – HTTP status code of the response.
  10344. * - **headers** – `{function([headerName])}` – Header getter function.
  10345. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  10346. * - **statusText** – `{string}` – HTTP status text of the response.
  10347. *
  10348. * A response status code between 200 and 299 is considered a success status and will result in
  10349. * the success callback being called. Any response status code outside of that range is
  10350. * considered an error status and will result in the error callback being called.
  10351. * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
  10352. * aborted, e.g. using a `config.timeout`.
  10353. * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
  10354. * that the outcome (success or error) will be determined by the final response status code.
  10355. *
  10356. *
  10357. * ## Shortcut methods
  10358. *
  10359. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  10360. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  10361. * last argument.
  10362. *
  10363. * ```js
  10364. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  10365. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  10366. * ```
  10367. *
  10368. * Complete list of shortcut methods:
  10369. *
  10370. * - {@link ng.$http#get $http.get}
  10371. * - {@link ng.$http#head $http.head}
  10372. * - {@link ng.$http#post $http.post}
  10373. * - {@link ng.$http#put $http.put}
  10374. * - {@link ng.$http#delete $http.delete}
  10375. * - {@link ng.$http#jsonp $http.jsonp}
  10376. * - {@link ng.$http#patch $http.patch}
  10377. *
  10378. *
  10379. * ## Writing Unit Tests that use $http
  10380. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  10381. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  10382. * request using trained responses.
  10383. *
  10384. * ```
  10385. * $httpBackend.expectGET(...);
  10386. * $http.get(...);
  10387. * $httpBackend.flush();
  10388. * ```
  10389. *
  10390. * ## Setting HTTP Headers
  10391. *
  10392. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  10393. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  10394. * object, which currently contains this default configuration:
  10395. *
  10396. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  10397. * - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</code>
  10398. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  10399. * - `Content-Type: application/json`
  10400. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  10401. * - `Content-Type: application/json`
  10402. *
  10403. * To add or overwrite these defaults, simply add or remove a property from these configuration
  10404. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  10405. * with the lowercased HTTP method name as the key, e.g.
  10406. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  10407. *
  10408. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  10409. * fashion. For example:
  10410. *
  10411. * ```
  10412. * module.run(function($http) {
  10413. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  10414. * });
  10415. * ```
  10416. *
  10417. * In addition, you can supply a `headers` property in the config object passed when
  10418. * calling `$http(config)`, which overrides the defaults without changing them globally.
  10419. *
  10420. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  10421. * Use the `headers` property, setting the desired header to `undefined`. For example:
  10422. *
  10423. * ```js
  10424. * var req = {
  10425. * method: 'POST',
  10426. * url: 'http://example.com',
  10427. * headers: {
  10428. * 'Content-Type': undefined
  10429. * },
  10430. * data: { test: 'test' }
  10431. * }
  10432. *
  10433. * $http(req).then(function(){...}, function(){...});
  10434. * ```
  10435. *
  10436. * ## Transforming Requests and Responses
  10437. *
  10438. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  10439. * and `transformResponse`. These properties can be a single function that returns
  10440. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  10441. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  10442. *
  10443. * <div class="alert alert-warning">
  10444. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  10445. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  10446. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  10447. * function will be reflected on the scope and in any templates where the object is data-bound.
  10448. * To prevent this, transform functions should have no side-effects.
  10449. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  10450. * </div>
  10451. *
  10452. * ### Default Transformations
  10453. *
  10454. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  10455. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  10456. * then these will be applied.
  10457. *
  10458. * You can augment or replace the default transformations by modifying these properties by adding to or
  10459. * replacing the array.
  10460. *
  10461. * Angular provides the following default transformations:
  10462. *
  10463. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  10464. *
  10465. * - If the `data` property of the request configuration object contains an object, serialize it
  10466. * into JSON format.
  10467. *
  10468. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  10469. *
  10470. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  10471. * - If JSON response is detected, deserialize it using a JSON parser.
  10472. *
  10473. *
  10474. * ### Overriding the Default Transformations Per Request
  10475. *
  10476. * If you wish to override the request/response transformations only for a single request then provide
  10477. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  10478. * into `$http`.
  10479. *
  10480. * Note that if you provide these properties on the config object the default transformations will be
  10481. * overwritten. If you wish to augment the default transformations then you must include them in your
  10482. * local transformation array.
  10483. *
  10484. * The following code demonstrates adding a new response transformation to be run after the default response
  10485. * transformations have been run.
  10486. *
  10487. * ```js
  10488. * function appendTransform(defaults, transform) {
  10489. *
  10490. * // We can't guarantee that the default transformation is an array
  10491. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  10492. *
  10493. * // Append the new transformation to the defaults
  10494. * return defaults.concat(transform);
  10495. * }
  10496. *
  10497. * $http({
  10498. * url: '...',
  10499. * method: 'GET',
  10500. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  10501. * return doTransform(value);
  10502. * })
  10503. * });
  10504. * ```
  10505. *
  10506. *
  10507. * ## Caching
  10508. *
  10509. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  10510. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  10511. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  10512. * precedence over the default cache value.
  10513. *
  10514. * In order to:
  10515. * * cache all responses - set the default cache value to TRUE or to a cache object
  10516. * * cache a specific response - set config.cache value to TRUE or to a cache object
  10517. *
  10518. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  10519. * then the default `$cacheFactory("$http")` object is used.
  10520. *
  10521. * The default cache value can be set by updating the
  10522. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  10523. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  10524. *
  10525. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  10526. * the relevant cache object. The next time the same request is made, the response is returned
  10527. * from the cache without sending a request to the server.
  10528. *
  10529. * Take note that:
  10530. *
  10531. * * Only GET and JSONP requests are cached.
  10532. * * The cache key is the request URL including search parameters; headers are not considered.
  10533. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  10534. * * If multiple identical requests are made using the same cache, which is not yet populated,
  10535. * one request will be made to the server and remaining requests will return the same response.
  10536. * * A cache-control header on the response does not affect if or how responses are cached.
  10537. *
  10538. *
  10539. * ## Interceptors
  10540. *
  10541. * Before you start creating interceptors, be sure to understand the
  10542. * {@link ng.$q $q and deferred/promise APIs}.
  10543. *
  10544. * For purposes of global error handling, authentication, or any kind of synchronous or
  10545. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  10546. * able to intercept requests before they are handed to the server and
  10547. * responses before they are handed over to the application code that
  10548. * initiated these requests. The interceptors leverage the {@link ng.$q
  10549. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  10550. *
  10551. * The interceptors are service factories that are registered with the `$httpProvider` by
  10552. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  10553. * injected with dependencies (if specified) and returns the interceptor.
  10554. *
  10555. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  10556. *
  10557. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  10558. * modify the `config` object or create a new one. The function needs to return the `config`
  10559. * object directly, or a promise containing the `config` or a new `config` object.
  10560. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  10561. * resolved with a rejection.
  10562. * * `response`: interceptors get called with http `response` object. The function is free to
  10563. * modify the `response` object or create a new one. The function needs to return the `response`
  10564. * object directly, or as a promise containing the `response` or a new `response` object.
  10565. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  10566. * resolved with a rejection.
  10567. *
  10568. *
  10569. * ```js
  10570. * // register the interceptor as a service
  10571. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  10572. * return {
  10573. * // optional method
  10574. * 'request': function(config) {
  10575. * // do something on success
  10576. * return config;
  10577. * },
  10578. *
  10579. * // optional method
  10580. * 'requestError': function(rejection) {
  10581. * // do something on error
  10582. * if (canRecover(rejection)) {
  10583. * return responseOrNewPromise
  10584. * }
  10585. * return $q.reject(rejection);
  10586. * },
  10587. *
  10588. *
  10589. *
  10590. * // optional method
  10591. * 'response': function(response) {
  10592. * // do something on success
  10593. * return response;
  10594. * },
  10595. *
  10596. * // optional method
  10597. * 'responseError': function(rejection) {
  10598. * // do something on error
  10599. * if (canRecover(rejection)) {
  10600. * return responseOrNewPromise
  10601. * }
  10602. * return $q.reject(rejection);
  10603. * }
  10604. * };
  10605. * });
  10606. *
  10607. * $httpProvider.interceptors.push('myHttpInterceptor');
  10608. *
  10609. *
  10610. * // alternatively, register the interceptor via an anonymous factory
  10611. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  10612. * return {
  10613. * 'request': function(config) {
  10614. * // same as above
  10615. * },
  10616. *
  10617. * 'response': function(response) {
  10618. * // same as above
  10619. * }
  10620. * };
  10621. * });
  10622. * ```
  10623. *
  10624. * ## Security Considerations
  10625. *
  10626. * When designing web applications, consider security threats from:
  10627. *
  10628. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10629. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  10630. *
  10631. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  10632. * pre-configured with strategies that address these issues, but for this to work backend server
  10633. * cooperation is required.
  10634. *
  10635. * ### JSON Vulnerability Protection
  10636. *
  10637. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10638. * allows third party website to turn your JSON resource URL into
  10639. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  10640. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  10641. * Angular will automatically strip the prefix before processing it as JSON.
  10642. *
  10643. * For example if your server needs to return:
  10644. * ```js
  10645. * ['one','two']
  10646. * ```
  10647. *
  10648. * which is vulnerable to attack, your server can return:
  10649. * ```js
  10650. * )]}',
  10651. * ['one','two']
  10652. * ```
  10653. *
  10654. * Angular will strip the prefix, before processing the JSON.
  10655. *
  10656. *
  10657. * ### Cross Site Request Forgery (XSRF) Protection
  10658. *
  10659. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  10660. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  10661. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  10662. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  10663. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  10664. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  10665. * The header will not be set for cross-domain requests.
  10666. *
  10667. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  10668. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  10669. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  10670. * that only JavaScript running on your domain could have sent the request. The token must be
  10671. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  10672. * making up its own tokens). We recommend that the token is a digest of your site's
  10673. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  10674. * for added security.
  10675. *
  10676. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  10677. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  10678. * or the per-request config object.
  10679. *
  10680. * In order to prevent collisions in environments where multiple Angular apps share the
  10681. * same domain or subdomain, we recommend that each application uses unique cookie name.
  10682. *
  10683. * @param {object} config Object describing the request to be made and how it should be
  10684. * processed. The object has following properties:
  10685. *
  10686. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  10687. * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;
  10688. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10689. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  10690. * with the `paramSerializer` and appended as GET parameters.
  10691. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  10692. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  10693. * HTTP headers to send to the server. If the return value of a function is null, the
  10694. * header will not be sent. Functions accept a config object as an argument.
  10695. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  10696. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  10697. * The handler will be called in the context of a `$apply` block.
  10698. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  10699. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  10700. * The handler will be called in the context of a `$apply` block.
  10701. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  10702. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  10703. * - **transformRequest** –
  10704. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  10705. * transform function or an array of such functions. The transform function takes the http
  10706. * request body and headers and returns its transformed (typically serialized) version.
  10707. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10708. * Overriding the Default Transformations}
  10709. * - **transformResponse** –
  10710. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  10711. * transform function or an array of such functions. The transform function takes the http
  10712. * response body, headers and status and returns its transformed (typically deserialized) version.
  10713. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10714. * Overriding the Default Transformations}
  10715. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  10716. * prepare the string representation of request parameters (specified as an object).
  10717. * If specified as string, it is interpreted as function registered with the
  10718. * {@link $injector $injector}, which means you can create your own serializer
  10719. * by registering it as a {@link auto.$provide#service service}.
  10720. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  10721. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  10722. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  10723. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  10724. * See {@link $http#caching $http Caching} for more information.
  10725. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  10726. * that should abort the request when resolved.
  10727. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  10728. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  10729. * for more information.
  10730. * - **responseType** - `{string}` - see
  10731. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  10732. *
  10733. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  10734. * when the request succeeds or fails.
  10735. *
  10736. *
  10737. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  10738. * requests. This is primarily meant to be used for debugging purposes.
  10739. *
  10740. *
  10741. * @example
  10742. <example module="httpExample" name="http-service">
  10743. <file name="index.html">
  10744. <div ng-controller="FetchController">
  10745. <select ng-model="method" aria-label="Request method">
  10746. <option>GET</option>
  10747. <option>JSONP</option>
  10748. </select>
  10749. <input type="text" ng-model="url" size="80" aria-label="URL" />
  10750. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  10751. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  10752. <button id="samplejsonpbtn"
  10753. ng-click="updateModel('JSONP',
  10754. 'https://angularjs.org/greet.php?name=Super%20Hero')">
  10755. Sample JSONP
  10756. </button>
  10757. <button id="invalidjsonpbtn"
  10758. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')">
  10759. Invalid JSONP
  10760. </button>
  10761. <pre>http status code: {{status}}</pre>
  10762. <pre>http response data: {{data}}</pre>
  10763. </div>
  10764. </file>
  10765. <file name="script.js">
  10766. angular.module('httpExample', [])
  10767. .config(['$sceDelegateProvider', function($sceDelegateProvider) {
  10768. // We must whitelist the JSONP endpoint that we are using to show that we trust it
  10769. $sceDelegateProvider.resourceUrlWhitelist([
  10770. 'self',
  10771. 'https://angularjs.org/**'
  10772. ]);
  10773. }])
  10774. .controller('FetchController', ['$scope', '$http', '$templateCache',
  10775. function($scope, $http, $templateCache) {
  10776. $scope.method = 'GET';
  10777. $scope.url = 'http-hello.html';
  10778. $scope.fetch = function() {
  10779. $scope.code = null;
  10780. $scope.response = null;
  10781. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  10782. then(function(response) {
  10783. $scope.status = response.status;
  10784. $scope.data = response.data;
  10785. }, function(response) {
  10786. $scope.data = response.data || 'Request failed';
  10787. $scope.status = response.status;
  10788. });
  10789. };
  10790. $scope.updateModel = function(method, url) {
  10791. $scope.method = method;
  10792. $scope.url = url;
  10793. };
  10794. }]);
  10795. </file>
  10796. <file name="http-hello.html">
  10797. Hello, $http!
  10798. </file>
  10799. <file name="protractor.js" type="protractor">
  10800. var status = element(by.binding('status'));
  10801. var data = element(by.binding('data'));
  10802. var fetchBtn = element(by.id('fetchbtn'));
  10803. var sampleGetBtn = element(by.id('samplegetbtn'));
  10804. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  10805. it('should make an xhr GET request', function() {
  10806. sampleGetBtn.click();
  10807. fetchBtn.click();
  10808. expect(status.getText()).toMatch('200');
  10809. expect(data.getText()).toMatch(/Hello, \$http!/);
  10810. });
  10811. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  10812. // it('should make a JSONP request to angularjs.org', function() {
  10813. // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  10814. // sampleJsonpBtn.click();
  10815. // fetchBtn.click();
  10816. // expect(status.getText()).toMatch('200');
  10817. // expect(data.getText()).toMatch(/Super Hero!/);
  10818. // });
  10819. it('should make JSONP request to invalid URL and invoke the error handler',
  10820. function() {
  10821. invalidJsonpBtn.click();
  10822. fetchBtn.click();
  10823. expect(status.getText()).toMatch('0');
  10824. expect(data.getText()).toMatch('Request failed');
  10825. });
  10826. </file>
  10827. </example>
  10828. */
  10829. function $http(requestConfig) {
  10830. if (!isObject(requestConfig)) {
  10831. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  10832. }
  10833. if (!isString($sce.valueOf(requestConfig.url))) {
  10834. throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
  10835. }
  10836. var config = extend({
  10837. method: 'get',
  10838. transformRequest: defaults.transformRequest,
  10839. transformResponse: defaults.transformResponse,
  10840. paramSerializer: defaults.paramSerializer,
  10841. jsonpCallbackParam: defaults.jsonpCallbackParam
  10842. }, requestConfig);
  10843. config.headers = mergeHeaders(requestConfig);
  10844. config.method = uppercase(config.method);
  10845. config.paramSerializer = isString(config.paramSerializer) ?
  10846. $injector.get(config.paramSerializer) : config.paramSerializer;
  10847. $browser.$$incOutstandingRequestCount();
  10848. var requestInterceptors = [];
  10849. var responseInterceptors = [];
  10850. var promise = $q.resolve(config);
  10851. // apply interceptors
  10852. forEach(reversedInterceptors, function(interceptor) {
  10853. if (interceptor.request || interceptor.requestError) {
  10854. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  10855. }
  10856. if (interceptor.response || interceptor.responseError) {
  10857. responseInterceptors.push(interceptor.response, interceptor.responseError);
  10858. }
  10859. });
  10860. promise = chainInterceptors(promise, requestInterceptors);
  10861. promise = promise.then(serverRequest);
  10862. promise = chainInterceptors(promise, responseInterceptors);
  10863. promise = promise.finally(completeOutstandingRequest);
  10864. return promise;
  10865. function chainInterceptors(promise, interceptors) {
  10866. for (var i = 0, ii = interceptors.length; i < ii;) {
  10867. var thenFn = interceptors[i++];
  10868. var rejectFn = interceptors[i++];
  10869. promise = promise.then(thenFn, rejectFn);
  10870. }
  10871. interceptors.length = 0;
  10872. return promise;
  10873. }
  10874. function completeOutstandingRequest() {
  10875. $browser.$$completeOutstandingRequest(noop);
  10876. }
  10877. function executeHeaderFns(headers, config) {
  10878. var headerContent, processedHeaders = {};
  10879. forEach(headers, function(headerFn, header) {
  10880. if (isFunction(headerFn)) {
  10881. headerContent = headerFn(config);
  10882. if (headerContent != null) {
  10883. processedHeaders[header] = headerContent;
  10884. }
  10885. } else {
  10886. processedHeaders[header] = headerFn;
  10887. }
  10888. });
  10889. return processedHeaders;
  10890. }
  10891. function mergeHeaders(config) {
  10892. var defHeaders = defaults.headers,
  10893. reqHeaders = extend({}, config.headers),
  10894. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  10895. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  10896. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  10897. defaultHeadersIteration:
  10898. for (defHeaderName in defHeaders) {
  10899. lowercaseDefHeaderName = lowercase(defHeaderName);
  10900. for (reqHeaderName in reqHeaders) {
  10901. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  10902. continue defaultHeadersIteration;
  10903. }
  10904. }
  10905. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  10906. }
  10907. // execute if header value is a function for merged headers
  10908. return executeHeaderFns(reqHeaders, shallowCopy(config));
  10909. }
  10910. function serverRequest(config) {
  10911. var headers = config.headers;
  10912. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  10913. // strip content-type if data is undefined
  10914. if (isUndefined(reqData)) {
  10915. forEach(headers, function(value, header) {
  10916. if (lowercase(header) === 'content-type') {
  10917. delete headers[header];
  10918. }
  10919. });
  10920. }
  10921. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  10922. config.withCredentials = defaults.withCredentials;
  10923. }
  10924. // send request
  10925. return sendReq(config, reqData).then(transformResponse, transformResponse);
  10926. }
  10927. function transformResponse(response) {
  10928. // make a copy since the response must be cacheable
  10929. var resp = extend({}, response);
  10930. resp.data = transformData(response.data, response.headers, response.status,
  10931. config.transformResponse);
  10932. return (isSuccess(response.status))
  10933. ? resp
  10934. : $q.reject(resp);
  10935. }
  10936. }
  10937. $http.pendingRequests = [];
  10938. /**
  10939. * @ngdoc method
  10940. * @name $http#get
  10941. *
  10942. * @description
  10943. * Shortcut method to perform `GET` request.
  10944. *
  10945. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10946. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10947. * @param {Object=} config Optional configuration object
  10948. * @returns {HttpPromise} Future object
  10949. */
  10950. /**
  10951. * @ngdoc method
  10952. * @name $http#delete
  10953. *
  10954. * @description
  10955. * Shortcut method to perform `DELETE` request.
  10956. *
  10957. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10958. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10959. * @param {Object=} config Optional configuration object
  10960. * @returns {HttpPromise} Future object
  10961. */
  10962. /**
  10963. * @ngdoc method
  10964. * @name $http#head
  10965. *
  10966. * @description
  10967. * Shortcut method to perform `HEAD` request.
  10968. *
  10969. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10970. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10971. * @param {Object=} config Optional configuration object
  10972. * @returns {HttpPromise} Future object
  10973. */
  10974. /**
  10975. * @ngdoc method
  10976. * @name $http#jsonp
  10977. *
  10978. * @description
  10979. * Shortcut method to perform `JSONP` request.
  10980. *
  10981. * Note that, since JSONP requests are sensitive because the response is given full access to the browser,
  10982. * the url must be declared, via {@link $sce} as a trusted resource URL.
  10983. * You can trust a URL by adding it to the whitelist via
  10984. * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or
  10985. * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
  10986. *
  10987. * JSONP requests must specify a callback to be used in the response from the server. This callback
  10988. * is passed as a query parameter in the request. You must specify the name of this parameter by
  10989. * setting the `jsonpCallbackParam` property on the request config object.
  10990. *
  10991. * ```
  10992. * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
  10993. * ```
  10994. *
  10995. * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.
  10996. * Initially this is set to `'callback'`.
  10997. *
  10998. * <div class="alert alert-danger">
  10999. * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
  11000. * parameter value should go.
  11001. * </div>
  11002. *
  11003. * If you would like to customise where and how the callbacks are stored then try overriding
  11004. * or decorating the {@link $jsonpCallbacks} service.
  11005. *
  11006. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11007. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11008. * @param {Object=} config Optional configuration object
  11009. * @returns {HttpPromise} Future object
  11010. */
  11011. createShortMethods('get', 'delete', 'head', 'jsonp');
  11012. /**
  11013. * @ngdoc method
  11014. * @name $http#post
  11015. *
  11016. * @description
  11017. * Shortcut method to perform `POST` request.
  11018. *
  11019. * @param {string} url Relative or absolute URL specifying the destination of the request
  11020. * @param {*} data Request content
  11021. * @param {Object=} config Optional configuration object
  11022. * @returns {HttpPromise} Future object
  11023. */
  11024. /**
  11025. * @ngdoc method
  11026. * @name $http#put
  11027. *
  11028. * @description
  11029. * Shortcut method to perform `PUT` request.
  11030. *
  11031. * @param {string} url Relative or absolute URL specifying the destination of the request
  11032. * @param {*} data Request content
  11033. * @param {Object=} config Optional configuration object
  11034. * @returns {HttpPromise} Future object
  11035. */
  11036. /**
  11037. * @ngdoc method
  11038. * @name $http#patch
  11039. *
  11040. * @description
  11041. * Shortcut method to perform `PATCH` request.
  11042. *
  11043. * @param {string} url Relative or absolute URL specifying the destination of the request
  11044. * @param {*} data Request content
  11045. * @param {Object=} config Optional configuration object
  11046. * @returns {HttpPromise} Future object
  11047. */
  11048. createShortMethodsWithData('post', 'put', 'patch');
  11049. /**
  11050. * @ngdoc property
  11051. * @name $http#defaults
  11052. *
  11053. * @description
  11054. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  11055. * default headers, withCredentials as well as request and response transformations.
  11056. *
  11057. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  11058. */
  11059. $http.defaults = defaults;
  11060. return $http;
  11061. function createShortMethods(names) {
  11062. forEach(arguments, function(name) {
  11063. $http[name] = function(url, config) {
  11064. return $http(extend({}, config || {}, {
  11065. method: name,
  11066. url: url
  11067. }));
  11068. };
  11069. });
  11070. }
  11071. function createShortMethodsWithData(name) {
  11072. forEach(arguments, function(name) {
  11073. $http[name] = function(url, data, config) {
  11074. return $http(extend({}, config || {}, {
  11075. method: name,
  11076. url: url,
  11077. data: data
  11078. }));
  11079. };
  11080. });
  11081. }
  11082. /**
  11083. * Makes the request.
  11084. *
  11085. * !!! ACCESSES CLOSURE VARS:
  11086. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  11087. */
  11088. function sendReq(config, reqData) {
  11089. var deferred = $q.defer(),
  11090. promise = deferred.promise,
  11091. cache,
  11092. cachedResp,
  11093. reqHeaders = config.headers,
  11094. isJsonp = lowercase(config.method) === 'jsonp',
  11095. url = config.url;
  11096. if (isJsonp) {
  11097. // JSONP is a pretty sensitive operation where we're allowing a script to have full access to
  11098. // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
  11099. url = $sce.getTrustedResourceUrl(url);
  11100. } else if (!isString(url)) {
  11101. // If it is not a string then the URL must be a $sce trusted object
  11102. url = $sce.valueOf(url);
  11103. }
  11104. url = buildUrl(url, config.paramSerializer(config.params));
  11105. if (isJsonp) {
  11106. // Check the url and add the JSONP callback placeholder
  11107. url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);
  11108. }
  11109. $http.pendingRequests.push(config);
  11110. promise.then(removePendingReq, removePendingReq);
  11111. if ((config.cache || defaults.cache) && config.cache !== false &&
  11112. (config.method === 'GET' || config.method === 'JSONP')) {
  11113. cache = isObject(config.cache) ? config.cache
  11114. : isObject(/** @type {?} */ (defaults).cache)
  11115. ? /** @type {?} */ (defaults).cache
  11116. : defaultCache;
  11117. }
  11118. if (cache) {
  11119. cachedResp = cache.get(url);
  11120. if (isDefined(cachedResp)) {
  11121. if (isPromiseLike(cachedResp)) {
  11122. // cached request has already been sent, but there is no response yet
  11123. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  11124. } else {
  11125. // serving from cache
  11126. if (isArray(cachedResp)) {
  11127. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  11128. } else {
  11129. resolvePromise(cachedResp, 200, {}, 'OK');
  11130. }
  11131. }
  11132. } else {
  11133. // put the promise for the non-transformed response into cache as a placeholder
  11134. cache.put(url, promise);
  11135. }
  11136. }
  11137. // if we won't have the response in cache, set the xsrf headers and
  11138. // send the request to the backend
  11139. if (isUndefined(cachedResp)) {
  11140. var xsrfValue = urlIsSameOrigin(config.url)
  11141. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  11142. : undefined;
  11143. if (xsrfValue) {
  11144. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  11145. }
  11146. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  11147. config.withCredentials, config.responseType,
  11148. createApplyHandlers(config.eventHandlers),
  11149. createApplyHandlers(config.uploadEventHandlers));
  11150. }
  11151. return promise;
  11152. function createApplyHandlers(eventHandlers) {
  11153. if (eventHandlers) {
  11154. var applyHandlers = {};
  11155. forEach(eventHandlers, function(eventHandler, key) {
  11156. applyHandlers[key] = function(event) {
  11157. if (useApplyAsync) {
  11158. $rootScope.$applyAsync(callEventHandler);
  11159. } else if ($rootScope.$$phase) {
  11160. callEventHandler();
  11161. } else {
  11162. $rootScope.$apply(callEventHandler);
  11163. }
  11164. function callEventHandler() {
  11165. eventHandler(event);
  11166. }
  11167. };
  11168. });
  11169. return applyHandlers;
  11170. }
  11171. }
  11172. /**
  11173. * Callback registered to $httpBackend():
  11174. * - caches the response if desired
  11175. * - resolves the raw $http promise
  11176. * - calls $apply
  11177. */
  11178. function done(status, response, headersString, statusText) {
  11179. if (cache) {
  11180. if (isSuccess(status)) {
  11181. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  11182. } else {
  11183. // remove promise from the cache
  11184. cache.remove(url);
  11185. }
  11186. }
  11187. function resolveHttpPromise() {
  11188. resolvePromise(response, status, headersString, statusText);
  11189. }
  11190. if (useApplyAsync) {
  11191. $rootScope.$applyAsync(resolveHttpPromise);
  11192. } else {
  11193. resolveHttpPromise();
  11194. if (!$rootScope.$$phase) $rootScope.$apply();
  11195. }
  11196. }
  11197. /**
  11198. * Resolves the raw $http promise.
  11199. */
  11200. function resolvePromise(response, status, headers, statusText) {
  11201. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  11202. status = status >= -1 ? status : 0;
  11203. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  11204. data: response,
  11205. status: status,
  11206. headers: headersGetter(headers),
  11207. config: config,
  11208. statusText: statusText
  11209. });
  11210. }
  11211. function resolvePromiseWithResult(result) {
  11212. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  11213. }
  11214. function removePendingReq() {
  11215. var idx = $http.pendingRequests.indexOf(config);
  11216. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  11217. }
  11218. }
  11219. function buildUrl(url, serializedParams) {
  11220. if (serializedParams.length > 0) {
  11221. url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
  11222. }
  11223. return url;
  11224. }
  11225. function sanitizeJsonpCallbackParam(url, key) {
  11226. if (/[&?][^=]+=JSON_CALLBACK/.test(url)) {
  11227. // Throw if the url already contains a reference to JSON_CALLBACK
  11228. throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
  11229. }
  11230. var callbackParamRegex = new RegExp('[&?]' + key + '=');
  11231. if (callbackParamRegex.test(url)) {
  11232. // Throw if the callback param was already provided
  11233. throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', key, url);
  11234. }
  11235. // Add in the JSON_CALLBACK callback param value
  11236. url += ((url.indexOf('?') === -1) ? '?' : '&') + key + '=JSON_CALLBACK';
  11237. return url;
  11238. }
  11239. }];
  11240. }
  11241. /**
  11242. * @ngdoc service
  11243. * @name $xhrFactory
  11244. * @this
  11245. *
  11246. * @description
  11247. * Factory function used to create XMLHttpRequest objects.
  11248. *
  11249. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  11250. *
  11251. * ```
  11252. * angular.module('myApp', [])
  11253. * .factory('$xhrFactory', function() {
  11254. * return function createXhr(method, url) {
  11255. * return new window.XMLHttpRequest({mozSystem: true});
  11256. * };
  11257. * });
  11258. * ```
  11259. *
  11260. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  11261. * @param {string} url URL of the request.
  11262. */
  11263. function $xhrFactoryProvider() {
  11264. this.$get = function() {
  11265. return function createXhr() {
  11266. return new window.XMLHttpRequest();
  11267. };
  11268. };
  11269. }
  11270. /**
  11271. * @ngdoc service
  11272. * @name $httpBackend
  11273. * @requires $jsonpCallbacks
  11274. * @requires $document
  11275. * @requires $xhrFactory
  11276. * @this
  11277. *
  11278. * @description
  11279. * HTTP backend used by the {@link ng.$http service} that delegates to
  11280. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  11281. *
  11282. * You should never need to use this service directly, instead use the higher-level abstractions:
  11283. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  11284. *
  11285. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  11286. * $httpBackend} which can be trained with responses.
  11287. */
  11288. function $HttpBackendProvider() {
  11289. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  11290. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  11291. }];
  11292. }
  11293. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  11294. // TODO(vojta): fix the signature
  11295. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  11296. url = url || $browser.url();
  11297. if (lowercase(method) === 'jsonp') {
  11298. var callbackPath = callbacks.createCallback(url);
  11299. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  11300. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  11301. var response = (status === 200) && callbacks.getResponse(callbackPath);
  11302. completeRequest(callback, status, response, '', text);
  11303. callbacks.removeCallback(callbackPath);
  11304. });
  11305. } else {
  11306. var xhr = createXhr(method, url);
  11307. xhr.open(method, url, true);
  11308. forEach(headers, function(value, key) {
  11309. if (isDefined(value)) {
  11310. xhr.setRequestHeader(key, value);
  11311. }
  11312. });
  11313. xhr.onload = function requestLoaded() {
  11314. var statusText = xhr.statusText || '';
  11315. // responseText is the old-school way of retrieving response (supported by IE9)
  11316. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  11317. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  11318. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  11319. var status = xhr.status === 1223 ? 204 : xhr.status;
  11320. // fix status code when it is 0 (0 status is undocumented).
  11321. // Occurs when accessing file resources or on Android 4.1 stock browser
  11322. // while retrieving files from application cache.
  11323. if (status === 0) {
  11324. status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
  11325. }
  11326. completeRequest(callback,
  11327. status,
  11328. response,
  11329. xhr.getAllResponseHeaders(),
  11330. statusText);
  11331. };
  11332. var requestError = function() {
  11333. // The response is always empty
  11334. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11335. completeRequest(callback, -1, null, null, '');
  11336. };
  11337. xhr.onerror = requestError;
  11338. xhr.onabort = requestError;
  11339. xhr.ontimeout = requestError;
  11340. forEach(eventHandlers, function(value, key) {
  11341. xhr.addEventListener(key, value);
  11342. });
  11343. forEach(uploadEventHandlers, function(value, key) {
  11344. xhr.upload.addEventListener(key, value);
  11345. });
  11346. if (withCredentials) {
  11347. xhr.withCredentials = true;
  11348. }
  11349. if (responseType) {
  11350. try {
  11351. xhr.responseType = responseType;
  11352. } catch (e) {
  11353. // WebKit added support for the json responseType value on 09/03/2013
  11354. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  11355. // known to throw when setting the value "json" as the response type. Other older
  11356. // browsers implementing the responseType
  11357. //
  11358. // The json response type can be ignored if not supported, because JSON payloads are
  11359. // parsed on the client-side regardless.
  11360. if (responseType !== 'json') {
  11361. throw e;
  11362. }
  11363. }
  11364. }
  11365. xhr.send(isUndefined(post) ? null : post);
  11366. }
  11367. if (timeout > 0) {
  11368. var timeoutId = $browserDefer(timeoutRequest, timeout);
  11369. } else if (isPromiseLike(timeout)) {
  11370. timeout.then(timeoutRequest);
  11371. }
  11372. function timeoutRequest() {
  11373. if (jsonpDone) {
  11374. jsonpDone();
  11375. }
  11376. if (xhr) {
  11377. xhr.abort();
  11378. }
  11379. }
  11380. function completeRequest(callback, status, response, headersString, statusText) {
  11381. // cancel timeout and subsequent timeout promise resolution
  11382. if (isDefined(timeoutId)) {
  11383. $browserDefer.cancel(timeoutId);
  11384. }
  11385. jsonpDone = xhr = null;
  11386. callback(status, response, headersString, statusText);
  11387. }
  11388. };
  11389. function jsonpReq(url, callbackPath, done) {
  11390. url = url.replace('JSON_CALLBACK', callbackPath);
  11391. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  11392. // - fetches local scripts via XHR and evals them
  11393. // - adds and immediately removes script elements from the document
  11394. var script = rawDocument.createElement('script'), callback = null;
  11395. script.type = 'text/javascript';
  11396. script.src = url;
  11397. script.async = true;
  11398. callback = function(event) {
  11399. script.removeEventListener('load', callback);
  11400. script.removeEventListener('error', callback);
  11401. rawDocument.body.removeChild(script);
  11402. script = null;
  11403. var status = -1;
  11404. var text = 'unknown';
  11405. if (event) {
  11406. if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
  11407. event = { type: 'error' };
  11408. }
  11409. text = event.type;
  11410. status = event.type === 'error' ? 404 : 200;
  11411. }
  11412. if (done) {
  11413. done(status, text);
  11414. }
  11415. };
  11416. script.addEventListener('load', callback);
  11417. script.addEventListener('error', callback);
  11418. rawDocument.body.appendChild(script);
  11419. return callback;
  11420. }
  11421. }
  11422. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  11423. $interpolateMinErr.throwNoconcat = function(text) {
  11424. throw $interpolateMinErr('noconcat',
  11425. 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
  11426. 'interpolations that concatenate multiple expressions when a trusted value is ' +
  11427. 'required. See http://docs.angularjs.org/api/ng.$sce', text);
  11428. };
  11429. $interpolateMinErr.interr = function(text, err) {
  11430. return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
  11431. };
  11432. /**
  11433. * @ngdoc provider
  11434. * @name $interpolateProvider
  11435. * @this
  11436. *
  11437. * @description
  11438. *
  11439. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  11440. *
  11441. * <div class="alert alert-danger">
  11442. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  11443. * template within a Python Jinja template (or any other template language). Mixing templating
  11444. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  11445. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  11446. * security bugs!
  11447. * </div>
  11448. *
  11449. * @example
  11450. <example name="custom-interpolation-markup" module="customInterpolationApp">
  11451. <file name="index.html">
  11452. <script>
  11453. var customInterpolationApp = angular.module('customInterpolationApp', []);
  11454. customInterpolationApp.config(function($interpolateProvider) {
  11455. $interpolateProvider.startSymbol('//');
  11456. $interpolateProvider.endSymbol('//');
  11457. });
  11458. customInterpolationApp.controller('DemoController', function() {
  11459. this.label = "This binding is brought you by // interpolation symbols.";
  11460. });
  11461. </script>
  11462. <div ng-controller="DemoController as demo">
  11463. //demo.label//
  11464. </div>
  11465. </file>
  11466. <file name="protractor.js" type="protractor">
  11467. it('should interpolate binding with custom symbols', function() {
  11468. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  11469. });
  11470. </file>
  11471. </example>
  11472. */
  11473. function $InterpolateProvider() {
  11474. var startSymbol = '{{';
  11475. var endSymbol = '}}';
  11476. /**
  11477. * @ngdoc method
  11478. * @name $interpolateProvider#startSymbol
  11479. * @description
  11480. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  11481. *
  11482. * @param {string=} value new value to set the starting symbol to.
  11483. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11484. */
  11485. this.startSymbol = function(value) {
  11486. if (value) {
  11487. startSymbol = value;
  11488. return this;
  11489. } else {
  11490. return startSymbol;
  11491. }
  11492. };
  11493. /**
  11494. * @ngdoc method
  11495. * @name $interpolateProvider#endSymbol
  11496. * @description
  11497. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11498. *
  11499. * @param {string=} value new value to set the ending symbol to.
  11500. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11501. */
  11502. this.endSymbol = function(value) {
  11503. if (value) {
  11504. endSymbol = value;
  11505. return this;
  11506. } else {
  11507. return endSymbol;
  11508. }
  11509. };
  11510. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  11511. var startSymbolLength = startSymbol.length,
  11512. endSymbolLength = endSymbol.length,
  11513. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  11514. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  11515. function escape(ch) {
  11516. return '\\\\\\' + ch;
  11517. }
  11518. function unescapeText(text) {
  11519. return text.replace(escapedStartRegexp, startSymbol).
  11520. replace(escapedEndRegexp, endSymbol);
  11521. }
  11522. // TODO: this is the same as the constantWatchDelegate in parse.js
  11523. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  11524. var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  11525. unwatch();
  11526. return constantInterp(scope);
  11527. }, listener, objectEquality);
  11528. return unwatch;
  11529. }
  11530. /**
  11531. * @ngdoc service
  11532. * @name $interpolate
  11533. * @kind function
  11534. *
  11535. * @requires $parse
  11536. * @requires $sce
  11537. *
  11538. * @description
  11539. *
  11540. * Compiles a string with markup into an interpolation function. This service is used by the
  11541. * HTML {@link ng.$compile $compile} service for data binding. See
  11542. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  11543. * interpolation markup.
  11544. *
  11545. *
  11546. * ```js
  11547. * var $interpolate = ...; // injected
  11548. * var exp = $interpolate('Hello {{name | uppercase}}!');
  11549. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  11550. * ```
  11551. *
  11552. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  11553. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  11554. * evaluate to a value other than `undefined`.
  11555. *
  11556. * ```js
  11557. * var $interpolate = ...; // injected
  11558. * var context = {greeting: 'Hello', name: undefined };
  11559. *
  11560. * // default "forgiving" mode
  11561. * var exp = $interpolate('{{greeting}} {{name}}!');
  11562. * expect(exp(context)).toEqual('Hello !');
  11563. *
  11564. * // "allOrNothing" mode
  11565. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  11566. * expect(exp(context)).toBeUndefined();
  11567. * context.name = 'Angular';
  11568. * expect(exp(context)).toEqual('Hello Angular!');
  11569. * ```
  11570. *
  11571. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  11572. *
  11573. * #### Escaped Interpolation
  11574. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  11575. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  11576. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  11577. * or binding.
  11578. *
  11579. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  11580. * degree, while also enabling code examples to work without relying on the
  11581. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  11582. *
  11583. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  11584. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  11585. * interpolation start/end markers with their escaped counterparts.**
  11586. *
  11587. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  11588. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  11589. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  11590. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  11591. * this is typically useful only when user-data is used in rendering a template from the server, or
  11592. * when otherwise untrusted data is used by a directive.
  11593. *
  11594. * <example name="interpolation">
  11595. * <file name="index.html">
  11596. * <div ng-init="username='A user'">
  11597. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  11598. * </p>
  11599. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  11600. * application, but fails to accomplish their task, because the server has correctly
  11601. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  11602. * characters.</p>
  11603. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  11604. * from the database by an administrator.</p>
  11605. * </div>
  11606. * </file>
  11607. * </example>
  11608. *
  11609. * @knownIssue
  11610. * It is currently not possible for an interpolated expression to contain the interpolation end
  11611. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  11612. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  11613. *
  11614. * @knownIssue
  11615. * All directives and components must use the standard `{{` `}}` interpolation symbols
  11616. * in their templates. If you change the application interpolation symbols the {@link $compile}
  11617. * service will attempt to denormalize the standard symbols to the custom symbols.
  11618. * The denormalization process is not clever enough to know not to replace instances of the standard
  11619. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  11620. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  11621. *
  11622. * ```
  11623. * <div data-context='{"context":{"id":3,"type":"page"}}">
  11624. * ```
  11625. *
  11626. * The workaround is to ensure that such instances are separated by whitespace:
  11627. * ```
  11628. * <div data-context='{"context":{"id":3,"type":"page"} }">
  11629. * ```
  11630. *
  11631. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  11632. *
  11633. * @param {string} text The text with markup to interpolate.
  11634. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  11635. * embedded expression in order to return an interpolation function. Strings with no
  11636. * embedded expression will return null for the interpolation function.
  11637. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  11638. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  11639. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  11640. * provides Strict Contextual Escaping for details.
  11641. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  11642. * unless all embedded expressions evaluate to a value other than `undefined`.
  11643. * @returns {function(context)} an interpolation function which is used to compute the
  11644. * interpolated string. The function has these parameters:
  11645. *
  11646. * - `context`: evaluation context for all expressions embedded in the interpolated text
  11647. */
  11648. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  11649. // Provide a quick exit and simplified result function for text with no interpolation
  11650. if (!text.length || text.indexOf(startSymbol) === -1) {
  11651. var constantInterp;
  11652. if (!mustHaveExpression) {
  11653. var unescapedText = unescapeText(text);
  11654. constantInterp = valueFn(unescapedText);
  11655. constantInterp.exp = text;
  11656. constantInterp.expressions = [];
  11657. constantInterp.$$watchDelegate = constantWatchDelegate;
  11658. }
  11659. return constantInterp;
  11660. }
  11661. allOrNothing = !!allOrNothing;
  11662. var startIndex,
  11663. endIndex,
  11664. index = 0,
  11665. expressions = [],
  11666. parseFns = [],
  11667. textLength = text.length,
  11668. exp,
  11669. concat = [],
  11670. expressionPositions = [];
  11671. while (index < textLength) {
  11672. if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
  11673. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
  11674. if (index !== startIndex) {
  11675. concat.push(unescapeText(text.substring(index, startIndex)));
  11676. }
  11677. exp = text.substring(startIndex + startSymbolLength, endIndex);
  11678. expressions.push(exp);
  11679. parseFns.push($parse(exp, parseStringifyInterceptor));
  11680. index = endIndex + endSymbolLength;
  11681. expressionPositions.push(concat.length);
  11682. concat.push('');
  11683. } else {
  11684. // we did not find an interpolation, so we have to add the remainder to the separators array
  11685. if (index !== textLength) {
  11686. concat.push(unescapeText(text.substring(index)));
  11687. }
  11688. break;
  11689. }
  11690. }
  11691. // Concatenating expressions makes it hard to reason about whether some combination of
  11692. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  11693. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  11694. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  11695. // make it obvious that you bound the value to some user controlled value. This helps reduce
  11696. // the load when auditing for XSS issues.
  11697. if (trustedContext && concat.length > 1) {
  11698. $interpolateMinErr.throwNoconcat(text);
  11699. }
  11700. if (!mustHaveExpression || expressions.length) {
  11701. var compute = function(values) {
  11702. for (var i = 0, ii = expressions.length; i < ii; i++) {
  11703. if (allOrNothing && isUndefined(values[i])) return;
  11704. concat[expressionPositions[i]] = values[i];
  11705. }
  11706. return concat.join('');
  11707. };
  11708. var getValue = function(value) {
  11709. return trustedContext ?
  11710. $sce.getTrusted(trustedContext, value) :
  11711. $sce.valueOf(value);
  11712. };
  11713. return extend(function interpolationFn(context) {
  11714. var i = 0;
  11715. var ii = expressions.length;
  11716. var values = new Array(ii);
  11717. try {
  11718. for (; i < ii; i++) {
  11719. values[i] = parseFns[i](context);
  11720. }
  11721. return compute(values);
  11722. } catch (err) {
  11723. $exceptionHandler($interpolateMinErr.interr(text, err));
  11724. }
  11725. }, {
  11726. // all of these properties are undocumented for now
  11727. exp: text, //just for compatibility with regular watchers created via $watch
  11728. expressions: expressions,
  11729. $$watchDelegate: function(scope, listener) {
  11730. var lastValue;
  11731. return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
  11732. var currValue = compute(values);
  11733. if (isFunction(listener)) {
  11734. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  11735. }
  11736. lastValue = currValue;
  11737. });
  11738. }
  11739. });
  11740. }
  11741. function parseStringifyInterceptor(value) {
  11742. try {
  11743. value = getValue(value);
  11744. return allOrNothing && !isDefined(value) ? value : stringify(value);
  11745. } catch (err) {
  11746. $exceptionHandler($interpolateMinErr.interr(text, err));
  11747. }
  11748. }
  11749. }
  11750. /**
  11751. * @ngdoc method
  11752. * @name $interpolate#startSymbol
  11753. * @description
  11754. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  11755. *
  11756. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  11757. * the symbol.
  11758. *
  11759. * @returns {string} start symbol.
  11760. */
  11761. $interpolate.startSymbol = function() {
  11762. return startSymbol;
  11763. };
  11764. /**
  11765. * @ngdoc method
  11766. * @name $interpolate#endSymbol
  11767. * @description
  11768. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11769. *
  11770. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  11771. * the symbol.
  11772. *
  11773. * @returns {string} end symbol.
  11774. */
  11775. $interpolate.endSymbol = function() {
  11776. return endSymbol;
  11777. };
  11778. return $interpolate;
  11779. }];
  11780. }
  11781. /** @this */
  11782. function $IntervalProvider() {
  11783. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  11784. function($rootScope, $window, $q, $$q, $browser) {
  11785. var intervals = {};
  11786. /**
  11787. * @ngdoc service
  11788. * @name $interval
  11789. *
  11790. * @description
  11791. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  11792. * milliseconds.
  11793. *
  11794. * The return value of registering an interval function is a promise. This promise will be
  11795. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  11796. * run indefinitely if `count` is not defined. The value of the notification will be the
  11797. * number of iterations that have run.
  11798. * To cancel an interval, call `$interval.cancel(promise)`.
  11799. *
  11800. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  11801. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  11802. * time.
  11803. *
  11804. * <div class="alert alert-warning">
  11805. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  11806. * with them. In particular they are not automatically destroyed when a controller's scope or a
  11807. * directive's element are destroyed.
  11808. * You should take this into consideration and make sure to always cancel the interval at the
  11809. * appropriate moment. See the example below for more details on how and when to do this.
  11810. * </div>
  11811. *
  11812. * @param {function()} fn A function that should be called repeatedly. If no additional arguments
  11813. * are passed (see below), the function is called with the current iteration count.
  11814. * @param {number} delay Number of milliseconds between each function call.
  11815. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  11816. * indefinitely.
  11817. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  11818. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  11819. * @param {...*=} Pass additional parameters to the executed function.
  11820. * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete.
  11821. *
  11822. * @example
  11823. * <example module="intervalExample" name="interval-service">
  11824. * <file name="index.html">
  11825. * <script>
  11826. * angular.module('intervalExample', [])
  11827. * .controller('ExampleController', ['$scope', '$interval',
  11828. * function($scope, $interval) {
  11829. * $scope.format = 'M/d/yy h:mm:ss a';
  11830. * $scope.blood_1 = 100;
  11831. * $scope.blood_2 = 120;
  11832. *
  11833. * var stop;
  11834. * $scope.fight = function() {
  11835. * // Don't start a new fight if we are already fighting
  11836. * if ( angular.isDefined(stop) ) return;
  11837. *
  11838. * stop = $interval(function() {
  11839. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  11840. * $scope.blood_1 = $scope.blood_1 - 3;
  11841. * $scope.blood_2 = $scope.blood_2 - 4;
  11842. * } else {
  11843. * $scope.stopFight();
  11844. * }
  11845. * }, 100);
  11846. * };
  11847. *
  11848. * $scope.stopFight = function() {
  11849. * if (angular.isDefined(stop)) {
  11850. * $interval.cancel(stop);
  11851. * stop = undefined;
  11852. * }
  11853. * };
  11854. *
  11855. * $scope.resetFight = function() {
  11856. * $scope.blood_1 = 100;
  11857. * $scope.blood_2 = 120;
  11858. * };
  11859. *
  11860. * $scope.$on('$destroy', function() {
  11861. * // Make sure that the interval is destroyed too
  11862. * $scope.stopFight();
  11863. * });
  11864. * }])
  11865. * // Register the 'myCurrentTime' directive factory method.
  11866. * // We inject $interval and dateFilter service since the factory method is DI.
  11867. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  11868. * function($interval, dateFilter) {
  11869. * // return the directive link function. (compile function not needed)
  11870. * return function(scope, element, attrs) {
  11871. * var format, // date format
  11872. * stopTime; // so that we can cancel the time updates
  11873. *
  11874. * // used to update the UI
  11875. * function updateTime() {
  11876. * element.text(dateFilter(new Date(), format));
  11877. * }
  11878. *
  11879. * // watch the expression, and update the UI on change.
  11880. * scope.$watch(attrs.myCurrentTime, function(value) {
  11881. * format = value;
  11882. * updateTime();
  11883. * });
  11884. *
  11885. * stopTime = $interval(updateTime, 1000);
  11886. *
  11887. * // listen on DOM destroy (removal) event, and cancel the next UI update
  11888. * // to prevent updating time after the DOM element was removed.
  11889. * element.on('$destroy', function() {
  11890. * $interval.cancel(stopTime);
  11891. * });
  11892. * }
  11893. * }]);
  11894. * </script>
  11895. *
  11896. * <div>
  11897. * <div ng-controller="ExampleController">
  11898. * <label>Date format: <input ng-model="format"></label> <hr/>
  11899. * Current time is: <span my-current-time="format"></span>
  11900. * <hr/>
  11901. * Blood 1 : <font color='red'>{{blood_1}}</font>
  11902. * Blood 2 : <font color='red'>{{blood_2}}</font>
  11903. * <button type="button" data-ng-click="fight()">Fight</button>
  11904. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  11905. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  11906. * </div>
  11907. * </div>
  11908. *
  11909. * </file>
  11910. * </example>
  11911. */
  11912. function interval(fn, delay, count, invokeApply) {
  11913. var hasParams = arguments.length > 4,
  11914. args = hasParams ? sliceArgs(arguments, 4) : [],
  11915. setInterval = $window.setInterval,
  11916. clearInterval = $window.clearInterval,
  11917. iteration = 0,
  11918. skipApply = (isDefined(invokeApply) && !invokeApply),
  11919. deferred = (skipApply ? $$q : $q).defer(),
  11920. promise = deferred.promise;
  11921. count = isDefined(count) ? count : 0;
  11922. promise.$$intervalId = setInterval(function tick() {
  11923. if (skipApply) {
  11924. $browser.defer(callback);
  11925. } else {
  11926. $rootScope.$evalAsync(callback);
  11927. }
  11928. deferred.notify(iteration++);
  11929. if (count > 0 && iteration >= count) {
  11930. deferred.resolve(iteration);
  11931. clearInterval(promise.$$intervalId);
  11932. delete intervals[promise.$$intervalId];
  11933. }
  11934. if (!skipApply) $rootScope.$apply();
  11935. }, delay);
  11936. intervals[promise.$$intervalId] = deferred;
  11937. return promise;
  11938. function callback() {
  11939. if (!hasParams) {
  11940. fn(iteration);
  11941. } else {
  11942. fn.apply(null, args);
  11943. }
  11944. }
  11945. }
  11946. /**
  11947. * @ngdoc method
  11948. * @name $interval#cancel
  11949. *
  11950. * @description
  11951. * Cancels a task associated with the `promise`.
  11952. *
  11953. * @param {Promise=} promise returned by the `$interval` function.
  11954. * @returns {boolean} Returns `true` if the task was successfully canceled.
  11955. */
  11956. interval.cancel = function(promise) {
  11957. if (promise && promise.$$intervalId in intervals) {
  11958. // Interval cancels should not report as unhandled promise.
  11959. intervals[promise.$$intervalId].promise.catch(noop);
  11960. intervals[promise.$$intervalId].reject('canceled');
  11961. $window.clearInterval(promise.$$intervalId);
  11962. delete intervals[promise.$$intervalId];
  11963. return true;
  11964. }
  11965. return false;
  11966. };
  11967. return interval;
  11968. }];
  11969. }
  11970. /**
  11971. * @ngdoc service
  11972. * @name $jsonpCallbacks
  11973. * @requires $window
  11974. * @description
  11975. * This service handles the lifecycle of callbacks to handle JSONP requests.
  11976. * Override this service if you wish to customise where the callbacks are stored and
  11977. * how they vary compared to the requested url.
  11978. */
  11979. var $jsonpCallbacksProvider = /** @this */ function() {
  11980. this.$get = function() {
  11981. var callbacks = angular.callbacks;
  11982. var callbackMap = {};
  11983. function createCallback(callbackId) {
  11984. var callback = function(data) {
  11985. callback.data = data;
  11986. callback.called = true;
  11987. };
  11988. callback.id = callbackId;
  11989. return callback;
  11990. }
  11991. return {
  11992. /**
  11993. * @ngdoc method
  11994. * @name $jsonpCallbacks#createCallback
  11995. * @param {string} url the url of the JSONP request
  11996. * @returns {string} the callback path to send to the server as part of the JSONP request
  11997. * @description
  11998. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  11999. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  12000. */
  12001. createCallback: function(url) {
  12002. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  12003. var callbackPath = 'angular.callbacks.' + callbackId;
  12004. var callback = createCallback(callbackId);
  12005. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  12006. return callbackPath;
  12007. },
  12008. /**
  12009. * @ngdoc method
  12010. * @name $jsonpCallbacks#wasCalled
  12011. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12012. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  12013. * @description
  12014. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  12015. * callback that was passed in the request.
  12016. */
  12017. wasCalled: function(callbackPath) {
  12018. return callbackMap[callbackPath].called;
  12019. },
  12020. /**
  12021. * @ngdoc method
  12022. * @name $jsonpCallbacks#getResponse
  12023. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12024. * @returns {*} the data received from the response via the registered callback
  12025. * @description
  12026. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  12027. * in the JSONP response.
  12028. */
  12029. getResponse: function(callbackPath) {
  12030. return callbackMap[callbackPath].data;
  12031. },
  12032. /**
  12033. * @ngdoc method
  12034. * @name $jsonpCallbacks#removeCallback
  12035. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12036. * @description
  12037. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  12038. * completed or timed-out.
  12039. */
  12040. removeCallback: function(callbackPath) {
  12041. var callback = callbackMap[callbackPath];
  12042. delete callbacks[callback.id];
  12043. delete callbackMap[callbackPath];
  12044. }
  12045. };
  12046. };
  12047. };
  12048. /**
  12049. * @ngdoc service
  12050. * @name $locale
  12051. *
  12052. * @description
  12053. * $locale service provides localization rules for various Angular components. As of right now the
  12054. * only public api is:
  12055. *
  12056. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  12057. */
  12058. var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
  12059. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  12060. var $locationMinErr = minErr('$location');
  12061. /**
  12062. * Encode path using encodeUriSegment, ignoring forward slashes
  12063. *
  12064. * @param {string} path Path to encode
  12065. * @returns {string}
  12066. */
  12067. function encodePath(path) {
  12068. var segments = path.split('/'),
  12069. i = segments.length;
  12070. while (i--) {
  12071. segments[i] = encodeUriSegment(segments[i]);
  12072. }
  12073. return segments.join('/');
  12074. }
  12075. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  12076. var parsedUrl = urlResolve(absoluteUrl);
  12077. locationObj.$$protocol = parsedUrl.protocol;
  12078. locationObj.$$host = parsedUrl.hostname;
  12079. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  12080. }
  12081. var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
  12082. function parseAppUrl(url, locationObj) {
  12083. if (DOUBLE_SLASH_REGEX.test(url)) {
  12084. throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
  12085. }
  12086. var prefixed = (url.charAt(0) !== '/');
  12087. if (prefixed) {
  12088. url = '/' + url;
  12089. }
  12090. var match = urlResolve(url);
  12091. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  12092. match.pathname.substring(1) : match.pathname);
  12093. locationObj.$$search = parseKeyValue(match.search);
  12094. locationObj.$$hash = decodeURIComponent(match.hash);
  12095. // make sure path starts with '/';
  12096. if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
  12097. locationObj.$$path = '/' + locationObj.$$path;
  12098. }
  12099. }
  12100. function startsWith(str, search) {
  12101. return str.slice(0, search.length) === search;
  12102. }
  12103. /**
  12104. *
  12105. * @param {string} base
  12106. * @param {string} url
  12107. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  12108. * the expected string.
  12109. */
  12110. function stripBaseUrl(base, url) {
  12111. if (startsWith(url, base)) {
  12112. return url.substr(base.length);
  12113. }
  12114. }
  12115. function stripHash(url) {
  12116. var index = url.indexOf('#');
  12117. return index === -1 ? url : url.substr(0, index);
  12118. }
  12119. function trimEmptyHash(url) {
  12120. return url.replace(/(#.+)|#$/, '$1');
  12121. }
  12122. function stripFile(url) {
  12123. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  12124. }
  12125. /* return the server only (scheme://host:port) */
  12126. function serverBase(url) {
  12127. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  12128. }
  12129. /**
  12130. * LocationHtml5Url represents a URL
  12131. * This object is exposed as $location service when HTML5 mode is enabled and supported
  12132. *
  12133. * @constructor
  12134. * @param {string} appBase application base URL
  12135. * @param {string} appBaseNoFile application base URL stripped of any filename
  12136. * @param {string} basePrefix URL path prefix
  12137. */
  12138. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  12139. this.$$html5 = true;
  12140. basePrefix = basePrefix || '';
  12141. parseAbsoluteUrl(appBase, this);
  12142. /**
  12143. * Parse given HTML5 (regular) URL string into properties
  12144. * @param {string} url HTML5 URL
  12145. * @private
  12146. */
  12147. this.$$parse = function(url) {
  12148. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  12149. if (!isString(pathUrl)) {
  12150. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  12151. appBaseNoFile);
  12152. }
  12153. parseAppUrl(pathUrl, this);
  12154. if (!this.$$path) {
  12155. this.$$path = '/';
  12156. }
  12157. this.$$compose();
  12158. };
  12159. /**
  12160. * Compose url and update `absUrl` property
  12161. * @private
  12162. */
  12163. this.$$compose = function() {
  12164. var search = toKeyValue(this.$$search),
  12165. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12166. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12167. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  12168. this.$$urlUpdatedByLocation = true;
  12169. };
  12170. this.$$parseLinkUrl = function(url, relHref) {
  12171. if (relHref && relHref[0] === '#') {
  12172. // special case for links to hash fragments:
  12173. // keep the old url and only replace the hash fragment
  12174. this.hash(relHref.slice(1));
  12175. return true;
  12176. }
  12177. var appUrl, prevAppUrl;
  12178. var rewrittenUrl;
  12179. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  12180. prevAppUrl = appUrl;
  12181. if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  12182. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  12183. } else {
  12184. rewrittenUrl = appBase + prevAppUrl;
  12185. }
  12186. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12187. rewrittenUrl = appBaseNoFile + appUrl;
  12188. } else if (appBaseNoFile === url + '/') {
  12189. rewrittenUrl = appBaseNoFile;
  12190. }
  12191. if (rewrittenUrl) {
  12192. this.$$parse(rewrittenUrl);
  12193. }
  12194. return !!rewrittenUrl;
  12195. };
  12196. }
  12197. /**
  12198. * LocationHashbangUrl represents URL
  12199. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  12200. * It also serves as the base class for html5 mode fallback on legacy browsers.
  12201. *
  12202. * @constructor
  12203. * @param {string} appBase application base URL
  12204. * @param {string} appBaseNoFile application base URL stripped of any filename
  12205. * @param {string} hashPrefix hashbang prefix
  12206. */
  12207. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  12208. parseAbsoluteUrl(appBase, this);
  12209. /**
  12210. * Parse given hashbang URL into properties
  12211. * @param {string} url Hashbang URL
  12212. * @private
  12213. */
  12214. this.$$parse = function(url) {
  12215. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  12216. var withoutHashUrl;
  12217. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  12218. // The rest of the URL starts with a hash so we have
  12219. // got either a hashbang path or a plain hash fragment
  12220. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  12221. if (isUndefined(withoutHashUrl)) {
  12222. // There was no hashbang prefix so we just have a hash fragment
  12223. withoutHashUrl = withoutBaseUrl;
  12224. }
  12225. } else {
  12226. // There was no hashbang path nor hash fragment:
  12227. // If we are in HTML5 mode we use what is left as the path;
  12228. // Otherwise we ignore what is left
  12229. if (this.$$html5) {
  12230. withoutHashUrl = withoutBaseUrl;
  12231. } else {
  12232. withoutHashUrl = '';
  12233. if (isUndefined(withoutBaseUrl)) {
  12234. appBase = url;
  12235. /** @type {?} */ (this).replace();
  12236. }
  12237. }
  12238. }
  12239. parseAppUrl(withoutHashUrl, this);
  12240. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  12241. this.$$compose();
  12242. /*
  12243. * In Windows, on an anchor node on documents loaded from
  12244. * the filesystem, the browser will return a pathname
  12245. * prefixed with the drive name ('/C:/path') when a
  12246. * pathname without a drive is set:
  12247. * * a.setAttribute('href', '/foo')
  12248. * * a.pathname === '/C:/foo' //true
  12249. *
  12250. * Inside of Angular, we're always using pathnames that
  12251. * do not include drive names for routing.
  12252. */
  12253. function removeWindowsDriveName(path, url, base) {
  12254. /*
  12255. Matches paths for file protocol on windows,
  12256. such as /C:/foo/bar, and captures only /foo/bar.
  12257. */
  12258. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  12259. var firstPathSegmentMatch;
  12260. //Get the relative path from the input URL.
  12261. if (startsWith(url, base)) {
  12262. url = url.replace(base, '');
  12263. }
  12264. // The input URL intentionally contains a first path segment that ends with a colon.
  12265. if (windowsFilePathExp.exec(url)) {
  12266. return path;
  12267. }
  12268. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  12269. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  12270. }
  12271. };
  12272. /**
  12273. * Compose hashbang URL and update `absUrl` property
  12274. * @private
  12275. */
  12276. this.$$compose = function() {
  12277. var search = toKeyValue(this.$$search),
  12278. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12279. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12280. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  12281. this.$$urlUpdatedByLocation = true;
  12282. };
  12283. this.$$parseLinkUrl = function(url, relHref) {
  12284. if (stripHash(appBase) === stripHash(url)) {
  12285. this.$$parse(url);
  12286. return true;
  12287. }
  12288. return false;
  12289. };
  12290. }
  12291. /**
  12292. * LocationHashbangUrl represents URL
  12293. * This object is exposed as $location service when html5 history api is enabled but the browser
  12294. * does not support it.
  12295. *
  12296. * @constructor
  12297. * @param {string} appBase application base URL
  12298. * @param {string} appBaseNoFile application base URL stripped of any filename
  12299. * @param {string} hashPrefix hashbang prefix
  12300. */
  12301. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  12302. this.$$html5 = true;
  12303. LocationHashbangUrl.apply(this, arguments);
  12304. this.$$parseLinkUrl = function(url, relHref) {
  12305. if (relHref && relHref[0] === '#') {
  12306. // special case for links to hash fragments:
  12307. // keep the old url and only replace the hash fragment
  12308. this.hash(relHref.slice(1));
  12309. return true;
  12310. }
  12311. var rewrittenUrl;
  12312. var appUrl;
  12313. if (appBase === stripHash(url)) {
  12314. rewrittenUrl = url;
  12315. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12316. rewrittenUrl = appBase + hashPrefix + appUrl;
  12317. } else if (appBaseNoFile === url + '/') {
  12318. rewrittenUrl = appBaseNoFile;
  12319. }
  12320. if (rewrittenUrl) {
  12321. this.$$parse(rewrittenUrl);
  12322. }
  12323. return !!rewrittenUrl;
  12324. };
  12325. this.$$compose = function() {
  12326. var search = toKeyValue(this.$$search),
  12327. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12328. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12329. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  12330. this.$$absUrl = appBase + hashPrefix + this.$$url;
  12331. this.$$urlUpdatedByLocation = true;
  12332. };
  12333. }
  12334. var locationPrototype = {
  12335. /**
  12336. * Ensure absolute URL is initialized.
  12337. * @private
  12338. */
  12339. $$absUrl:'',
  12340. /**
  12341. * Are we in html5 mode?
  12342. * @private
  12343. */
  12344. $$html5: false,
  12345. /**
  12346. * Has any change been replacing?
  12347. * @private
  12348. */
  12349. $$replace: false,
  12350. /**
  12351. * @ngdoc method
  12352. * @name $location#absUrl
  12353. *
  12354. * @description
  12355. * This method is getter only.
  12356. *
  12357. * Return full URL representation with all segments encoded according to rules specified in
  12358. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  12359. *
  12360. *
  12361. * ```js
  12362. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12363. * var absUrl = $location.absUrl();
  12364. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  12365. * ```
  12366. *
  12367. * @return {string} full URL
  12368. */
  12369. absUrl: locationGetter('$$absUrl'),
  12370. /**
  12371. * @ngdoc method
  12372. * @name $location#url
  12373. *
  12374. * @description
  12375. * This method is getter / setter.
  12376. *
  12377. * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
  12378. *
  12379. * Change path, search and hash, when called with parameter and return `$location`.
  12380. *
  12381. *
  12382. * ```js
  12383. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12384. * var url = $location.url();
  12385. * // => "/some/path?foo=bar&baz=xoxo"
  12386. * ```
  12387. *
  12388. * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
  12389. * @return {string} url
  12390. */
  12391. url: function(url) {
  12392. if (isUndefined(url)) {
  12393. return this.$$url;
  12394. }
  12395. var match = PATH_MATCH.exec(url);
  12396. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  12397. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  12398. this.hash(match[5] || '');
  12399. return this;
  12400. },
  12401. /**
  12402. * @ngdoc method
  12403. * @name $location#protocol
  12404. *
  12405. * @description
  12406. * This method is getter only.
  12407. *
  12408. * Return protocol of current URL.
  12409. *
  12410. *
  12411. * ```js
  12412. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12413. * var protocol = $location.protocol();
  12414. * // => "http"
  12415. * ```
  12416. *
  12417. * @return {string} protocol of current URL
  12418. */
  12419. protocol: locationGetter('$$protocol'),
  12420. /**
  12421. * @ngdoc method
  12422. * @name $location#host
  12423. *
  12424. * @description
  12425. * This method is getter only.
  12426. *
  12427. * Return host of current URL.
  12428. *
  12429. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  12430. *
  12431. *
  12432. * ```js
  12433. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12434. * var host = $location.host();
  12435. * // => "example.com"
  12436. *
  12437. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  12438. * host = $location.host();
  12439. * // => "example.com"
  12440. * host = location.host;
  12441. * // => "example.com:8080"
  12442. * ```
  12443. *
  12444. * @return {string} host of current URL.
  12445. */
  12446. host: locationGetter('$$host'),
  12447. /**
  12448. * @ngdoc method
  12449. * @name $location#port
  12450. *
  12451. * @description
  12452. * This method is getter only.
  12453. *
  12454. * Return port of current URL.
  12455. *
  12456. *
  12457. * ```js
  12458. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12459. * var port = $location.port();
  12460. * // => 80
  12461. * ```
  12462. *
  12463. * @return {Number} port
  12464. */
  12465. port: locationGetter('$$port'),
  12466. /**
  12467. * @ngdoc method
  12468. * @name $location#path
  12469. *
  12470. * @description
  12471. * This method is getter / setter.
  12472. *
  12473. * Return path of current URL when called without any parameter.
  12474. *
  12475. * Change path when called with parameter and return `$location`.
  12476. *
  12477. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  12478. * if it is missing.
  12479. *
  12480. *
  12481. * ```js
  12482. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12483. * var path = $location.path();
  12484. * // => "/some/path"
  12485. * ```
  12486. *
  12487. * @param {(string|number)=} path New path
  12488. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  12489. */
  12490. path: locationGetterSetter('$$path', function(path) {
  12491. path = path !== null ? path.toString() : '';
  12492. return path.charAt(0) === '/' ? path : '/' + path;
  12493. }),
  12494. /**
  12495. * @ngdoc method
  12496. * @name $location#search
  12497. *
  12498. * @description
  12499. * This method is getter / setter.
  12500. *
  12501. * Return search part (as object) of current URL when called without any parameter.
  12502. *
  12503. * Change search part when called with parameter and return `$location`.
  12504. *
  12505. *
  12506. * ```js
  12507. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12508. * var searchObject = $location.search();
  12509. * // => {foo: 'bar', baz: 'xoxo'}
  12510. *
  12511. * // set foo to 'yipee'
  12512. * $location.search('foo', 'yipee');
  12513. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  12514. * ```
  12515. *
  12516. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  12517. * hash object.
  12518. *
  12519. * When called with a single argument the method acts as a setter, setting the `search` component
  12520. * of `$location` to the specified value.
  12521. *
  12522. * If the argument is a hash object containing an array of values, these values will be encoded
  12523. * as duplicate search parameters in the URL.
  12524. *
  12525. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  12526. * will override only a single search property.
  12527. *
  12528. * If `paramValue` is an array, it will override the property of the `search` component of
  12529. * `$location` specified via the first argument.
  12530. *
  12531. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  12532. *
  12533. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  12534. * value nor trailing equal sign.
  12535. *
  12536. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  12537. * one or more arguments returns `$location` object itself.
  12538. */
  12539. search: function(search, paramValue) {
  12540. switch (arguments.length) {
  12541. case 0:
  12542. return this.$$search;
  12543. case 1:
  12544. if (isString(search) || isNumber(search)) {
  12545. search = search.toString();
  12546. this.$$search = parseKeyValue(search);
  12547. } else if (isObject(search)) {
  12548. search = copy(search, {});
  12549. // remove object undefined or null properties
  12550. forEach(search, function(value, key) {
  12551. if (value == null) delete search[key];
  12552. });
  12553. this.$$search = search;
  12554. } else {
  12555. throw $locationMinErr('isrcharg',
  12556. 'The first argument of the `$location#search()` call must be a string or an object.');
  12557. }
  12558. break;
  12559. default:
  12560. if (isUndefined(paramValue) || paramValue === null) {
  12561. delete this.$$search[search];
  12562. } else {
  12563. this.$$search[search] = paramValue;
  12564. }
  12565. }
  12566. this.$$compose();
  12567. return this;
  12568. },
  12569. /**
  12570. * @ngdoc method
  12571. * @name $location#hash
  12572. *
  12573. * @description
  12574. * This method is getter / setter.
  12575. *
  12576. * Returns the hash fragment when called without any parameters.
  12577. *
  12578. * Changes the hash fragment when called with a parameter and returns `$location`.
  12579. *
  12580. *
  12581. * ```js
  12582. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  12583. * var hash = $location.hash();
  12584. * // => "hashValue"
  12585. * ```
  12586. *
  12587. * @param {(string|number)=} hash New hash fragment
  12588. * @return {string} hash
  12589. */
  12590. hash: locationGetterSetter('$$hash', function(hash) {
  12591. return hash !== null ? hash.toString() : '';
  12592. }),
  12593. /**
  12594. * @ngdoc method
  12595. * @name $location#replace
  12596. *
  12597. * @description
  12598. * If called, all changes to $location during the current `$digest` will replace the current history
  12599. * record, instead of adding a new one.
  12600. */
  12601. replace: function() {
  12602. this.$$replace = true;
  12603. return this;
  12604. }
  12605. };
  12606. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  12607. Location.prototype = Object.create(locationPrototype);
  12608. /**
  12609. * @ngdoc method
  12610. * @name $location#state
  12611. *
  12612. * @description
  12613. * This method is getter / setter.
  12614. *
  12615. * Return the history state object when called without any parameter.
  12616. *
  12617. * Change the history state object when called with one parameter and return `$location`.
  12618. * The state object is later passed to `pushState` or `replaceState`.
  12619. *
  12620. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  12621. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  12622. * older browsers (like IE9 or Android < 4.0), don't use this method.
  12623. *
  12624. * @param {object=} state State object for pushState or replaceState
  12625. * @return {object} state
  12626. */
  12627. Location.prototype.state = function(state) {
  12628. if (!arguments.length) {
  12629. return this.$$state;
  12630. }
  12631. if (Location !== LocationHtml5Url || !this.$$html5) {
  12632. throw $locationMinErr('nostate', 'History API state support is available only ' +
  12633. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  12634. }
  12635. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  12636. // but we're changing the $$state reference to $browser.state() during the $digest
  12637. // so the modification window is narrow.
  12638. this.$$state = isUndefined(state) ? null : state;
  12639. this.$$urlUpdatedByLocation = true;
  12640. return this;
  12641. };
  12642. });
  12643. function locationGetter(property) {
  12644. return /** @this */ function() {
  12645. return this[property];
  12646. };
  12647. }
  12648. function locationGetterSetter(property, preprocess) {
  12649. return /** @this */ function(value) {
  12650. if (isUndefined(value)) {
  12651. return this[property];
  12652. }
  12653. this[property] = preprocess(value);
  12654. this.$$compose();
  12655. return this;
  12656. };
  12657. }
  12658. /**
  12659. * @ngdoc service
  12660. * @name $location
  12661. *
  12662. * @requires $rootElement
  12663. *
  12664. * @description
  12665. * The $location service parses the URL in the browser address bar (based on the
  12666. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  12667. * available to your application. Changes to the URL in the address bar are reflected into
  12668. * $location service and changes to $location are reflected into the browser address bar.
  12669. *
  12670. * **The $location service:**
  12671. *
  12672. * - Exposes the current URL in the browser address bar, so you can
  12673. * - Watch and observe the URL.
  12674. * - Change the URL.
  12675. * - Synchronizes the URL with the browser when the user
  12676. * - Changes the address bar.
  12677. * - Clicks the back or forward button (or clicks a History link).
  12678. * - Clicks on a link.
  12679. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  12680. *
  12681. * For more information see {@link guide/$location Developer Guide: Using $location}
  12682. */
  12683. /**
  12684. * @ngdoc provider
  12685. * @name $locationProvider
  12686. * @this
  12687. *
  12688. * @description
  12689. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  12690. */
  12691. function $LocationProvider() {
  12692. var hashPrefix = '!',
  12693. html5Mode = {
  12694. enabled: false,
  12695. requireBase: true,
  12696. rewriteLinks: true
  12697. };
  12698. /**
  12699. * @ngdoc method
  12700. * @name $locationProvider#hashPrefix
  12701. * @description
  12702. * The default value for the prefix is `'!'`.
  12703. * @param {string=} prefix Prefix for hash part (containing path and search)
  12704. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12705. */
  12706. this.hashPrefix = function(prefix) {
  12707. if (isDefined(prefix)) {
  12708. hashPrefix = prefix;
  12709. return this;
  12710. } else {
  12711. return hashPrefix;
  12712. }
  12713. };
  12714. /**
  12715. * @ngdoc method
  12716. * @name $locationProvider#html5Mode
  12717. * @description
  12718. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  12719. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  12720. * properties:
  12721. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  12722. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  12723. * support `pushState`.
  12724. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  12725. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  12726. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  12727. * See the {@link guide/$location $location guide for more information}
  12728. * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
  12729. * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
  12730. * only happen on links with an attribute that matches the given string. For example, if set
  12731. * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
  12732. * Note that [attribute name normalization](guide/directive#normalization) does not apply
  12733. * here, so `'internalLink'` will **not** match `'internal-link'`.
  12734. *
  12735. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  12736. */
  12737. this.html5Mode = function(mode) {
  12738. if (isBoolean(mode)) {
  12739. html5Mode.enabled = mode;
  12740. return this;
  12741. } else if (isObject(mode)) {
  12742. if (isBoolean(mode.enabled)) {
  12743. html5Mode.enabled = mode.enabled;
  12744. }
  12745. if (isBoolean(mode.requireBase)) {
  12746. html5Mode.requireBase = mode.requireBase;
  12747. }
  12748. if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
  12749. html5Mode.rewriteLinks = mode.rewriteLinks;
  12750. }
  12751. return this;
  12752. } else {
  12753. return html5Mode;
  12754. }
  12755. };
  12756. /**
  12757. * @ngdoc event
  12758. * @name $location#$locationChangeStart
  12759. * @eventType broadcast on root scope
  12760. * @description
  12761. * Broadcasted before a URL will change.
  12762. *
  12763. * This change can be prevented by calling
  12764. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  12765. * details about event object. Upon successful change
  12766. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  12767. *
  12768. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12769. * the browser supports the HTML5 History API.
  12770. *
  12771. * @param {Object} angularEvent Synthetic event object.
  12772. * @param {string} newUrl New URL
  12773. * @param {string=} oldUrl URL that was before it was changed.
  12774. * @param {string=} newState New history state object
  12775. * @param {string=} oldState History state object that was before it was changed.
  12776. */
  12777. /**
  12778. * @ngdoc event
  12779. * @name $location#$locationChangeSuccess
  12780. * @eventType broadcast on root scope
  12781. * @description
  12782. * Broadcasted after a URL was changed.
  12783. *
  12784. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12785. * the browser supports the HTML5 History API.
  12786. *
  12787. * @param {Object} angularEvent Synthetic event object.
  12788. * @param {string} newUrl New URL
  12789. * @param {string=} oldUrl URL that was before it was changed.
  12790. * @param {string=} newState New history state object
  12791. * @param {string=} oldState History state object that was before it was changed.
  12792. */
  12793. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  12794. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  12795. var $location,
  12796. LocationMode,
  12797. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  12798. initialUrl = $browser.url(),
  12799. appBase;
  12800. if (html5Mode.enabled) {
  12801. if (!baseHref && html5Mode.requireBase) {
  12802. throw $locationMinErr('nobase',
  12803. '$location in HTML5 mode requires a <base> tag to be present!');
  12804. }
  12805. appBase = serverBase(initialUrl) + (baseHref || '/');
  12806. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  12807. } else {
  12808. appBase = stripHash(initialUrl);
  12809. LocationMode = LocationHashbangUrl;
  12810. }
  12811. var appBaseNoFile = stripFile(appBase);
  12812. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  12813. $location.$$parseLinkUrl(initialUrl, initialUrl);
  12814. $location.$$state = $browser.state();
  12815. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  12816. function setBrowserUrlWithFallback(url, replace, state) {
  12817. var oldUrl = $location.url();
  12818. var oldState = $location.$$state;
  12819. try {
  12820. $browser.url(url, replace, state);
  12821. // Make sure $location.state() returns referentially identical (not just deeply equal)
  12822. // state object; this makes possible quick checking if the state changed in the digest
  12823. // loop. Checking deep equality would be too expensive.
  12824. $location.$$state = $browser.state();
  12825. } catch (e) {
  12826. // Restore old values if pushState fails
  12827. $location.url(oldUrl);
  12828. $location.$$state = oldState;
  12829. throw e;
  12830. }
  12831. }
  12832. $rootElement.on('click', function(event) {
  12833. var rewriteLinks = html5Mode.rewriteLinks;
  12834. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  12835. // currently we open nice url link and redirect then
  12836. if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
  12837. var elm = jqLite(event.target);
  12838. // traverse the DOM up to find first A tag
  12839. while (nodeName_(elm[0]) !== 'a') {
  12840. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  12841. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  12842. }
  12843. if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
  12844. var absHref = elm.prop('href');
  12845. // get the actual href attribute - see
  12846. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  12847. var relHref = elm.attr('href') || elm.attr('xlink:href');
  12848. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  12849. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  12850. // an animation.
  12851. absHref = urlResolve(absHref.animVal).href;
  12852. }
  12853. // Ignore when url is started with javascript: or mailto:
  12854. if (IGNORE_URI_REGEXP.test(absHref)) return;
  12855. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  12856. if ($location.$$parseLinkUrl(absHref, relHref)) {
  12857. // We do a preventDefault for all urls that are part of the angular application,
  12858. // in html5mode and also without, so that we are able to abort navigation without
  12859. // getting double entries in the location history.
  12860. event.preventDefault();
  12861. // update location manually
  12862. if ($location.absUrl() !== $browser.url()) {
  12863. $rootScope.$apply();
  12864. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  12865. $window.angular['ff-684208-preventDefault'] = true;
  12866. }
  12867. }
  12868. }
  12869. });
  12870. // rewrite hashbang url <> html5 url
  12871. if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
  12872. $browser.url($location.absUrl(), true);
  12873. }
  12874. var initializing = true;
  12875. // update $location when $browser url changes
  12876. $browser.onUrlChange(function(newUrl, newState) {
  12877. if (!startsWith(newUrl, appBaseNoFile)) {
  12878. // If we are navigating outside of the app then force a reload
  12879. $window.location.href = newUrl;
  12880. return;
  12881. }
  12882. $rootScope.$evalAsync(function() {
  12883. var oldUrl = $location.absUrl();
  12884. var oldState = $location.$$state;
  12885. var defaultPrevented;
  12886. newUrl = trimEmptyHash(newUrl);
  12887. $location.$$parse(newUrl);
  12888. $location.$$state = newState;
  12889. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12890. newState, oldState).defaultPrevented;
  12891. // if the location was changed by a `$locationChangeStart` handler then stop
  12892. // processing this location change
  12893. if ($location.absUrl() !== newUrl) return;
  12894. if (defaultPrevented) {
  12895. $location.$$parse(oldUrl);
  12896. $location.$$state = oldState;
  12897. setBrowserUrlWithFallback(oldUrl, false, oldState);
  12898. } else {
  12899. initializing = false;
  12900. afterLocationChange(oldUrl, oldState);
  12901. }
  12902. });
  12903. if (!$rootScope.$$phase) $rootScope.$digest();
  12904. });
  12905. // update browser
  12906. $rootScope.$watch(function $locationWatch() {
  12907. if (initializing || $location.$$urlUpdatedByLocation) {
  12908. $location.$$urlUpdatedByLocation = false;
  12909. var oldUrl = trimEmptyHash($browser.url());
  12910. var newUrl = trimEmptyHash($location.absUrl());
  12911. var oldState = $browser.state();
  12912. var currentReplace = $location.$$replace;
  12913. var urlOrStateChanged = oldUrl !== newUrl ||
  12914. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  12915. if (initializing || urlOrStateChanged) {
  12916. initializing = false;
  12917. $rootScope.$evalAsync(function() {
  12918. var newUrl = $location.absUrl();
  12919. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12920. $location.$$state, oldState).defaultPrevented;
  12921. // if the location was changed by a `$locationChangeStart` handler then stop
  12922. // processing this location change
  12923. if ($location.absUrl() !== newUrl) return;
  12924. if (defaultPrevented) {
  12925. $location.$$parse(oldUrl);
  12926. $location.$$state = oldState;
  12927. } else {
  12928. if (urlOrStateChanged) {
  12929. setBrowserUrlWithFallback(newUrl, currentReplace,
  12930. oldState === $location.$$state ? null : $location.$$state);
  12931. }
  12932. afterLocationChange(oldUrl, oldState);
  12933. }
  12934. });
  12935. }
  12936. }
  12937. $location.$$replace = false;
  12938. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  12939. // there is a change
  12940. });
  12941. return $location;
  12942. function afterLocationChange(oldUrl, oldState) {
  12943. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  12944. $location.$$state, oldState);
  12945. }
  12946. }];
  12947. }
  12948. /**
  12949. * @ngdoc service
  12950. * @name $log
  12951. * @requires $window
  12952. *
  12953. * @description
  12954. * Simple service for logging. Default implementation safely writes the message
  12955. * into the browser's console (if present).
  12956. *
  12957. * The main purpose of this service is to simplify debugging and troubleshooting.
  12958. *
  12959. * The default is to log `debug` messages. You can use
  12960. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  12961. *
  12962. * @example
  12963. <example module="logExample" name="log-service">
  12964. <file name="script.js">
  12965. angular.module('logExample', [])
  12966. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  12967. $scope.$log = $log;
  12968. $scope.message = 'Hello World!';
  12969. }]);
  12970. </file>
  12971. <file name="index.html">
  12972. <div ng-controller="LogController">
  12973. <p>Reload this page with open console, enter text and hit the log button...</p>
  12974. <label>Message:
  12975. <input type="text" ng-model="message" /></label>
  12976. <button ng-click="$log.log(message)">log</button>
  12977. <button ng-click="$log.warn(message)">warn</button>
  12978. <button ng-click="$log.info(message)">info</button>
  12979. <button ng-click="$log.error(message)">error</button>
  12980. <button ng-click="$log.debug(message)">debug</button>
  12981. </div>
  12982. </file>
  12983. </example>
  12984. */
  12985. /**
  12986. * @ngdoc provider
  12987. * @name $logProvider
  12988. * @this
  12989. *
  12990. * @description
  12991. * Use the `$logProvider` to configure how the application logs messages
  12992. */
  12993. function $LogProvider() {
  12994. var debug = true,
  12995. self = this;
  12996. /**
  12997. * @ngdoc method
  12998. * @name $logProvider#debugEnabled
  12999. * @description
  13000. * @param {boolean=} flag enable or disable debug level messages
  13001. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  13002. */
  13003. this.debugEnabled = function(flag) {
  13004. if (isDefined(flag)) {
  13005. debug = flag;
  13006. return this;
  13007. } else {
  13008. return debug;
  13009. }
  13010. };
  13011. this.$get = ['$window', function($window) {
  13012. // Support: IE 9-11, Edge 12-14+
  13013. // IE/Edge display errors in such a way that it requires the user to click in 4 places
  13014. // to see the stack trace. There is no way to feature-detect it so there's a chance
  13015. // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't
  13016. // break apps. Other browsers display errors in a sensible way and some of them map stack
  13017. // traces along source maps if available so it makes sense to let browsers display it
  13018. // as they want.
  13019. var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent);
  13020. return {
  13021. /**
  13022. * @ngdoc method
  13023. * @name $log#log
  13024. *
  13025. * @description
  13026. * Write a log message
  13027. */
  13028. log: consoleLog('log'),
  13029. /**
  13030. * @ngdoc method
  13031. * @name $log#info
  13032. *
  13033. * @description
  13034. * Write an information message
  13035. */
  13036. info: consoleLog('info'),
  13037. /**
  13038. * @ngdoc method
  13039. * @name $log#warn
  13040. *
  13041. * @description
  13042. * Write a warning message
  13043. */
  13044. warn: consoleLog('warn'),
  13045. /**
  13046. * @ngdoc method
  13047. * @name $log#error
  13048. *
  13049. * @description
  13050. * Write an error message
  13051. */
  13052. error: consoleLog('error'),
  13053. /**
  13054. * @ngdoc method
  13055. * @name $log#debug
  13056. *
  13057. * @description
  13058. * Write a debug message
  13059. */
  13060. debug: (function() {
  13061. var fn = consoleLog('debug');
  13062. return function() {
  13063. if (debug) {
  13064. fn.apply(self, arguments);
  13065. }
  13066. };
  13067. })()
  13068. };
  13069. function formatError(arg) {
  13070. if (arg instanceof Error) {
  13071. if (arg.stack && formatStackTrace) {
  13072. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  13073. ? 'Error: ' + arg.message + '\n' + arg.stack
  13074. : arg.stack;
  13075. } else if (arg.sourceURL) {
  13076. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  13077. }
  13078. }
  13079. return arg;
  13080. }
  13081. function consoleLog(type) {
  13082. var console = $window.console || {},
  13083. logFn = console[type] || console.log || noop,
  13084. hasApply = false;
  13085. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  13086. // The reason behind this is that console.log has type "object" in IE8...
  13087. try {
  13088. hasApply = !!logFn.apply;
  13089. } catch (e) { /* empty */ }
  13090. if (hasApply) {
  13091. return function() {
  13092. var args = [];
  13093. forEach(arguments, function(arg) {
  13094. args.push(formatError(arg));
  13095. });
  13096. return logFn.apply(console, args);
  13097. };
  13098. }
  13099. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  13100. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  13101. return function(arg1, arg2) {
  13102. logFn(arg1, arg2 == null ? '' : arg2);
  13103. };
  13104. }
  13105. }];
  13106. }
  13107. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  13108. * Any commits to this file should be reviewed with security in mind. *
  13109. * Changes to this file can potentially create security vulnerabilities. *
  13110. * An approval from 2 Core members with history of modifying *
  13111. * this file is required. *
  13112. * *
  13113. * Does the change somehow allow for arbitrary javascript to be executed? *
  13114. * Or allows for someone to change the prototype of built-in objects? *
  13115. * Or gives undesired access to variables likes document or window? *
  13116. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  13117. var $parseMinErr = minErr('$parse');
  13118. var objectValueOf = {}.constructor.prototype.valueOf;
  13119. // Sandboxing Angular Expressions
  13120. // ------------------------------
  13121. // Angular expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by
  13122. // various means such as obtaining a reference to native JS functions like the Function constructor.
  13123. //
  13124. // As an example, consider the following Angular expression:
  13125. //
  13126. // {}.toString.constructor('alert("evil JS code")')
  13127. //
  13128. // It is important to realize that if you create an expression from a string that contains user provided
  13129. // content then it is possible that your application contains a security vulnerability to an XSS style attack.
  13130. //
  13131. // See https://docs.angularjs.org/guide/security
  13132. function getStringValue(name) {
  13133. // Property names must be strings. This means that non-string objects cannot be used
  13134. // as keys in an object. Any non-string object, including a number, is typecasted
  13135. // into a string via the toString method.
  13136. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  13137. //
  13138. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  13139. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  13140. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  13141. //
  13142. // TypeError: Cannot convert object to primitive value
  13143. //
  13144. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  13145. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  13146. // such a 'broken' object as a key.
  13147. return name + '';
  13148. }
  13149. var OPERATORS = createMap();
  13150. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  13151. var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
  13152. /////////////////////////////////////////
  13153. /**
  13154. * @constructor
  13155. */
  13156. var Lexer = function Lexer(options) {
  13157. this.options = options;
  13158. };
  13159. Lexer.prototype = {
  13160. constructor: Lexer,
  13161. lex: function(text) {
  13162. this.text = text;
  13163. this.index = 0;
  13164. this.tokens = [];
  13165. while (this.index < this.text.length) {
  13166. var ch = this.text.charAt(this.index);
  13167. if (ch === '"' || ch === '\'') {
  13168. this.readString(ch);
  13169. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  13170. this.readNumber();
  13171. } else if (this.isIdentifierStart(this.peekMultichar())) {
  13172. this.readIdent();
  13173. } else if (this.is(ch, '(){}[].,;:?')) {
  13174. this.tokens.push({index: this.index, text: ch});
  13175. this.index++;
  13176. } else if (this.isWhitespace(ch)) {
  13177. this.index++;
  13178. } else {
  13179. var ch2 = ch + this.peek();
  13180. var ch3 = ch2 + this.peek(2);
  13181. var op1 = OPERATORS[ch];
  13182. var op2 = OPERATORS[ch2];
  13183. var op3 = OPERATORS[ch3];
  13184. if (op1 || op2 || op3) {
  13185. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  13186. this.tokens.push({index: this.index, text: token, operator: true});
  13187. this.index += token.length;
  13188. } else {
  13189. this.throwError('Unexpected next character ', this.index, this.index + 1);
  13190. }
  13191. }
  13192. }
  13193. return this.tokens;
  13194. },
  13195. is: function(ch, chars) {
  13196. return chars.indexOf(ch) !== -1;
  13197. },
  13198. peek: function(i) {
  13199. var num = i || 1;
  13200. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  13201. },
  13202. isNumber: function(ch) {
  13203. return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  13204. },
  13205. isWhitespace: function(ch) {
  13206. // IE treats non-breaking space as \u00A0
  13207. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  13208. ch === '\n' || ch === '\v' || ch === '\u00A0');
  13209. },
  13210. isIdentifierStart: function(ch) {
  13211. return this.options.isIdentifierStart ?
  13212. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  13213. this.isValidIdentifierStart(ch);
  13214. },
  13215. isValidIdentifierStart: function(ch) {
  13216. return ('a' <= ch && ch <= 'z' ||
  13217. 'A' <= ch && ch <= 'Z' ||
  13218. '_' === ch || ch === '$');
  13219. },
  13220. isIdentifierContinue: function(ch) {
  13221. return this.options.isIdentifierContinue ?
  13222. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  13223. this.isValidIdentifierContinue(ch);
  13224. },
  13225. isValidIdentifierContinue: function(ch, cp) {
  13226. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  13227. },
  13228. codePointAt: function(ch) {
  13229. if (ch.length === 1) return ch.charCodeAt(0);
  13230. // eslint-disable-next-line no-bitwise
  13231. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  13232. },
  13233. peekMultichar: function() {
  13234. var ch = this.text.charAt(this.index);
  13235. var peek = this.peek();
  13236. if (!peek) {
  13237. return ch;
  13238. }
  13239. var cp1 = ch.charCodeAt(0);
  13240. var cp2 = peek.charCodeAt(0);
  13241. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  13242. return ch + peek;
  13243. }
  13244. return ch;
  13245. },
  13246. isExpOperator: function(ch) {
  13247. return (ch === '-' || ch === '+' || this.isNumber(ch));
  13248. },
  13249. throwError: function(error, start, end) {
  13250. end = end || this.index;
  13251. var colStr = (isDefined(start)
  13252. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  13253. : ' ' + end);
  13254. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  13255. error, colStr, this.text);
  13256. },
  13257. readNumber: function() {
  13258. var number = '';
  13259. var start = this.index;
  13260. while (this.index < this.text.length) {
  13261. var ch = lowercase(this.text.charAt(this.index));
  13262. if (ch === '.' || this.isNumber(ch)) {
  13263. number += ch;
  13264. } else {
  13265. var peekCh = this.peek();
  13266. if (ch === 'e' && this.isExpOperator(peekCh)) {
  13267. number += ch;
  13268. } else if (this.isExpOperator(ch) &&
  13269. peekCh && this.isNumber(peekCh) &&
  13270. number.charAt(number.length - 1) === 'e') {
  13271. number += ch;
  13272. } else if (this.isExpOperator(ch) &&
  13273. (!peekCh || !this.isNumber(peekCh)) &&
  13274. number.charAt(number.length - 1) === 'e') {
  13275. this.throwError('Invalid exponent');
  13276. } else {
  13277. break;
  13278. }
  13279. }
  13280. this.index++;
  13281. }
  13282. this.tokens.push({
  13283. index: start,
  13284. text: number,
  13285. constant: true,
  13286. value: Number(number)
  13287. });
  13288. },
  13289. readIdent: function() {
  13290. var start = this.index;
  13291. this.index += this.peekMultichar().length;
  13292. while (this.index < this.text.length) {
  13293. var ch = this.peekMultichar();
  13294. if (!this.isIdentifierContinue(ch)) {
  13295. break;
  13296. }
  13297. this.index += ch.length;
  13298. }
  13299. this.tokens.push({
  13300. index: start,
  13301. text: this.text.slice(start, this.index),
  13302. identifier: true
  13303. });
  13304. },
  13305. readString: function(quote) {
  13306. var start = this.index;
  13307. this.index++;
  13308. var string = '';
  13309. var rawString = quote;
  13310. var escape = false;
  13311. while (this.index < this.text.length) {
  13312. var ch = this.text.charAt(this.index);
  13313. rawString += ch;
  13314. if (escape) {
  13315. if (ch === 'u') {
  13316. var hex = this.text.substring(this.index + 1, this.index + 5);
  13317. if (!hex.match(/[\da-f]{4}/i)) {
  13318. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  13319. }
  13320. this.index += 4;
  13321. string += String.fromCharCode(parseInt(hex, 16));
  13322. } else {
  13323. var rep = ESCAPE[ch];
  13324. string = string + (rep || ch);
  13325. }
  13326. escape = false;
  13327. } else if (ch === '\\') {
  13328. escape = true;
  13329. } else if (ch === quote) {
  13330. this.index++;
  13331. this.tokens.push({
  13332. index: start,
  13333. text: rawString,
  13334. constant: true,
  13335. value: string
  13336. });
  13337. return;
  13338. } else {
  13339. string += ch;
  13340. }
  13341. this.index++;
  13342. }
  13343. this.throwError('Unterminated quote', start);
  13344. }
  13345. };
  13346. var AST = function AST(lexer, options) {
  13347. this.lexer = lexer;
  13348. this.options = options;
  13349. };
  13350. AST.Program = 'Program';
  13351. AST.ExpressionStatement = 'ExpressionStatement';
  13352. AST.AssignmentExpression = 'AssignmentExpression';
  13353. AST.ConditionalExpression = 'ConditionalExpression';
  13354. AST.LogicalExpression = 'LogicalExpression';
  13355. AST.BinaryExpression = 'BinaryExpression';
  13356. AST.UnaryExpression = 'UnaryExpression';
  13357. AST.CallExpression = 'CallExpression';
  13358. AST.MemberExpression = 'MemberExpression';
  13359. AST.Identifier = 'Identifier';
  13360. AST.Literal = 'Literal';
  13361. AST.ArrayExpression = 'ArrayExpression';
  13362. AST.Property = 'Property';
  13363. AST.ObjectExpression = 'ObjectExpression';
  13364. AST.ThisExpression = 'ThisExpression';
  13365. AST.LocalsExpression = 'LocalsExpression';
  13366. // Internal use only
  13367. AST.NGValueParameter = 'NGValueParameter';
  13368. AST.prototype = {
  13369. ast: function(text) {
  13370. this.text = text;
  13371. this.tokens = this.lexer.lex(text);
  13372. var value = this.program();
  13373. if (this.tokens.length !== 0) {
  13374. this.throwError('is an unexpected token', this.tokens[0]);
  13375. }
  13376. return value;
  13377. },
  13378. program: function() {
  13379. var body = [];
  13380. while (true) {
  13381. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  13382. body.push(this.expressionStatement());
  13383. if (!this.expect(';')) {
  13384. return { type: AST.Program, body: body};
  13385. }
  13386. }
  13387. },
  13388. expressionStatement: function() {
  13389. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  13390. },
  13391. filterChain: function() {
  13392. var left = this.expression();
  13393. while (this.expect('|')) {
  13394. left = this.filter(left);
  13395. }
  13396. return left;
  13397. },
  13398. expression: function() {
  13399. return this.assignment();
  13400. },
  13401. assignment: function() {
  13402. var result = this.ternary();
  13403. if (this.expect('=')) {
  13404. if (!isAssignable(result)) {
  13405. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13406. }
  13407. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  13408. }
  13409. return result;
  13410. },
  13411. ternary: function() {
  13412. var test = this.logicalOR();
  13413. var alternate;
  13414. var consequent;
  13415. if (this.expect('?')) {
  13416. alternate = this.expression();
  13417. if (this.consume(':')) {
  13418. consequent = this.expression();
  13419. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  13420. }
  13421. }
  13422. return test;
  13423. },
  13424. logicalOR: function() {
  13425. var left = this.logicalAND();
  13426. while (this.expect('||')) {
  13427. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  13428. }
  13429. return left;
  13430. },
  13431. logicalAND: function() {
  13432. var left = this.equality();
  13433. while (this.expect('&&')) {
  13434. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  13435. }
  13436. return left;
  13437. },
  13438. equality: function() {
  13439. var left = this.relational();
  13440. var token;
  13441. while ((token = this.expect('==','!=','===','!=='))) {
  13442. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  13443. }
  13444. return left;
  13445. },
  13446. relational: function() {
  13447. var left = this.additive();
  13448. var token;
  13449. while ((token = this.expect('<', '>', '<=', '>='))) {
  13450. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  13451. }
  13452. return left;
  13453. },
  13454. additive: function() {
  13455. var left = this.multiplicative();
  13456. var token;
  13457. while ((token = this.expect('+','-'))) {
  13458. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  13459. }
  13460. return left;
  13461. },
  13462. multiplicative: function() {
  13463. var left = this.unary();
  13464. var token;
  13465. while ((token = this.expect('*','/','%'))) {
  13466. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  13467. }
  13468. return left;
  13469. },
  13470. unary: function() {
  13471. var token;
  13472. if ((token = this.expect('+', '-', '!'))) {
  13473. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  13474. } else {
  13475. return this.primary();
  13476. }
  13477. },
  13478. primary: function() {
  13479. var primary;
  13480. if (this.expect('(')) {
  13481. primary = this.filterChain();
  13482. this.consume(')');
  13483. } else if (this.expect('[')) {
  13484. primary = this.arrayDeclaration();
  13485. } else if (this.expect('{')) {
  13486. primary = this.object();
  13487. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  13488. primary = copy(this.selfReferential[this.consume().text]);
  13489. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  13490. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  13491. } else if (this.peek().identifier) {
  13492. primary = this.identifier();
  13493. } else if (this.peek().constant) {
  13494. primary = this.constant();
  13495. } else {
  13496. this.throwError('not a primary expression', this.peek());
  13497. }
  13498. var next;
  13499. while ((next = this.expect('(', '[', '.'))) {
  13500. if (next.text === '(') {
  13501. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  13502. this.consume(')');
  13503. } else if (next.text === '[') {
  13504. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  13505. this.consume(']');
  13506. } else if (next.text === '.') {
  13507. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  13508. } else {
  13509. this.throwError('IMPOSSIBLE');
  13510. }
  13511. }
  13512. return primary;
  13513. },
  13514. filter: function(baseExpression) {
  13515. var args = [baseExpression];
  13516. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  13517. while (this.expect(':')) {
  13518. args.push(this.expression());
  13519. }
  13520. return result;
  13521. },
  13522. parseArguments: function() {
  13523. var args = [];
  13524. if (this.peekToken().text !== ')') {
  13525. do {
  13526. args.push(this.filterChain());
  13527. } while (this.expect(','));
  13528. }
  13529. return args;
  13530. },
  13531. identifier: function() {
  13532. var token = this.consume();
  13533. if (!token.identifier) {
  13534. this.throwError('is not a valid identifier', token);
  13535. }
  13536. return { type: AST.Identifier, name: token.text };
  13537. },
  13538. constant: function() {
  13539. // TODO check that it is a constant
  13540. return { type: AST.Literal, value: this.consume().value };
  13541. },
  13542. arrayDeclaration: function() {
  13543. var elements = [];
  13544. if (this.peekToken().text !== ']') {
  13545. do {
  13546. if (this.peek(']')) {
  13547. // Support trailing commas per ES5.1.
  13548. break;
  13549. }
  13550. elements.push(this.expression());
  13551. } while (this.expect(','));
  13552. }
  13553. this.consume(']');
  13554. return { type: AST.ArrayExpression, elements: elements };
  13555. },
  13556. object: function() {
  13557. var properties = [], property;
  13558. if (this.peekToken().text !== '}') {
  13559. do {
  13560. if (this.peek('}')) {
  13561. // Support trailing commas per ES5.1.
  13562. break;
  13563. }
  13564. property = {type: AST.Property, kind: 'init'};
  13565. if (this.peek().constant) {
  13566. property.key = this.constant();
  13567. property.computed = false;
  13568. this.consume(':');
  13569. property.value = this.expression();
  13570. } else if (this.peek().identifier) {
  13571. property.key = this.identifier();
  13572. property.computed = false;
  13573. if (this.peek(':')) {
  13574. this.consume(':');
  13575. property.value = this.expression();
  13576. } else {
  13577. property.value = property.key;
  13578. }
  13579. } else if (this.peek('[')) {
  13580. this.consume('[');
  13581. property.key = this.expression();
  13582. this.consume(']');
  13583. property.computed = true;
  13584. this.consume(':');
  13585. property.value = this.expression();
  13586. } else {
  13587. this.throwError('invalid key', this.peek());
  13588. }
  13589. properties.push(property);
  13590. } while (this.expect(','));
  13591. }
  13592. this.consume('}');
  13593. return {type: AST.ObjectExpression, properties: properties };
  13594. },
  13595. throwError: function(msg, token) {
  13596. throw $parseMinErr('syntax',
  13597. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  13598. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  13599. },
  13600. consume: function(e1) {
  13601. if (this.tokens.length === 0) {
  13602. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13603. }
  13604. var token = this.expect(e1);
  13605. if (!token) {
  13606. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  13607. }
  13608. return token;
  13609. },
  13610. peekToken: function() {
  13611. if (this.tokens.length === 0) {
  13612. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13613. }
  13614. return this.tokens[0];
  13615. },
  13616. peek: function(e1, e2, e3, e4) {
  13617. return this.peekAhead(0, e1, e2, e3, e4);
  13618. },
  13619. peekAhead: function(i, e1, e2, e3, e4) {
  13620. if (this.tokens.length > i) {
  13621. var token = this.tokens[i];
  13622. var t = token.text;
  13623. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  13624. (!e1 && !e2 && !e3 && !e4)) {
  13625. return token;
  13626. }
  13627. }
  13628. return false;
  13629. },
  13630. expect: function(e1, e2, e3, e4) {
  13631. var token = this.peek(e1, e2, e3, e4);
  13632. if (token) {
  13633. this.tokens.shift();
  13634. return token;
  13635. }
  13636. return false;
  13637. },
  13638. selfReferential: {
  13639. 'this': {type: AST.ThisExpression },
  13640. '$locals': {type: AST.LocalsExpression }
  13641. }
  13642. };
  13643. function ifDefined(v, d) {
  13644. return typeof v !== 'undefined' ? v : d;
  13645. }
  13646. function plusFn(l, r) {
  13647. if (typeof l === 'undefined') return r;
  13648. if (typeof r === 'undefined') return l;
  13649. return l + r;
  13650. }
  13651. function isStateless($filter, filterName) {
  13652. var fn = $filter(filterName);
  13653. return !fn.$stateful;
  13654. }
  13655. function findConstantAndWatchExpressions(ast, $filter) {
  13656. var allConstants;
  13657. var argsToWatch;
  13658. var isStatelessFilter;
  13659. switch (ast.type) {
  13660. case AST.Program:
  13661. allConstants = true;
  13662. forEach(ast.body, function(expr) {
  13663. findConstantAndWatchExpressions(expr.expression, $filter);
  13664. allConstants = allConstants && expr.expression.constant;
  13665. });
  13666. ast.constant = allConstants;
  13667. break;
  13668. case AST.Literal:
  13669. ast.constant = true;
  13670. ast.toWatch = [];
  13671. break;
  13672. case AST.UnaryExpression:
  13673. findConstantAndWatchExpressions(ast.argument, $filter);
  13674. ast.constant = ast.argument.constant;
  13675. ast.toWatch = ast.argument.toWatch;
  13676. break;
  13677. case AST.BinaryExpression:
  13678. findConstantAndWatchExpressions(ast.left, $filter);
  13679. findConstantAndWatchExpressions(ast.right, $filter);
  13680. ast.constant = ast.left.constant && ast.right.constant;
  13681. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  13682. break;
  13683. case AST.LogicalExpression:
  13684. findConstantAndWatchExpressions(ast.left, $filter);
  13685. findConstantAndWatchExpressions(ast.right, $filter);
  13686. ast.constant = ast.left.constant && ast.right.constant;
  13687. ast.toWatch = ast.constant ? [] : [ast];
  13688. break;
  13689. case AST.ConditionalExpression:
  13690. findConstantAndWatchExpressions(ast.test, $filter);
  13691. findConstantAndWatchExpressions(ast.alternate, $filter);
  13692. findConstantAndWatchExpressions(ast.consequent, $filter);
  13693. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  13694. ast.toWatch = ast.constant ? [] : [ast];
  13695. break;
  13696. case AST.Identifier:
  13697. ast.constant = false;
  13698. ast.toWatch = [ast];
  13699. break;
  13700. case AST.MemberExpression:
  13701. findConstantAndWatchExpressions(ast.object, $filter);
  13702. if (ast.computed) {
  13703. findConstantAndWatchExpressions(ast.property, $filter);
  13704. }
  13705. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  13706. ast.toWatch = [ast];
  13707. break;
  13708. case AST.CallExpression:
  13709. isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
  13710. allConstants = isStatelessFilter;
  13711. argsToWatch = [];
  13712. forEach(ast.arguments, function(expr) {
  13713. findConstantAndWatchExpressions(expr, $filter);
  13714. allConstants = allConstants && expr.constant;
  13715. if (!expr.constant) {
  13716. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13717. }
  13718. });
  13719. ast.constant = allConstants;
  13720. ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
  13721. break;
  13722. case AST.AssignmentExpression:
  13723. findConstantAndWatchExpressions(ast.left, $filter);
  13724. findConstantAndWatchExpressions(ast.right, $filter);
  13725. ast.constant = ast.left.constant && ast.right.constant;
  13726. ast.toWatch = [ast];
  13727. break;
  13728. case AST.ArrayExpression:
  13729. allConstants = true;
  13730. argsToWatch = [];
  13731. forEach(ast.elements, function(expr) {
  13732. findConstantAndWatchExpressions(expr, $filter);
  13733. allConstants = allConstants && expr.constant;
  13734. if (!expr.constant) {
  13735. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13736. }
  13737. });
  13738. ast.constant = allConstants;
  13739. ast.toWatch = argsToWatch;
  13740. break;
  13741. case AST.ObjectExpression:
  13742. allConstants = true;
  13743. argsToWatch = [];
  13744. forEach(ast.properties, function(property) {
  13745. findConstantAndWatchExpressions(property.value, $filter);
  13746. allConstants = allConstants && property.value.constant && !property.computed;
  13747. if (!property.value.constant) {
  13748. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  13749. }
  13750. if (property.computed) {
  13751. findConstantAndWatchExpressions(property.key, $filter);
  13752. if (!property.key.constant) {
  13753. argsToWatch.push.apply(argsToWatch, property.key.toWatch);
  13754. }
  13755. }
  13756. });
  13757. ast.constant = allConstants;
  13758. ast.toWatch = argsToWatch;
  13759. break;
  13760. case AST.ThisExpression:
  13761. ast.constant = false;
  13762. ast.toWatch = [];
  13763. break;
  13764. case AST.LocalsExpression:
  13765. ast.constant = false;
  13766. ast.toWatch = [];
  13767. break;
  13768. }
  13769. }
  13770. function getInputs(body) {
  13771. if (body.length !== 1) return;
  13772. var lastExpression = body[0].expression;
  13773. var candidate = lastExpression.toWatch;
  13774. if (candidate.length !== 1) return candidate;
  13775. return candidate[0] !== lastExpression ? candidate : undefined;
  13776. }
  13777. function isAssignable(ast) {
  13778. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  13779. }
  13780. function assignableAST(ast) {
  13781. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  13782. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  13783. }
  13784. }
  13785. function isLiteral(ast) {
  13786. return ast.body.length === 0 ||
  13787. ast.body.length === 1 && (
  13788. ast.body[0].expression.type === AST.Literal ||
  13789. ast.body[0].expression.type === AST.ArrayExpression ||
  13790. ast.body[0].expression.type === AST.ObjectExpression);
  13791. }
  13792. function isConstant(ast) {
  13793. return ast.constant;
  13794. }
  13795. function ASTCompiler($filter) {
  13796. this.$filter = $filter;
  13797. }
  13798. ASTCompiler.prototype = {
  13799. compile: function(ast) {
  13800. var self = this;
  13801. this.state = {
  13802. nextId: 0,
  13803. filters: {},
  13804. fn: {vars: [], body: [], own: {}},
  13805. assign: {vars: [], body: [], own: {}},
  13806. inputs: []
  13807. };
  13808. findConstantAndWatchExpressions(ast, self.$filter);
  13809. var extra = '';
  13810. var assignable;
  13811. this.stage = 'assign';
  13812. if ((assignable = assignableAST(ast))) {
  13813. this.state.computing = 'assign';
  13814. var result = this.nextId();
  13815. this.recurse(assignable, result);
  13816. this.return_(result);
  13817. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  13818. }
  13819. var toWatch = getInputs(ast.body);
  13820. self.stage = 'inputs';
  13821. forEach(toWatch, function(watch, key) {
  13822. var fnKey = 'fn' + key;
  13823. self.state[fnKey] = {vars: [], body: [], own: {}};
  13824. self.state.computing = fnKey;
  13825. var intoId = self.nextId();
  13826. self.recurse(watch, intoId);
  13827. self.return_(intoId);
  13828. self.state.inputs.push(fnKey);
  13829. watch.watchId = key;
  13830. });
  13831. this.state.computing = 'fn';
  13832. this.stage = 'main';
  13833. this.recurse(ast);
  13834. var fnString =
  13835. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  13836. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  13837. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  13838. this.filterPrefix() +
  13839. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  13840. extra +
  13841. this.watchFns() +
  13842. 'return fn;';
  13843. // eslint-disable-next-line no-new-func
  13844. var fn = (new Function('$filter',
  13845. 'getStringValue',
  13846. 'ifDefined',
  13847. 'plus',
  13848. fnString))(
  13849. this.$filter,
  13850. getStringValue,
  13851. ifDefined,
  13852. plusFn);
  13853. this.state = this.stage = undefined;
  13854. return fn;
  13855. },
  13856. USE: 'use',
  13857. STRICT: 'strict',
  13858. watchFns: function() {
  13859. var result = [];
  13860. var fns = this.state.inputs;
  13861. var self = this;
  13862. forEach(fns, function(name) {
  13863. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  13864. });
  13865. if (fns.length) {
  13866. result.push('fn.inputs=[' + fns.join(',') + '];');
  13867. }
  13868. return result.join('');
  13869. },
  13870. generateFunction: function(name, params) {
  13871. return 'function(' + params + '){' +
  13872. this.varsPrefix(name) +
  13873. this.body(name) +
  13874. '};';
  13875. },
  13876. filterPrefix: function() {
  13877. var parts = [];
  13878. var self = this;
  13879. forEach(this.state.filters, function(id, filter) {
  13880. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  13881. });
  13882. if (parts.length) return 'var ' + parts.join(',') + ';';
  13883. return '';
  13884. },
  13885. varsPrefix: function(section) {
  13886. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  13887. },
  13888. body: function(section) {
  13889. return this.state[section].body.join('');
  13890. },
  13891. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13892. var left, right, self = this, args, expression, computed;
  13893. recursionFn = recursionFn || noop;
  13894. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  13895. intoId = intoId || this.nextId();
  13896. this.if_('i',
  13897. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  13898. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  13899. );
  13900. return;
  13901. }
  13902. switch (ast.type) {
  13903. case AST.Program:
  13904. forEach(ast.body, function(expression, pos) {
  13905. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  13906. if (pos !== ast.body.length - 1) {
  13907. self.current().body.push(right, ';');
  13908. } else {
  13909. self.return_(right);
  13910. }
  13911. });
  13912. break;
  13913. case AST.Literal:
  13914. expression = this.escape(ast.value);
  13915. this.assign(intoId, expression);
  13916. recursionFn(intoId || expression);
  13917. break;
  13918. case AST.UnaryExpression:
  13919. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  13920. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  13921. this.assign(intoId, expression);
  13922. recursionFn(expression);
  13923. break;
  13924. case AST.BinaryExpression:
  13925. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  13926. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  13927. if (ast.operator === '+') {
  13928. expression = this.plus(left, right);
  13929. } else if (ast.operator === '-') {
  13930. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  13931. } else {
  13932. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  13933. }
  13934. this.assign(intoId, expression);
  13935. recursionFn(expression);
  13936. break;
  13937. case AST.LogicalExpression:
  13938. intoId = intoId || this.nextId();
  13939. self.recurse(ast.left, intoId);
  13940. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  13941. recursionFn(intoId);
  13942. break;
  13943. case AST.ConditionalExpression:
  13944. intoId = intoId || this.nextId();
  13945. self.recurse(ast.test, intoId);
  13946. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  13947. recursionFn(intoId);
  13948. break;
  13949. case AST.Identifier:
  13950. intoId = intoId || this.nextId();
  13951. if (nameId) {
  13952. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  13953. nameId.computed = false;
  13954. nameId.name = ast.name;
  13955. }
  13956. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  13957. function() {
  13958. self.if_(self.stage === 'inputs' || 's', function() {
  13959. if (create && create !== 1) {
  13960. self.if_(
  13961. self.isNull(self.nonComputedMember('s', ast.name)),
  13962. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  13963. }
  13964. self.assign(intoId, self.nonComputedMember('s', ast.name));
  13965. });
  13966. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  13967. );
  13968. recursionFn(intoId);
  13969. break;
  13970. case AST.MemberExpression:
  13971. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  13972. intoId = intoId || this.nextId();
  13973. self.recurse(ast.object, left, undefined, function() {
  13974. self.if_(self.notNull(left), function() {
  13975. if (ast.computed) {
  13976. right = self.nextId();
  13977. self.recurse(ast.property, right);
  13978. self.getStringValue(right);
  13979. if (create && create !== 1) {
  13980. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  13981. }
  13982. expression = self.computedMember(left, right);
  13983. self.assign(intoId, expression);
  13984. if (nameId) {
  13985. nameId.computed = true;
  13986. nameId.name = right;
  13987. }
  13988. } else {
  13989. if (create && create !== 1) {
  13990. self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  13991. }
  13992. expression = self.nonComputedMember(left, ast.property.name);
  13993. self.assign(intoId, expression);
  13994. if (nameId) {
  13995. nameId.computed = false;
  13996. nameId.name = ast.property.name;
  13997. }
  13998. }
  13999. }, function() {
  14000. self.assign(intoId, 'undefined');
  14001. });
  14002. recursionFn(intoId);
  14003. }, !!create);
  14004. break;
  14005. case AST.CallExpression:
  14006. intoId = intoId || this.nextId();
  14007. if (ast.filter) {
  14008. right = self.filter(ast.callee.name);
  14009. args = [];
  14010. forEach(ast.arguments, function(expr) {
  14011. var argument = self.nextId();
  14012. self.recurse(expr, argument);
  14013. args.push(argument);
  14014. });
  14015. expression = right + '(' + args.join(',') + ')';
  14016. self.assign(intoId, expression);
  14017. recursionFn(intoId);
  14018. } else {
  14019. right = self.nextId();
  14020. left = {};
  14021. args = [];
  14022. self.recurse(ast.callee, right, left, function() {
  14023. self.if_(self.notNull(right), function() {
  14024. forEach(ast.arguments, function(expr) {
  14025. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14026. args.push(argument);
  14027. });
  14028. });
  14029. if (left.name) {
  14030. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  14031. } else {
  14032. expression = right + '(' + args.join(',') + ')';
  14033. }
  14034. self.assign(intoId, expression);
  14035. }, function() {
  14036. self.assign(intoId, 'undefined');
  14037. });
  14038. recursionFn(intoId);
  14039. });
  14040. }
  14041. break;
  14042. case AST.AssignmentExpression:
  14043. right = this.nextId();
  14044. left = {};
  14045. this.recurse(ast.left, undefined, left, function() {
  14046. self.if_(self.notNull(left.context), function() {
  14047. self.recurse(ast.right, right);
  14048. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  14049. self.assign(intoId, expression);
  14050. recursionFn(intoId || expression);
  14051. });
  14052. }, 1);
  14053. break;
  14054. case AST.ArrayExpression:
  14055. args = [];
  14056. forEach(ast.elements, function(expr) {
  14057. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14058. args.push(argument);
  14059. });
  14060. });
  14061. expression = '[' + args.join(',') + ']';
  14062. this.assign(intoId, expression);
  14063. recursionFn(intoId || expression);
  14064. break;
  14065. case AST.ObjectExpression:
  14066. args = [];
  14067. computed = false;
  14068. forEach(ast.properties, function(property) {
  14069. if (property.computed) {
  14070. computed = true;
  14071. }
  14072. });
  14073. if (computed) {
  14074. intoId = intoId || this.nextId();
  14075. this.assign(intoId, '{}');
  14076. forEach(ast.properties, function(property) {
  14077. if (property.computed) {
  14078. left = self.nextId();
  14079. self.recurse(property.key, left);
  14080. } else {
  14081. left = property.key.type === AST.Identifier ?
  14082. property.key.name :
  14083. ('' + property.key.value);
  14084. }
  14085. right = self.nextId();
  14086. self.recurse(property.value, right);
  14087. self.assign(self.member(intoId, left, property.computed), right);
  14088. });
  14089. } else {
  14090. forEach(ast.properties, function(property) {
  14091. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  14092. args.push(self.escape(
  14093. property.key.type === AST.Identifier ? property.key.name :
  14094. ('' + property.key.value)) +
  14095. ':' + expr);
  14096. });
  14097. });
  14098. expression = '{' + args.join(',') + '}';
  14099. this.assign(intoId, expression);
  14100. }
  14101. recursionFn(intoId || expression);
  14102. break;
  14103. case AST.ThisExpression:
  14104. this.assign(intoId, 's');
  14105. recursionFn(intoId || 's');
  14106. break;
  14107. case AST.LocalsExpression:
  14108. this.assign(intoId, 'l');
  14109. recursionFn(intoId || 'l');
  14110. break;
  14111. case AST.NGValueParameter:
  14112. this.assign(intoId, 'v');
  14113. recursionFn(intoId || 'v');
  14114. break;
  14115. }
  14116. },
  14117. getHasOwnProperty: function(element, property) {
  14118. var key = element + '.' + property;
  14119. var own = this.current().own;
  14120. if (!own.hasOwnProperty(key)) {
  14121. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  14122. }
  14123. return own[key];
  14124. },
  14125. assign: function(id, value) {
  14126. if (!id) return;
  14127. this.current().body.push(id, '=', value, ';');
  14128. return id;
  14129. },
  14130. filter: function(filterName) {
  14131. if (!this.state.filters.hasOwnProperty(filterName)) {
  14132. this.state.filters[filterName] = this.nextId(true);
  14133. }
  14134. return this.state.filters[filterName];
  14135. },
  14136. ifDefined: function(id, defaultValue) {
  14137. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  14138. },
  14139. plus: function(left, right) {
  14140. return 'plus(' + left + ',' + right + ')';
  14141. },
  14142. return_: function(id) {
  14143. this.current().body.push('return ', id, ';');
  14144. },
  14145. if_: function(test, alternate, consequent) {
  14146. if (test === true) {
  14147. alternate();
  14148. } else {
  14149. var body = this.current().body;
  14150. body.push('if(', test, '){');
  14151. alternate();
  14152. body.push('}');
  14153. if (consequent) {
  14154. body.push('else{');
  14155. consequent();
  14156. body.push('}');
  14157. }
  14158. }
  14159. },
  14160. not: function(expression) {
  14161. return '!(' + expression + ')';
  14162. },
  14163. isNull: function(expression) {
  14164. return expression + '==null';
  14165. },
  14166. notNull: function(expression) {
  14167. return expression + '!=null';
  14168. },
  14169. nonComputedMember: function(left, right) {
  14170. var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
  14171. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  14172. if (SAFE_IDENTIFIER.test(right)) {
  14173. return left + '.' + right;
  14174. } else {
  14175. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  14176. }
  14177. },
  14178. computedMember: function(left, right) {
  14179. return left + '[' + right + ']';
  14180. },
  14181. member: function(left, right, computed) {
  14182. if (computed) return this.computedMember(left, right);
  14183. return this.nonComputedMember(left, right);
  14184. },
  14185. getStringValue: function(item) {
  14186. this.assign(item, 'getStringValue(' + item + ')');
  14187. },
  14188. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14189. var self = this;
  14190. return function() {
  14191. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  14192. };
  14193. },
  14194. lazyAssign: function(id, value) {
  14195. var self = this;
  14196. return function() {
  14197. self.assign(id, value);
  14198. };
  14199. },
  14200. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  14201. stringEscapeFn: function(c) {
  14202. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  14203. },
  14204. escape: function(value) {
  14205. if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
  14206. if (isNumber(value)) return value.toString();
  14207. if (value === true) return 'true';
  14208. if (value === false) return 'false';
  14209. if (value === null) return 'null';
  14210. if (typeof value === 'undefined') return 'undefined';
  14211. throw $parseMinErr('esc', 'IMPOSSIBLE');
  14212. },
  14213. nextId: function(skip, init) {
  14214. var id = 'v' + (this.state.nextId++);
  14215. if (!skip) {
  14216. this.current().vars.push(id + (init ? '=' + init : ''));
  14217. }
  14218. return id;
  14219. },
  14220. current: function() {
  14221. return this.state[this.state.computing];
  14222. }
  14223. };
  14224. function ASTInterpreter($filter) {
  14225. this.$filter = $filter;
  14226. }
  14227. ASTInterpreter.prototype = {
  14228. compile: function(ast) {
  14229. var self = this;
  14230. findConstantAndWatchExpressions(ast, self.$filter);
  14231. var assignable;
  14232. var assign;
  14233. if ((assignable = assignableAST(ast))) {
  14234. assign = this.recurse(assignable);
  14235. }
  14236. var toWatch = getInputs(ast.body);
  14237. var inputs;
  14238. if (toWatch) {
  14239. inputs = [];
  14240. forEach(toWatch, function(watch, key) {
  14241. var input = self.recurse(watch);
  14242. watch.input = input;
  14243. inputs.push(input);
  14244. watch.watchId = key;
  14245. });
  14246. }
  14247. var expressions = [];
  14248. forEach(ast.body, function(expression) {
  14249. expressions.push(self.recurse(expression.expression));
  14250. });
  14251. var fn = ast.body.length === 0 ? noop :
  14252. ast.body.length === 1 ? expressions[0] :
  14253. function(scope, locals) {
  14254. var lastValue;
  14255. forEach(expressions, function(exp) {
  14256. lastValue = exp(scope, locals);
  14257. });
  14258. return lastValue;
  14259. };
  14260. if (assign) {
  14261. fn.assign = function(scope, value, locals) {
  14262. return assign(scope, locals, value);
  14263. };
  14264. }
  14265. if (inputs) {
  14266. fn.inputs = inputs;
  14267. }
  14268. return fn;
  14269. },
  14270. recurse: function(ast, context, create) {
  14271. var left, right, self = this, args;
  14272. if (ast.input) {
  14273. return this.inputs(ast.input, ast.watchId);
  14274. }
  14275. switch (ast.type) {
  14276. case AST.Literal:
  14277. return this.value(ast.value, context);
  14278. case AST.UnaryExpression:
  14279. right = this.recurse(ast.argument);
  14280. return this['unary' + ast.operator](right, context);
  14281. case AST.BinaryExpression:
  14282. left = this.recurse(ast.left);
  14283. right = this.recurse(ast.right);
  14284. return this['binary' + ast.operator](left, right, context);
  14285. case AST.LogicalExpression:
  14286. left = this.recurse(ast.left);
  14287. right = this.recurse(ast.right);
  14288. return this['binary' + ast.operator](left, right, context);
  14289. case AST.ConditionalExpression:
  14290. return this['ternary?:'](
  14291. this.recurse(ast.test),
  14292. this.recurse(ast.alternate),
  14293. this.recurse(ast.consequent),
  14294. context
  14295. );
  14296. case AST.Identifier:
  14297. return self.identifier(ast.name, context, create);
  14298. case AST.MemberExpression:
  14299. left = this.recurse(ast.object, false, !!create);
  14300. if (!ast.computed) {
  14301. right = ast.property.name;
  14302. }
  14303. if (ast.computed) right = this.recurse(ast.property);
  14304. return ast.computed ?
  14305. this.computedMember(left, right, context, create) :
  14306. this.nonComputedMember(left, right, context, create);
  14307. case AST.CallExpression:
  14308. args = [];
  14309. forEach(ast.arguments, function(expr) {
  14310. args.push(self.recurse(expr));
  14311. });
  14312. if (ast.filter) right = this.$filter(ast.callee.name);
  14313. if (!ast.filter) right = this.recurse(ast.callee, true);
  14314. return ast.filter ?
  14315. function(scope, locals, assign, inputs) {
  14316. var values = [];
  14317. for (var i = 0; i < args.length; ++i) {
  14318. values.push(args[i](scope, locals, assign, inputs));
  14319. }
  14320. var value = right.apply(undefined, values, inputs);
  14321. return context ? {context: undefined, name: undefined, value: value} : value;
  14322. } :
  14323. function(scope, locals, assign, inputs) {
  14324. var rhs = right(scope, locals, assign, inputs);
  14325. var value;
  14326. if (rhs.value != null) {
  14327. var values = [];
  14328. for (var i = 0; i < args.length; ++i) {
  14329. values.push(args[i](scope, locals, assign, inputs));
  14330. }
  14331. value = rhs.value.apply(rhs.context, values);
  14332. }
  14333. return context ? {value: value} : value;
  14334. };
  14335. case AST.AssignmentExpression:
  14336. left = this.recurse(ast.left, true, 1);
  14337. right = this.recurse(ast.right);
  14338. return function(scope, locals, assign, inputs) {
  14339. var lhs = left(scope, locals, assign, inputs);
  14340. var rhs = right(scope, locals, assign, inputs);
  14341. lhs.context[lhs.name] = rhs;
  14342. return context ? {value: rhs} : rhs;
  14343. };
  14344. case AST.ArrayExpression:
  14345. args = [];
  14346. forEach(ast.elements, function(expr) {
  14347. args.push(self.recurse(expr));
  14348. });
  14349. return function(scope, locals, assign, inputs) {
  14350. var value = [];
  14351. for (var i = 0; i < args.length; ++i) {
  14352. value.push(args[i](scope, locals, assign, inputs));
  14353. }
  14354. return context ? {value: value} : value;
  14355. };
  14356. case AST.ObjectExpression:
  14357. args = [];
  14358. forEach(ast.properties, function(property) {
  14359. if (property.computed) {
  14360. args.push({key: self.recurse(property.key),
  14361. computed: true,
  14362. value: self.recurse(property.value)
  14363. });
  14364. } else {
  14365. args.push({key: property.key.type === AST.Identifier ?
  14366. property.key.name :
  14367. ('' + property.key.value),
  14368. computed: false,
  14369. value: self.recurse(property.value)
  14370. });
  14371. }
  14372. });
  14373. return function(scope, locals, assign, inputs) {
  14374. var value = {};
  14375. for (var i = 0; i < args.length; ++i) {
  14376. if (args[i].computed) {
  14377. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  14378. } else {
  14379. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  14380. }
  14381. }
  14382. return context ? {value: value} : value;
  14383. };
  14384. case AST.ThisExpression:
  14385. return function(scope) {
  14386. return context ? {value: scope} : scope;
  14387. };
  14388. case AST.LocalsExpression:
  14389. return function(scope, locals) {
  14390. return context ? {value: locals} : locals;
  14391. };
  14392. case AST.NGValueParameter:
  14393. return function(scope, locals, assign) {
  14394. return context ? {value: assign} : assign;
  14395. };
  14396. }
  14397. },
  14398. 'unary+': function(argument, context) {
  14399. return function(scope, locals, assign, inputs) {
  14400. var arg = argument(scope, locals, assign, inputs);
  14401. if (isDefined(arg)) {
  14402. arg = +arg;
  14403. } else {
  14404. arg = 0;
  14405. }
  14406. return context ? {value: arg} : arg;
  14407. };
  14408. },
  14409. 'unary-': function(argument, context) {
  14410. return function(scope, locals, assign, inputs) {
  14411. var arg = argument(scope, locals, assign, inputs);
  14412. if (isDefined(arg)) {
  14413. arg = -arg;
  14414. } else {
  14415. arg = -0;
  14416. }
  14417. return context ? {value: arg} : arg;
  14418. };
  14419. },
  14420. 'unary!': function(argument, context) {
  14421. return function(scope, locals, assign, inputs) {
  14422. var arg = !argument(scope, locals, assign, inputs);
  14423. return context ? {value: arg} : arg;
  14424. };
  14425. },
  14426. 'binary+': function(left, right, context) {
  14427. return function(scope, locals, assign, inputs) {
  14428. var lhs = left(scope, locals, assign, inputs);
  14429. var rhs = right(scope, locals, assign, inputs);
  14430. var arg = plusFn(lhs, rhs);
  14431. return context ? {value: arg} : arg;
  14432. };
  14433. },
  14434. 'binary-': function(left, right, context) {
  14435. return function(scope, locals, assign, inputs) {
  14436. var lhs = left(scope, locals, assign, inputs);
  14437. var rhs = right(scope, locals, assign, inputs);
  14438. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  14439. return context ? {value: arg} : arg;
  14440. };
  14441. },
  14442. 'binary*': function(left, right, context) {
  14443. return function(scope, locals, assign, inputs) {
  14444. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  14445. return context ? {value: arg} : arg;
  14446. };
  14447. },
  14448. 'binary/': function(left, right, context) {
  14449. return function(scope, locals, assign, inputs) {
  14450. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  14451. return context ? {value: arg} : arg;
  14452. };
  14453. },
  14454. 'binary%': function(left, right, context) {
  14455. return function(scope, locals, assign, inputs) {
  14456. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  14457. return context ? {value: arg} : arg;
  14458. };
  14459. },
  14460. 'binary===': function(left, right, context) {
  14461. return function(scope, locals, assign, inputs) {
  14462. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  14463. return context ? {value: arg} : arg;
  14464. };
  14465. },
  14466. 'binary!==': function(left, right, context) {
  14467. return function(scope, locals, assign, inputs) {
  14468. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  14469. return context ? {value: arg} : arg;
  14470. };
  14471. },
  14472. 'binary==': function(left, right, context) {
  14473. return function(scope, locals, assign, inputs) {
  14474. // eslint-disable-next-line eqeqeq
  14475. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  14476. return context ? {value: arg} : arg;
  14477. };
  14478. },
  14479. 'binary!=': function(left, right, context) {
  14480. return function(scope, locals, assign, inputs) {
  14481. // eslint-disable-next-line eqeqeq
  14482. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  14483. return context ? {value: arg} : arg;
  14484. };
  14485. },
  14486. 'binary<': function(left, right, context) {
  14487. return function(scope, locals, assign, inputs) {
  14488. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  14489. return context ? {value: arg} : arg;
  14490. };
  14491. },
  14492. 'binary>': function(left, right, context) {
  14493. return function(scope, locals, assign, inputs) {
  14494. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  14495. return context ? {value: arg} : arg;
  14496. };
  14497. },
  14498. 'binary<=': function(left, right, context) {
  14499. return function(scope, locals, assign, inputs) {
  14500. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  14501. return context ? {value: arg} : arg;
  14502. };
  14503. },
  14504. 'binary>=': function(left, right, context) {
  14505. return function(scope, locals, assign, inputs) {
  14506. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  14507. return context ? {value: arg} : arg;
  14508. };
  14509. },
  14510. 'binary&&': function(left, right, context) {
  14511. return function(scope, locals, assign, inputs) {
  14512. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  14513. return context ? {value: arg} : arg;
  14514. };
  14515. },
  14516. 'binary||': function(left, right, context) {
  14517. return function(scope, locals, assign, inputs) {
  14518. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  14519. return context ? {value: arg} : arg;
  14520. };
  14521. },
  14522. 'ternary?:': function(test, alternate, consequent, context) {
  14523. return function(scope, locals, assign, inputs) {
  14524. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  14525. return context ? {value: arg} : arg;
  14526. };
  14527. },
  14528. value: function(value, context) {
  14529. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  14530. },
  14531. identifier: function(name, context, create) {
  14532. return function(scope, locals, assign, inputs) {
  14533. var base = locals && (name in locals) ? locals : scope;
  14534. if (create && create !== 1 && base && base[name] == null) {
  14535. base[name] = {};
  14536. }
  14537. var value = base ? base[name] : undefined;
  14538. if (context) {
  14539. return {context: base, name: name, value: value};
  14540. } else {
  14541. return value;
  14542. }
  14543. };
  14544. },
  14545. computedMember: function(left, right, context, create) {
  14546. return function(scope, locals, assign, inputs) {
  14547. var lhs = left(scope, locals, assign, inputs);
  14548. var rhs;
  14549. var value;
  14550. if (lhs != null) {
  14551. rhs = right(scope, locals, assign, inputs);
  14552. rhs = getStringValue(rhs);
  14553. if (create && create !== 1) {
  14554. if (lhs && !(lhs[rhs])) {
  14555. lhs[rhs] = {};
  14556. }
  14557. }
  14558. value = lhs[rhs];
  14559. }
  14560. if (context) {
  14561. return {context: lhs, name: rhs, value: value};
  14562. } else {
  14563. return value;
  14564. }
  14565. };
  14566. },
  14567. nonComputedMember: function(left, right, context, create) {
  14568. return function(scope, locals, assign, inputs) {
  14569. var lhs = left(scope, locals, assign, inputs);
  14570. if (create && create !== 1) {
  14571. if (lhs && lhs[right] == null) {
  14572. lhs[right] = {};
  14573. }
  14574. }
  14575. var value = lhs != null ? lhs[right] : undefined;
  14576. if (context) {
  14577. return {context: lhs, name: right, value: value};
  14578. } else {
  14579. return value;
  14580. }
  14581. };
  14582. },
  14583. inputs: function(input, watchId) {
  14584. return function(scope, value, locals, inputs) {
  14585. if (inputs) return inputs[watchId];
  14586. return input(scope, value, locals);
  14587. };
  14588. }
  14589. };
  14590. /**
  14591. * @constructor
  14592. */
  14593. function Parser(lexer, $filter, options) {
  14594. this.ast = new AST(lexer, options);
  14595. this.astCompiler = options.csp ? new ASTInterpreter($filter) :
  14596. new ASTCompiler($filter);
  14597. }
  14598. Parser.prototype = {
  14599. constructor: Parser,
  14600. parse: function(text) {
  14601. var ast = this.ast.ast(text);
  14602. var fn = this.astCompiler.compile(ast);
  14603. fn.literal = isLiteral(ast);
  14604. fn.constant = isConstant(ast);
  14605. return fn;
  14606. }
  14607. };
  14608. function getValueOf(value) {
  14609. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  14610. }
  14611. ///////////////////////////////////
  14612. /**
  14613. * @ngdoc service
  14614. * @name $parse
  14615. * @kind function
  14616. *
  14617. * @description
  14618. *
  14619. * Converts Angular {@link guide/expression expression} into a function.
  14620. *
  14621. * ```js
  14622. * var getter = $parse('user.name');
  14623. * var setter = getter.assign;
  14624. * var context = {user:{name:'angular'}};
  14625. * var locals = {user:{name:'local'}};
  14626. *
  14627. * expect(getter(context)).toEqual('angular');
  14628. * setter(context, 'newValue');
  14629. * expect(context.user.name).toEqual('newValue');
  14630. * expect(getter(context, locals)).toEqual('local');
  14631. * ```
  14632. *
  14633. *
  14634. * @param {string} expression String expression to compile.
  14635. * @returns {function(context, locals)} a function which represents the compiled expression:
  14636. *
  14637. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14638. * are evaluated against (typically a scope object).
  14639. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14640. * `context`.
  14641. *
  14642. * The returned function also has the following properties:
  14643. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  14644. * literal.
  14645. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  14646. * constant literals.
  14647. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  14648. * set to a function to change its value on the given context.
  14649. *
  14650. */
  14651. /**
  14652. * @ngdoc provider
  14653. * @name $parseProvider
  14654. * @this
  14655. *
  14656. * @description
  14657. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  14658. * service.
  14659. */
  14660. function $ParseProvider() {
  14661. var cache = createMap();
  14662. var literals = {
  14663. 'true': true,
  14664. 'false': false,
  14665. 'null': null,
  14666. 'undefined': undefined
  14667. };
  14668. var identStart, identContinue;
  14669. /**
  14670. * @ngdoc method
  14671. * @name $parseProvider#addLiteral
  14672. * @description
  14673. *
  14674. * Configure $parse service to add literal values that will be present as literal at expressions.
  14675. *
  14676. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  14677. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  14678. *
  14679. **/
  14680. this.addLiteral = function(literalName, literalValue) {
  14681. literals[literalName] = literalValue;
  14682. };
  14683. /**
  14684. * @ngdoc method
  14685. * @name $parseProvider#setIdentifierFns
  14686. *
  14687. * @description
  14688. *
  14689. * Allows defining the set of characters that are allowed in Angular expressions. The function
  14690. * `identifierStart` will get called to know if a given character is a valid character to be the
  14691. * first character for an identifier. The function `identifierContinue` will get called to know if
  14692. * a given character is a valid character to be a follow-up identifier character. The functions
  14693. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  14694. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  14695. * mind that the `string` parameter can be two characters long depending on the character
  14696. * representation. It is expected for the function to return `true` or `false`, whether that
  14697. * character is allowed or not.
  14698. *
  14699. * Since this function will be called extensively, keep the implementation of these functions fast,
  14700. * as the performance of these functions have a direct impact on the expressions parsing speed.
  14701. *
  14702. * @param {function=} identifierStart The function that will decide whether the given character is
  14703. * a valid identifier start character.
  14704. * @param {function=} identifierContinue The function that will decide whether the given character is
  14705. * a valid identifier continue character.
  14706. */
  14707. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  14708. identStart = identifierStart;
  14709. identContinue = identifierContinue;
  14710. return this;
  14711. };
  14712. this.$get = ['$filter', function($filter) {
  14713. var noUnsafeEval = csp().noUnsafeEval;
  14714. var $parseOptions = {
  14715. csp: noUnsafeEval,
  14716. literals: copy(literals),
  14717. isIdentifierStart: isFunction(identStart) && identStart,
  14718. isIdentifierContinue: isFunction(identContinue) && identContinue
  14719. };
  14720. return $parse;
  14721. function $parse(exp, interceptorFn) {
  14722. var parsedExpression, oneTime, cacheKey;
  14723. switch (typeof exp) {
  14724. case 'string':
  14725. exp = exp.trim();
  14726. cacheKey = exp;
  14727. parsedExpression = cache[cacheKey];
  14728. if (!parsedExpression) {
  14729. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  14730. oneTime = true;
  14731. exp = exp.substring(2);
  14732. }
  14733. var lexer = new Lexer($parseOptions);
  14734. var parser = new Parser(lexer, $filter, $parseOptions);
  14735. parsedExpression = parser.parse(exp);
  14736. if (parsedExpression.constant) {
  14737. parsedExpression.$$watchDelegate = constantWatchDelegate;
  14738. } else if (oneTime) {
  14739. parsedExpression.oneTime = true;
  14740. parsedExpression.$$watchDelegate = oneTimeWatchDelegate;
  14741. } else if (parsedExpression.inputs) {
  14742. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  14743. }
  14744. cache[cacheKey] = parsedExpression;
  14745. }
  14746. return addInterceptor(parsedExpression, interceptorFn);
  14747. case 'function':
  14748. return addInterceptor(exp, interceptorFn);
  14749. default:
  14750. return addInterceptor(noop, interceptorFn);
  14751. }
  14752. }
  14753. function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) {
  14754. if (newValue == null || oldValueOfValue == null) { // null/undefined
  14755. return newValue === oldValueOfValue;
  14756. }
  14757. if (typeof newValue === 'object') {
  14758. // attempt to convert the value to a primitive type
  14759. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  14760. // be cheaply dirty-checked
  14761. newValue = getValueOf(newValue);
  14762. if (typeof newValue === 'object' && !compareObjectIdentity) {
  14763. // objects/arrays are not supported - deep-watching them would be too expensive
  14764. return false;
  14765. }
  14766. // fall-through to the primitive equality check
  14767. }
  14768. //Primitive or NaN
  14769. // eslint-disable-next-line no-self-compare
  14770. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  14771. }
  14772. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14773. var inputExpressions = parsedExpression.inputs;
  14774. var lastResult;
  14775. if (inputExpressions.length === 1) {
  14776. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14777. inputExpressions = inputExpressions[0];
  14778. return scope.$watch(function expressionInputWatch(scope) {
  14779. var newInputValue = inputExpressions(scope);
  14780. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, parsedExpression.literal)) {
  14781. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  14782. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  14783. }
  14784. return lastResult;
  14785. }, listener, objectEquality, prettyPrintExpression);
  14786. }
  14787. var oldInputValueOfValues = [];
  14788. var oldInputValues = [];
  14789. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14790. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14791. oldInputValues[i] = null;
  14792. }
  14793. return scope.$watch(function expressionInputsWatch(scope) {
  14794. var changed = false;
  14795. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14796. var newInputValue = inputExpressions[i](scope);
  14797. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], parsedExpression.literal))) {
  14798. oldInputValues[i] = newInputValue;
  14799. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  14800. }
  14801. }
  14802. if (changed) {
  14803. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  14804. }
  14805. return lastResult;
  14806. }, listener, objectEquality, prettyPrintExpression);
  14807. }
  14808. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14809. var isDone = parsedExpression.literal ? isAllDefined : isDefined;
  14810. var unwatch, lastValue;
  14811. if (parsedExpression.inputs) {
  14812. unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
  14813. } else {
  14814. unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
  14815. }
  14816. return unwatch;
  14817. function oneTimeWatch(scope) {
  14818. return parsedExpression(scope);
  14819. }
  14820. function oneTimeListener(value, old, scope) {
  14821. lastValue = value;
  14822. if (isFunction(listener)) {
  14823. listener(value, old, scope);
  14824. }
  14825. if (isDone(value)) {
  14826. scope.$$postDigest(function() {
  14827. if (isDone(lastValue)) {
  14828. unwatch();
  14829. }
  14830. });
  14831. }
  14832. }
  14833. }
  14834. function isAllDefined(value) {
  14835. var allDefined = true;
  14836. forEach(value, function(val) {
  14837. if (!isDefined(val)) allDefined = false;
  14838. });
  14839. return allDefined;
  14840. }
  14841. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14842. var unwatch = scope.$watch(function constantWatch(scope) {
  14843. unwatch();
  14844. return parsedExpression(scope);
  14845. }, listener, objectEquality);
  14846. return unwatch;
  14847. }
  14848. function addInterceptor(parsedExpression, interceptorFn) {
  14849. if (!interceptorFn) return parsedExpression;
  14850. var watchDelegate = parsedExpression.$$watchDelegate;
  14851. var useInputs = false;
  14852. var isDone = parsedExpression.literal ? isAllDefined : isDefined;
  14853. function regularInterceptedExpression(scope, locals, assign, inputs) {
  14854. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  14855. return interceptorFn(value, scope, locals);
  14856. }
  14857. function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  14858. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  14859. var result = interceptorFn(value, scope, locals);
  14860. // we only return the interceptor's result if the
  14861. // initial value is defined (for bind-once)
  14862. return isDone(value) ? result : value;
  14863. }
  14864. var fn = parsedExpression.oneTime ? oneTimeInterceptedExpression : regularInterceptedExpression;
  14865. // Propogate the literal/oneTime attributes
  14866. fn.literal = parsedExpression.literal;
  14867. fn.oneTime = parsedExpression.oneTime;
  14868. // Propagate or create inputs / $$watchDelegates
  14869. useInputs = !parsedExpression.inputs;
  14870. if (watchDelegate && watchDelegate !== inputsWatchDelegate) {
  14871. fn.$$watchDelegate = watchDelegate;
  14872. fn.inputs = parsedExpression.inputs;
  14873. } else if (!interceptorFn.$stateful) {
  14874. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  14875. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  14876. fn.$$watchDelegate = inputsWatchDelegate;
  14877. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  14878. }
  14879. return fn;
  14880. }
  14881. }];
  14882. }
  14883. /**
  14884. * @ngdoc service
  14885. * @name $q
  14886. * @requires $rootScope
  14887. *
  14888. * @description
  14889. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  14890. * when they are done processing.
  14891. *
  14892. * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred
  14893. * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  14894. *
  14895. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  14896. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  14897. *
  14898. * # $q constructor
  14899. *
  14900. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  14901. * function as the first argument. This is similar to the native Promise implementation from ES6,
  14902. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  14903. *
  14904. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  14905. * available yet.
  14906. *
  14907. * It can be used like so:
  14908. *
  14909. * ```js
  14910. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14911. * // are available in the current lexical scope (they could have been injected or passed in).
  14912. *
  14913. * function asyncGreet(name) {
  14914. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  14915. * return $q(function(resolve, reject) {
  14916. * setTimeout(function() {
  14917. * if (okToGreet(name)) {
  14918. * resolve('Hello, ' + name + '!');
  14919. * } else {
  14920. * reject('Greeting ' + name + ' is not allowed.');
  14921. * }
  14922. * }, 1000);
  14923. * });
  14924. * }
  14925. *
  14926. * var promise = asyncGreet('Robin Hood');
  14927. * promise.then(function(greeting) {
  14928. * alert('Success: ' + greeting);
  14929. * }, function(reason) {
  14930. * alert('Failed: ' + reason);
  14931. * });
  14932. * ```
  14933. *
  14934. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  14935. *
  14936. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  14937. *
  14938. * However, the more traditional CommonJS-style usage is still available, and documented below.
  14939. *
  14940. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  14941. * interface for interacting with an object that represents the result of an action that is
  14942. * performed asynchronously, and may or may not be finished at any given point in time.
  14943. *
  14944. * From the perspective of dealing with error handling, deferred and promise APIs are to
  14945. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  14946. *
  14947. * ```js
  14948. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14949. * // are available in the current lexical scope (they could have been injected or passed in).
  14950. *
  14951. * function asyncGreet(name) {
  14952. * var deferred = $q.defer();
  14953. *
  14954. * setTimeout(function() {
  14955. * deferred.notify('About to greet ' + name + '.');
  14956. *
  14957. * if (okToGreet(name)) {
  14958. * deferred.resolve('Hello, ' + name + '!');
  14959. * } else {
  14960. * deferred.reject('Greeting ' + name + ' is not allowed.');
  14961. * }
  14962. * }, 1000);
  14963. *
  14964. * return deferred.promise;
  14965. * }
  14966. *
  14967. * var promise = asyncGreet('Robin Hood');
  14968. * promise.then(function(greeting) {
  14969. * alert('Success: ' + greeting);
  14970. * }, function(reason) {
  14971. * alert('Failed: ' + reason);
  14972. * }, function(update) {
  14973. * alert('Got notification: ' + update);
  14974. * });
  14975. * ```
  14976. *
  14977. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  14978. * comes in the way of guarantees that promise and deferred APIs make, see
  14979. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  14980. *
  14981. * Additionally the promise api allows for composition that is very hard to do with the
  14982. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  14983. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  14984. * section on serial or parallel joining of promises.
  14985. *
  14986. * # The Deferred API
  14987. *
  14988. * A new instance of deferred is constructed by calling `$q.defer()`.
  14989. *
  14990. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  14991. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  14992. * of the task.
  14993. *
  14994. * **Methods**
  14995. *
  14996. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  14997. * constructed via `$q.reject`, the promise will be rejected instead.
  14998. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  14999. * resolving it with a rejection constructed via `$q.reject`.
  15000. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  15001. * multiple times before the promise is either resolved or rejected.
  15002. *
  15003. * **Properties**
  15004. *
  15005. * - promise – `{Promise}` – promise object associated with this deferred.
  15006. *
  15007. *
  15008. * # The Promise API
  15009. *
  15010. * A new promise instance is created when a deferred instance is created and can be retrieved by
  15011. * calling `deferred.promise`.
  15012. *
  15013. * The purpose of the promise object is to allow for interested parties to get access to the result
  15014. * of the deferred task when it completes.
  15015. *
  15016. * **Methods**
  15017. *
  15018. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  15019. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  15020. * as soon as the result is available. The callbacks are called with a single argument: the result
  15021. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  15022. * provide a progress indication, before the promise is resolved or rejected.
  15023. *
  15024. * This method *returns a new promise* which is resolved or rejected via the return value of the
  15025. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  15026. * with the value which is resolved in that promise using
  15027. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  15028. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  15029. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  15030. * arguments are optional.
  15031. *
  15032. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  15033. *
  15034. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  15035. * but to do so without modifying the final value. This is useful to release resources or do some
  15036. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  15037. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  15038. * more information.
  15039. *
  15040. * # Chaining promises
  15041. *
  15042. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  15043. * possible to create a chain of promises:
  15044. *
  15045. * ```js
  15046. * promiseB = promiseA.then(function(result) {
  15047. * return result + 1;
  15048. * });
  15049. *
  15050. * // promiseB will be resolved immediately after promiseA is resolved and its value
  15051. * // will be the result of promiseA incremented by 1
  15052. * ```
  15053. *
  15054. * It is possible to create chains of any length and since a promise can be resolved with another
  15055. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  15056. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  15057. * $http's response interceptors.
  15058. *
  15059. *
  15060. * # Differences between Kris Kowal's Q and $q
  15061. *
  15062. * There are two main differences:
  15063. *
  15064. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  15065. * mechanism in angular, which means faster propagation of resolution or rejection into your
  15066. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  15067. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  15068. * all the important functionality needed for common async tasks.
  15069. *
  15070. * # Testing
  15071. *
  15072. * ```js
  15073. * it('should simulate promise', inject(function($q, $rootScope) {
  15074. * var deferred = $q.defer();
  15075. * var promise = deferred.promise;
  15076. * var resolvedValue;
  15077. *
  15078. * promise.then(function(value) { resolvedValue = value; });
  15079. * expect(resolvedValue).toBeUndefined();
  15080. *
  15081. * // Simulate resolving of promise
  15082. * deferred.resolve(123);
  15083. * // Note that the 'then' function does not get called synchronously.
  15084. * // This is because we want the promise API to always be async, whether or not
  15085. * // it got called synchronously or asynchronously.
  15086. * expect(resolvedValue).toBeUndefined();
  15087. *
  15088. * // Propagate promise resolution to 'then' functions using $apply().
  15089. * $rootScope.$apply();
  15090. * expect(resolvedValue).toEqual(123);
  15091. * }));
  15092. * ```
  15093. *
  15094. * @param {function(function, function)} resolver Function which is responsible for resolving or
  15095. * rejecting the newly created promise. The first parameter is a function which resolves the
  15096. * promise, the second parameter is a function which rejects the promise.
  15097. *
  15098. * @returns {Promise} The newly created promise.
  15099. */
  15100. /**
  15101. * @ngdoc provider
  15102. * @name $qProvider
  15103. * @this
  15104. *
  15105. * @description
  15106. */
  15107. function $QProvider() {
  15108. var errorOnUnhandledRejections = true;
  15109. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  15110. return qFactory(function(callback) {
  15111. $rootScope.$evalAsync(callback);
  15112. }, $exceptionHandler, errorOnUnhandledRejections);
  15113. }];
  15114. /**
  15115. * @ngdoc method
  15116. * @name $qProvider#errorOnUnhandledRejections
  15117. * @kind function
  15118. *
  15119. * @description
  15120. * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
  15121. * This feature is enabled by default.
  15122. *
  15123. * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
  15124. * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
  15125. * chaining otherwise.
  15126. */
  15127. this.errorOnUnhandledRejections = function(value) {
  15128. if (isDefined(value)) {
  15129. errorOnUnhandledRejections = value;
  15130. return this;
  15131. } else {
  15132. return errorOnUnhandledRejections;
  15133. }
  15134. };
  15135. }
  15136. /** @this */
  15137. function $$QProvider() {
  15138. var errorOnUnhandledRejections = true;
  15139. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  15140. return qFactory(function(callback) {
  15141. $browser.defer(callback);
  15142. }, $exceptionHandler, errorOnUnhandledRejections);
  15143. }];
  15144. this.errorOnUnhandledRejections = function(value) {
  15145. if (isDefined(value)) {
  15146. errorOnUnhandledRejections = value;
  15147. return this;
  15148. } else {
  15149. return errorOnUnhandledRejections;
  15150. }
  15151. };
  15152. }
  15153. /**
  15154. * Constructs a promise manager.
  15155. *
  15156. * @param {function(function)} nextTick Function for executing functions in the next turn.
  15157. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  15158. * debugging purposes.
  15159. @ param {=boolean} errorOnUnhandledRejections Whether an error should be generated on unhandled
  15160. * promises rejections.
  15161. * @returns {object} Promise manager.
  15162. */
  15163. function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
  15164. var $qMinErr = minErr('$q', TypeError);
  15165. var queueSize = 0;
  15166. var checkQueue = [];
  15167. /**
  15168. * @ngdoc method
  15169. * @name ng.$q#defer
  15170. * @kind function
  15171. *
  15172. * @description
  15173. * Creates a `Deferred` object which represents a task which will finish in the future.
  15174. *
  15175. * @returns {Deferred} Returns a new instance of deferred.
  15176. */
  15177. function defer() {
  15178. return new Deferred();
  15179. }
  15180. function Deferred() {
  15181. var promise = this.promise = new Promise();
  15182. //Non prototype methods necessary to support unbound execution :/
  15183. this.resolve = function(val) { resolvePromise(promise, val); };
  15184. this.reject = function(reason) { rejectPromise(promise, reason); };
  15185. this.notify = function(progress) { notifyPromise(promise, progress); };
  15186. }
  15187. function Promise() {
  15188. this.$$state = { status: 0 };
  15189. }
  15190. extend(Promise.prototype, {
  15191. then: function(onFulfilled, onRejected, progressBack) {
  15192. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  15193. return this;
  15194. }
  15195. var result = new Promise();
  15196. this.$$state.pending = this.$$state.pending || [];
  15197. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  15198. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  15199. return result;
  15200. },
  15201. 'catch': function(callback) {
  15202. return this.then(null, callback);
  15203. },
  15204. 'finally': function(callback, progressBack) {
  15205. return this.then(function(value) {
  15206. return handleCallback(value, resolve, callback);
  15207. }, function(error) {
  15208. return handleCallback(error, reject, callback);
  15209. }, progressBack);
  15210. }
  15211. });
  15212. function processQueue(state) {
  15213. var fn, promise, pending;
  15214. pending = state.pending;
  15215. state.processScheduled = false;
  15216. state.pending = undefined;
  15217. try {
  15218. for (var i = 0, ii = pending.length; i < ii; ++i) {
  15219. state.pur = true;
  15220. promise = pending[i][0];
  15221. fn = pending[i][state.status];
  15222. try {
  15223. if (isFunction(fn)) {
  15224. resolvePromise(promise, fn(state.value));
  15225. } else if (state.status === 1) {
  15226. resolvePromise(promise, state.value);
  15227. } else {
  15228. rejectPromise(promise, state.value);
  15229. }
  15230. } catch (e) {
  15231. rejectPromise(promise, e);
  15232. }
  15233. }
  15234. } finally {
  15235. --queueSize;
  15236. if (errorOnUnhandledRejections && queueSize === 0) {
  15237. nextTick(processChecks);
  15238. }
  15239. }
  15240. }
  15241. function processChecks() {
  15242. // eslint-disable-next-line no-unmodified-loop-condition
  15243. while (!queueSize && checkQueue.length) {
  15244. var toCheck = checkQueue.shift();
  15245. if (!toCheck.pur) {
  15246. toCheck.pur = true;
  15247. var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
  15248. if (toCheck.value instanceof Error) {
  15249. exceptionHandler(toCheck.value, errorMessage);
  15250. } else {
  15251. exceptionHandler(errorMessage);
  15252. }
  15253. }
  15254. }
  15255. }
  15256. function scheduleProcessQueue(state) {
  15257. if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !state.pur) {
  15258. if (queueSize === 0 && checkQueue.length === 0) {
  15259. nextTick(processChecks);
  15260. }
  15261. checkQueue.push(state);
  15262. }
  15263. if (state.processScheduled || !state.pending) return;
  15264. state.processScheduled = true;
  15265. ++queueSize;
  15266. nextTick(function() { processQueue(state); });
  15267. }
  15268. function resolvePromise(promise, val) {
  15269. if (promise.$$state.status) return;
  15270. if (val === promise) {
  15271. $$reject(promise, $qMinErr(
  15272. 'qcycle',
  15273. 'Expected promise to be resolved with value other than itself \'{0}\'',
  15274. val));
  15275. } else {
  15276. $$resolve(promise, val);
  15277. }
  15278. }
  15279. function $$resolve(promise, val) {
  15280. var then;
  15281. var done = false;
  15282. try {
  15283. if (isObject(val) || isFunction(val)) then = val.then;
  15284. if (isFunction(then)) {
  15285. promise.$$state.status = -1;
  15286. then.call(val, doResolve, doReject, doNotify);
  15287. } else {
  15288. promise.$$state.value = val;
  15289. promise.$$state.status = 1;
  15290. scheduleProcessQueue(promise.$$state);
  15291. }
  15292. } catch (e) {
  15293. doReject(e);
  15294. }
  15295. function doResolve(val) {
  15296. if (done) return;
  15297. done = true;
  15298. $$resolve(promise, val);
  15299. }
  15300. function doReject(val) {
  15301. if (done) return;
  15302. done = true;
  15303. $$reject(promise, val);
  15304. }
  15305. function doNotify(progress) {
  15306. notifyPromise(promise, progress);
  15307. }
  15308. }
  15309. function rejectPromise(promise, reason) {
  15310. if (promise.$$state.status) return;
  15311. $$reject(promise, reason);
  15312. }
  15313. function $$reject(promise, reason) {
  15314. promise.$$state.value = reason;
  15315. promise.$$state.status = 2;
  15316. scheduleProcessQueue(promise.$$state);
  15317. }
  15318. function notifyPromise(promise, progress) {
  15319. var callbacks = promise.$$state.pending;
  15320. if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {
  15321. nextTick(function() {
  15322. var callback, result;
  15323. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  15324. result = callbacks[i][0];
  15325. callback = callbacks[i][3];
  15326. try {
  15327. notifyPromise(result, isFunction(callback) ? callback(progress) : progress);
  15328. } catch (e) {
  15329. exceptionHandler(e);
  15330. }
  15331. }
  15332. });
  15333. }
  15334. }
  15335. /**
  15336. * @ngdoc method
  15337. * @name $q#reject
  15338. * @kind function
  15339. *
  15340. * @description
  15341. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  15342. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  15343. * a promise chain, you don't need to worry about it.
  15344. *
  15345. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  15346. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  15347. * a promise error callback and you want to forward the error to the promise derived from the
  15348. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  15349. * `reject`.
  15350. *
  15351. * ```js
  15352. * promiseB = promiseA.then(function(result) {
  15353. * // success: do something and resolve promiseB
  15354. * // with the old or a new result
  15355. * return result;
  15356. * }, function(reason) {
  15357. * // error: handle the error if possible and
  15358. * // resolve promiseB with newPromiseOrValue,
  15359. * // otherwise forward the rejection to promiseB
  15360. * if (canHandle(reason)) {
  15361. * // handle the error and recover
  15362. * return newPromiseOrValue;
  15363. * }
  15364. * return $q.reject(reason);
  15365. * });
  15366. * ```
  15367. *
  15368. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  15369. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  15370. */
  15371. function reject(reason) {
  15372. var result = new Promise();
  15373. rejectPromise(result, reason);
  15374. return result;
  15375. }
  15376. function handleCallback(value, resolver, callback) {
  15377. var callbackOutput = null;
  15378. try {
  15379. if (isFunction(callback)) callbackOutput = callback();
  15380. } catch (e) {
  15381. return reject(e);
  15382. }
  15383. if (isPromiseLike(callbackOutput)) {
  15384. return callbackOutput.then(function() {
  15385. return resolver(value);
  15386. }, reject);
  15387. } else {
  15388. return resolver(value);
  15389. }
  15390. }
  15391. /**
  15392. * @ngdoc method
  15393. * @name $q#when
  15394. * @kind function
  15395. *
  15396. * @description
  15397. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  15398. * This is useful when you are dealing with an object that might or might not be a promise, or if
  15399. * the promise comes from a source that can't be trusted.
  15400. *
  15401. * @param {*} value Value or a promise
  15402. * @param {Function=} successCallback
  15403. * @param {Function=} errorCallback
  15404. * @param {Function=} progressCallback
  15405. * @returns {Promise} Returns a promise of the passed value or promise
  15406. */
  15407. function when(value, callback, errback, progressBack) {
  15408. var result = new Promise();
  15409. resolvePromise(result, value);
  15410. return result.then(callback, errback, progressBack);
  15411. }
  15412. /**
  15413. * @ngdoc method
  15414. * @name $q#resolve
  15415. * @kind function
  15416. *
  15417. * @description
  15418. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  15419. *
  15420. * @param {*} value Value or a promise
  15421. * @param {Function=} successCallback
  15422. * @param {Function=} errorCallback
  15423. * @param {Function=} progressCallback
  15424. * @returns {Promise} Returns a promise of the passed value or promise
  15425. */
  15426. var resolve = when;
  15427. /**
  15428. * @ngdoc method
  15429. * @name $q#all
  15430. * @kind function
  15431. *
  15432. * @description
  15433. * Combines multiple promises into a single promise that is resolved when all of the input
  15434. * promises are resolved.
  15435. *
  15436. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15437. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  15438. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  15439. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  15440. * with the same rejection value.
  15441. */
  15442. function all(promises) {
  15443. var result = new Promise(),
  15444. counter = 0,
  15445. results = isArray(promises) ? [] : {};
  15446. forEach(promises, function(promise, key) {
  15447. counter++;
  15448. when(promise).then(function(value) {
  15449. results[key] = value;
  15450. if (!(--counter)) resolvePromise(result, results);
  15451. }, function(reason) {
  15452. rejectPromise(result, reason);
  15453. });
  15454. });
  15455. if (counter === 0) {
  15456. resolvePromise(result, results);
  15457. }
  15458. return result;
  15459. }
  15460. /**
  15461. * @ngdoc method
  15462. * @name $q#race
  15463. * @kind function
  15464. *
  15465. * @description
  15466. * Returns a promise that resolves or rejects as soon as one of those promises
  15467. * resolves or rejects, with the value or reason from that promise.
  15468. *
  15469. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15470. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  15471. * resolves or rejects, with the value or reason from that promise.
  15472. */
  15473. function race(promises) {
  15474. var deferred = defer();
  15475. forEach(promises, function(promise) {
  15476. when(promise).then(deferred.resolve, deferred.reject);
  15477. });
  15478. return deferred.promise;
  15479. }
  15480. function $Q(resolver) {
  15481. if (!isFunction(resolver)) {
  15482. throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
  15483. }
  15484. var promise = new Promise();
  15485. function resolveFn(value) {
  15486. resolvePromise(promise, value);
  15487. }
  15488. function rejectFn(reason) {
  15489. rejectPromise(promise, reason);
  15490. }
  15491. resolver(resolveFn, rejectFn);
  15492. return promise;
  15493. }
  15494. // Let's make the instanceof operator work for promises, so that
  15495. // `new $q(fn) instanceof $q` would evaluate to true.
  15496. $Q.prototype = Promise.prototype;
  15497. $Q.defer = defer;
  15498. $Q.reject = reject;
  15499. $Q.when = when;
  15500. $Q.resolve = resolve;
  15501. $Q.all = all;
  15502. $Q.race = race;
  15503. return $Q;
  15504. }
  15505. /** @this */
  15506. function $$RAFProvider() { //rAF
  15507. this.$get = ['$window', '$timeout', function($window, $timeout) {
  15508. var requestAnimationFrame = $window.requestAnimationFrame ||
  15509. $window.webkitRequestAnimationFrame;
  15510. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  15511. $window.webkitCancelAnimationFrame ||
  15512. $window.webkitCancelRequestAnimationFrame;
  15513. var rafSupported = !!requestAnimationFrame;
  15514. var raf = rafSupported
  15515. ? function(fn) {
  15516. var id = requestAnimationFrame(fn);
  15517. return function() {
  15518. cancelAnimationFrame(id);
  15519. };
  15520. }
  15521. : function(fn) {
  15522. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  15523. return function() {
  15524. $timeout.cancel(timer);
  15525. };
  15526. };
  15527. raf.supported = rafSupported;
  15528. return raf;
  15529. }];
  15530. }
  15531. /**
  15532. * DESIGN NOTES
  15533. *
  15534. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  15535. *
  15536. * The typical use of scope is to watch the expressions, which most of the time return the same
  15537. * value as last time so we optimize the operation.
  15538. *
  15539. * Closures construction is expensive in terms of speed as well as memory:
  15540. * - No closures, instead use prototypical inheritance for API
  15541. * - Internal state needs to be stored on scope directly, which means that private state is
  15542. * exposed as $$____ properties
  15543. *
  15544. * Loop operations are optimized by using while(count--) { ... }
  15545. * - This means that in order to keep the same order of execution as addition we have to add
  15546. * items to the array at the beginning (unshift) instead of at the end (push)
  15547. *
  15548. * Child scopes are created and removed often
  15549. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  15550. *
  15551. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  15552. * in the same way as watch. Watch requires return of the initialization function which is expensive
  15553. * to construct.
  15554. */
  15555. /**
  15556. * @ngdoc provider
  15557. * @name $rootScopeProvider
  15558. * @description
  15559. *
  15560. * Provider for the $rootScope service.
  15561. */
  15562. /**
  15563. * @ngdoc method
  15564. * @name $rootScopeProvider#digestTtl
  15565. * @description
  15566. *
  15567. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  15568. * assuming that the model is unstable.
  15569. *
  15570. * The current default is 10 iterations.
  15571. *
  15572. * In complex applications it's possible that the dependencies between `$watch`s will result in
  15573. * several digest iterations. However if an application needs more than the default 10 digest
  15574. * iterations for its model to stabilize then you should investigate what is causing the model to
  15575. * continuously change during the digest.
  15576. *
  15577. * Increasing the TTL could have performance implications, so you should not change it without
  15578. * proper justification.
  15579. *
  15580. * @param {number} limit The number of digest iterations.
  15581. */
  15582. /**
  15583. * @ngdoc service
  15584. * @name $rootScope
  15585. * @this
  15586. *
  15587. * @description
  15588. *
  15589. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  15590. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  15591. * between the model and the view, via a mechanism for watching the model for changes.
  15592. * They also provide event emission/broadcast and subscription facility. See the
  15593. * {@link guide/scope developer guide on scopes}.
  15594. */
  15595. function $RootScopeProvider() {
  15596. var TTL = 10;
  15597. var $rootScopeMinErr = minErr('$rootScope');
  15598. var lastDirtyWatch = null;
  15599. var applyAsyncId = null;
  15600. this.digestTtl = function(value) {
  15601. if (arguments.length) {
  15602. TTL = value;
  15603. }
  15604. return TTL;
  15605. };
  15606. function createChildScopeClass(parent) {
  15607. function ChildScope() {
  15608. this.$$watchers = this.$$nextSibling =
  15609. this.$$childHead = this.$$childTail = null;
  15610. this.$$listeners = {};
  15611. this.$$listenerCount = {};
  15612. this.$$watchersCount = 0;
  15613. this.$id = nextUid();
  15614. this.$$ChildScope = null;
  15615. }
  15616. ChildScope.prototype = parent;
  15617. return ChildScope;
  15618. }
  15619. this.$get = ['$exceptionHandler', '$parse', '$browser',
  15620. function($exceptionHandler, $parse, $browser) {
  15621. function destroyChildScope($event) {
  15622. $event.currentScope.$$destroyed = true;
  15623. }
  15624. function cleanUpScope($scope) {
  15625. // Support: IE 9 only
  15626. if (msie === 9) {
  15627. // There is a memory leak in IE9 if all child scopes are not disconnected
  15628. // completely when a scope is destroyed. So this code will recurse up through
  15629. // all this scopes children
  15630. //
  15631. // See issue https://github.com/angular/angular.js/issues/10706
  15632. if ($scope.$$childHead) {
  15633. cleanUpScope($scope.$$childHead);
  15634. }
  15635. if ($scope.$$nextSibling) {
  15636. cleanUpScope($scope.$$nextSibling);
  15637. }
  15638. }
  15639. // The code below works around IE9 and V8's memory leaks
  15640. //
  15641. // See:
  15642. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  15643. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  15644. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  15645. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  15646. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  15647. }
  15648. /**
  15649. * @ngdoc type
  15650. * @name $rootScope.Scope
  15651. *
  15652. * @description
  15653. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  15654. * {@link auto.$injector $injector}. Child scopes are created using the
  15655. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  15656. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  15657. * an in-depth introduction and usage examples.
  15658. *
  15659. *
  15660. * # Inheritance
  15661. * A scope can inherit from a parent scope, as in this example:
  15662. * ```js
  15663. var parent = $rootScope;
  15664. var child = parent.$new();
  15665. parent.salutation = "Hello";
  15666. expect(child.salutation).toEqual('Hello');
  15667. child.salutation = "Welcome";
  15668. expect(child.salutation).toEqual('Welcome');
  15669. expect(parent.salutation).toEqual('Hello');
  15670. * ```
  15671. *
  15672. * When interacting with `Scope` in tests, additional helper methods are available on the
  15673. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  15674. * details.
  15675. *
  15676. *
  15677. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  15678. * provided for the current scope. Defaults to {@link ng}.
  15679. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  15680. * append/override services provided by `providers`. This is handy
  15681. * when unit-testing and having the need to override a default
  15682. * service.
  15683. * @returns {Object} Newly created scope.
  15684. *
  15685. */
  15686. function Scope() {
  15687. this.$id = nextUid();
  15688. this.$$phase = this.$parent = this.$$watchers =
  15689. this.$$nextSibling = this.$$prevSibling =
  15690. this.$$childHead = this.$$childTail = null;
  15691. this.$root = this;
  15692. this.$$destroyed = false;
  15693. this.$$listeners = {};
  15694. this.$$listenerCount = {};
  15695. this.$$watchersCount = 0;
  15696. this.$$isolateBindings = null;
  15697. }
  15698. /**
  15699. * @ngdoc property
  15700. * @name $rootScope.Scope#$id
  15701. *
  15702. * @description
  15703. * Unique scope ID (monotonically increasing) useful for debugging.
  15704. */
  15705. /**
  15706. * @ngdoc property
  15707. * @name $rootScope.Scope#$parent
  15708. *
  15709. * @description
  15710. * Reference to the parent scope.
  15711. */
  15712. /**
  15713. * @ngdoc property
  15714. * @name $rootScope.Scope#$root
  15715. *
  15716. * @description
  15717. * Reference to the root scope.
  15718. */
  15719. Scope.prototype = {
  15720. constructor: Scope,
  15721. /**
  15722. * @ngdoc method
  15723. * @name $rootScope.Scope#$new
  15724. * @kind function
  15725. *
  15726. * @description
  15727. * Creates a new child {@link ng.$rootScope.Scope scope}.
  15728. *
  15729. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  15730. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  15731. *
  15732. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  15733. * desired for the scope and its child scopes to be permanently detached from the parent and
  15734. * thus stop participating in model change detection and listener notification by invoking.
  15735. *
  15736. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  15737. * parent scope. The scope is isolated, as it can not see parent scope properties.
  15738. * When creating widgets, it is useful for the widget to not accidentally read parent
  15739. * state.
  15740. *
  15741. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  15742. * of the newly created scope. Defaults to `this` scope if not provided.
  15743. * This is used when creating a transclude scope to correctly place it
  15744. * in the scope hierarchy while maintaining the correct prototypical
  15745. * inheritance.
  15746. *
  15747. * @returns {Object} The newly created child scope.
  15748. *
  15749. */
  15750. $new: function(isolate, parent) {
  15751. var child;
  15752. parent = parent || this;
  15753. if (isolate) {
  15754. child = new Scope();
  15755. child.$root = this.$root;
  15756. } else {
  15757. // Only create a child scope class if somebody asks for one,
  15758. // but cache it to allow the VM to optimize lookups.
  15759. if (!this.$$ChildScope) {
  15760. this.$$ChildScope = createChildScopeClass(this);
  15761. }
  15762. child = new this.$$ChildScope();
  15763. }
  15764. child.$parent = parent;
  15765. child.$$prevSibling = parent.$$childTail;
  15766. if (parent.$$childHead) {
  15767. parent.$$childTail.$$nextSibling = child;
  15768. parent.$$childTail = child;
  15769. } else {
  15770. parent.$$childHead = parent.$$childTail = child;
  15771. }
  15772. // When the new scope is not isolated or we inherit from `this`, and
  15773. // the parent scope is destroyed, the property `$$destroyed` is inherited
  15774. // prototypically. In all other cases, this property needs to be set
  15775. // when the parent scope is destroyed.
  15776. // The listener needs to be added after the parent is set
  15777. if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
  15778. return child;
  15779. },
  15780. /**
  15781. * @ngdoc method
  15782. * @name $rootScope.Scope#$watch
  15783. * @kind function
  15784. *
  15785. * @description
  15786. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  15787. *
  15788. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  15789. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  15790. * its value when executed multiple times with the same input because it may be executed multiple
  15791. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  15792. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
  15793. * - The `listener` is called only when the value from the current `watchExpression` and the
  15794. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  15795. * see below). Inequality is determined according to reference inequality,
  15796. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  15797. * via the `!==` Javascript operator, unless `objectEquality == true`
  15798. * (see next point)
  15799. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  15800. * according to the {@link angular.equals} function. To save the value of the object for
  15801. * later comparison, the {@link angular.copy} function is used. This therefore means that
  15802. * watching complex objects will have adverse memory and performance implications.
  15803. * - This should not be used to watch for changes in objects that are
  15804. * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.
  15805. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  15806. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  15807. * iteration limit is 10 to prevent an infinite loop deadlock.
  15808. *
  15809. *
  15810. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  15811. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  15812. * multiple calls to your `watchExpression` because it will execute multiple times in a
  15813. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  15814. *
  15815. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  15816. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  15817. * watcher. In rare cases, this is undesirable because the listener is called when the result
  15818. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  15819. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  15820. * listener was called due to initialization.
  15821. *
  15822. *
  15823. *
  15824. * # Example
  15825. * ```js
  15826. // let's assume that scope was dependency injected as the $rootScope
  15827. var scope = $rootScope;
  15828. scope.name = 'misko';
  15829. scope.counter = 0;
  15830. expect(scope.counter).toEqual(0);
  15831. scope.$watch('name', function(newValue, oldValue) {
  15832. scope.counter = scope.counter + 1;
  15833. });
  15834. expect(scope.counter).toEqual(0);
  15835. scope.$digest();
  15836. // the listener is always called during the first $digest loop after it was registered
  15837. expect(scope.counter).toEqual(1);
  15838. scope.$digest();
  15839. // but now it will not be called unless the value changes
  15840. expect(scope.counter).toEqual(1);
  15841. scope.name = 'adam';
  15842. scope.$digest();
  15843. expect(scope.counter).toEqual(2);
  15844. // Using a function as a watchExpression
  15845. var food;
  15846. scope.foodCounter = 0;
  15847. expect(scope.foodCounter).toEqual(0);
  15848. scope.$watch(
  15849. // This function returns the value being watched. It is called for each turn of the $digest loop
  15850. function() { return food; },
  15851. // This is the change listener, called when the value returned from the above function changes
  15852. function(newValue, oldValue) {
  15853. if ( newValue !== oldValue ) {
  15854. // Only increment the counter if the value changed
  15855. scope.foodCounter = scope.foodCounter + 1;
  15856. }
  15857. }
  15858. );
  15859. // No digest has been run so the counter will be zero
  15860. expect(scope.foodCounter).toEqual(0);
  15861. // Run the digest but since food has not changed count will still be zero
  15862. scope.$digest();
  15863. expect(scope.foodCounter).toEqual(0);
  15864. // Update food and run digest. Now the counter will increment
  15865. food = 'cheeseburger';
  15866. scope.$digest();
  15867. expect(scope.foodCounter).toEqual(1);
  15868. * ```
  15869. *
  15870. *
  15871. *
  15872. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  15873. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  15874. * a call to the `listener`.
  15875. *
  15876. * - `string`: Evaluated as {@link guide/expression expression}
  15877. * - `function(scope)`: called with current `scope` as a parameter.
  15878. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  15879. * of `watchExpression` changes.
  15880. *
  15881. * - `newVal` contains the current value of the `watchExpression`
  15882. * - `oldVal` contains the previous value of the `watchExpression`
  15883. * - `scope` refers to the current scope
  15884. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  15885. * comparing for reference equality.
  15886. * @returns {function()} Returns a deregistration function for this listener.
  15887. */
  15888. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  15889. var get = $parse(watchExp);
  15890. if (get.$$watchDelegate) {
  15891. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  15892. }
  15893. var scope = this,
  15894. array = scope.$$watchers,
  15895. watcher = {
  15896. fn: listener,
  15897. last: initWatchVal,
  15898. get: get,
  15899. exp: prettyPrintExpression || watchExp,
  15900. eq: !!objectEquality
  15901. };
  15902. lastDirtyWatch = null;
  15903. if (!isFunction(listener)) {
  15904. watcher.fn = noop;
  15905. }
  15906. if (!array) {
  15907. array = scope.$$watchers = [];
  15908. array.$$digestWatchIndex = -1;
  15909. }
  15910. // we use unshift since we use a while loop in $digest for speed.
  15911. // the while loop reads in reverse order.
  15912. array.unshift(watcher);
  15913. array.$$digestWatchIndex++;
  15914. incrementWatchersCount(this, 1);
  15915. return function deregisterWatch() {
  15916. var index = arrayRemove(array, watcher);
  15917. if (index >= 0) {
  15918. incrementWatchersCount(scope, -1);
  15919. if (index < array.$$digestWatchIndex) {
  15920. array.$$digestWatchIndex--;
  15921. }
  15922. }
  15923. lastDirtyWatch = null;
  15924. };
  15925. },
  15926. /**
  15927. * @ngdoc method
  15928. * @name $rootScope.Scope#$watchGroup
  15929. * @kind function
  15930. *
  15931. * @description
  15932. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  15933. * If any one expression in the collection changes the `listener` is executed.
  15934. *
  15935. * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
  15936. * values are examined for changes on every call to `$digest`.
  15937. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  15938. *
  15939. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  15940. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  15941. *
  15942. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  15943. * expression in `watchExpressions` changes
  15944. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  15945. * those of `watchExpression`
  15946. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  15947. * those of `watchExpression`
  15948. * The `scope` refers to the current scope.
  15949. * @returns {function()} Returns a de-registration function for all listeners.
  15950. */
  15951. $watchGroup: function(watchExpressions, listener) {
  15952. var oldValues = new Array(watchExpressions.length);
  15953. var newValues = new Array(watchExpressions.length);
  15954. var deregisterFns = [];
  15955. var self = this;
  15956. var changeReactionScheduled = false;
  15957. var firstRun = true;
  15958. if (!watchExpressions.length) {
  15959. // No expressions means we call the listener ASAP
  15960. var shouldCall = true;
  15961. self.$evalAsync(function() {
  15962. if (shouldCall) listener(newValues, newValues, self);
  15963. });
  15964. return function deregisterWatchGroup() {
  15965. shouldCall = false;
  15966. };
  15967. }
  15968. if (watchExpressions.length === 1) {
  15969. // Special case size of one
  15970. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  15971. newValues[0] = value;
  15972. oldValues[0] = oldValue;
  15973. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  15974. });
  15975. }
  15976. forEach(watchExpressions, function(expr, i) {
  15977. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  15978. newValues[i] = value;
  15979. oldValues[i] = oldValue;
  15980. if (!changeReactionScheduled) {
  15981. changeReactionScheduled = true;
  15982. self.$evalAsync(watchGroupAction);
  15983. }
  15984. });
  15985. deregisterFns.push(unwatchFn);
  15986. });
  15987. function watchGroupAction() {
  15988. changeReactionScheduled = false;
  15989. if (firstRun) {
  15990. firstRun = false;
  15991. listener(newValues, newValues, self);
  15992. } else {
  15993. listener(newValues, oldValues, self);
  15994. }
  15995. }
  15996. return function deregisterWatchGroup() {
  15997. while (deregisterFns.length) {
  15998. deregisterFns.shift()();
  15999. }
  16000. };
  16001. },
  16002. /**
  16003. * @ngdoc method
  16004. * @name $rootScope.Scope#$watchCollection
  16005. * @kind function
  16006. *
  16007. * @description
  16008. * Shallow watches the properties of an object and fires whenever any of the properties change
  16009. * (for arrays, this implies watching the array items; for object maps, this implies watching
  16010. * the properties). If a change is detected, the `listener` callback is fired.
  16011. *
  16012. * - The `obj` collection is observed via standard $watch operation and is examined on every
  16013. * call to $digest() to see if any items have been added, removed, or moved.
  16014. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  16015. * adding, removing, and moving items belonging to an object or array.
  16016. *
  16017. *
  16018. * # Example
  16019. * ```js
  16020. $scope.names = ['igor', 'matias', 'misko', 'james'];
  16021. $scope.dataCount = 4;
  16022. $scope.$watchCollection('names', function(newNames, oldNames) {
  16023. $scope.dataCount = newNames.length;
  16024. });
  16025. expect($scope.dataCount).toEqual(4);
  16026. $scope.$digest();
  16027. //still at 4 ... no changes
  16028. expect($scope.dataCount).toEqual(4);
  16029. $scope.names.pop();
  16030. $scope.$digest();
  16031. //now there's been a change
  16032. expect($scope.dataCount).toEqual(3);
  16033. * ```
  16034. *
  16035. *
  16036. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  16037. * expression value should evaluate to an object or an array which is observed on each
  16038. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  16039. * collection will trigger a call to the `listener`.
  16040. *
  16041. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  16042. * when a change is detected.
  16043. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  16044. * - The `oldCollection` object is a copy of the former collection data.
  16045. * Due to performance considerations, the`oldCollection` value is computed only if the
  16046. * `listener` function declares two or more arguments.
  16047. * - The `scope` argument refers to the current scope.
  16048. *
  16049. * @returns {function()} Returns a de-registration function for this listener. When the
  16050. * de-registration function is executed, the internal watch operation is terminated.
  16051. */
  16052. $watchCollection: function(obj, listener) {
  16053. $watchCollectionInterceptor.$stateful = true;
  16054. var self = this;
  16055. // the current value, updated on each dirty-check run
  16056. var newValue;
  16057. // a shallow copy of the newValue from the last dirty-check run,
  16058. // updated to match newValue during dirty-check run
  16059. var oldValue;
  16060. // a shallow copy of the newValue from when the last change happened
  16061. var veryOldValue;
  16062. // only track veryOldValue if the listener is asking for it
  16063. var trackVeryOldValue = (listener.length > 1);
  16064. var changeDetected = 0;
  16065. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  16066. var internalArray = [];
  16067. var internalObject = {};
  16068. var initRun = true;
  16069. var oldLength = 0;
  16070. function $watchCollectionInterceptor(_value) {
  16071. newValue = _value;
  16072. var newLength, key, bothNaN, newItem, oldItem;
  16073. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  16074. if (isUndefined(newValue)) return;
  16075. if (!isObject(newValue)) { // if primitive
  16076. if (oldValue !== newValue) {
  16077. oldValue = newValue;
  16078. changeDetected++;
  16079. }
  16080. } else if (isArrayLike(newValue)) {
  16081. if (oldValue !== internalArray) {
  16082. // we are transitioning from something which was not an array into array.
  16083. oldValue = internalArray;
  16084. oldLength = oldValue.length = 0;
  16085. changeDetected++;
  16086. }
  16087. newLength = newValue.length;
  16088. if (oldLength !== newLength) {
  16089. // if lengths do not match we need to trigger change notification
  16090. changeDetected++;
  16091. oldValue.length = oldLength = newLength;
  16092. }
  16093. // copy the items to oldValue and look for changes.
  16094. for (var i = 0; i < newLength; i++) {
  16095. oldItem = oldValue[i];
  16096. newItem = newValue[i];
  16097. // eslint-disable-next-line no-self-compare
  16098. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16099. if (!bothNaN && (oldItem !== newItem)) {
  16100. changeDetected++;
  16101. oldValue[i] = newItem;
  16102. }
  16103. }
  16104. } else {
  16105. if (oldValue !== internalObject) {
  16106. // we are transitioning from something which was not an object into object.
  16107. oldValue = internalObject = {};
  16108. oldLength = 0;
  16109. changeDetected++;
  16110. }
  16111. // copy the items to oldValue and look for changes.
  16112. newLength = 0;
  16113. for (key in newValue) {
  16114. if (hasOwnProperty.call(newValue, key)) {
  16115. newLength++;
  16116. newItem = newValue[key];
  16117. oldItem = oldValue[key];
  16118. if (key in oldValue) {
  16119. // eslint-disable-next-line no-self-compare
  16120. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16121. if (!bothNaN && (oldItem !== newItem)) {
  16122. changeDetected++;
  16123. oldValue[key] = newItem;
  16124. }
  16125. } else {
  16126. oldLength++;
  16127. oldValue[key] = newItem;
  16128. changeDetected++;
  16129. }
  16130. }
  16131. }
  16132. if (oldLength > newLength) {
  16133. // we used to have more keys, need to find them and destroy them.
  16134. changeDetected++;
  16135. for (key in oldValue) {
  16136. if (!hasOwnProperty.call(newValue, key)) {
  16137. oldLength--;
  16138. delete oldValue[key];
  16139. }
  16140. }
  16141. }
  16142. }
  16143. return changeDetected;
  16144. }
  16145. function $watchCollectionAction() {
  16146. if (initRun) {
  16147. initRun = false;
  16148. listener(newValue, newValue, self);
  16149. } else {
  16150. listener(newValue, veryOldValue, self);
  16151. }
  16152. // make a copy for the next time a collection is changed
  16153. if (trackVeryOldValue) {
  16154. if (!isObject(newValue)) {
  16155. //primitive
  16156. veryOldValue = newValue;
  16157. } else if (isArrayLike(newValue)) {
  16158. veryOldValue = new Array(newValue.length);
  16159. for (var i = 0; i < newValue.length; i++) {
  16160. veryOldValue[i] = newValue[i];
  16161. }
  16162. } else { // if object
  16163. veryOldValue = {};
  16164. for (var key in newValue) {
  16165. if (hasOwnProperty.call(newValue, key)) {
  16166. veryOldValue[key] = newValue[key];
  16167. }
  16168. }
  16169. }
  16170. }
  16171. }
  16172. return this.$watch(changeDetector, $watchCollectionAction);
  16173. },
  16174. /**
  16175. * @ngdoc method
  16176. * @name $rootScope.Scope#$digest
  16177. * @kind function
  16178. *
  16179. * @description
  16180. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  16181. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  16182. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  16183. * until no more listeners are firing. This means that it is possible to get into an infinite
  16184. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  16185. * iterations exceeds 10.
  16186. *
  16187. * Usually, you don't call `$digest()` directly in
  16188. * {@link ng.directive:ngController controllers} or in
  16189. * {@link ng.$compileProvider#directive directives}.
  16190. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  16191. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  16192. *
  16193. * If you want to be notified whenever `$digest()` is called,
  16194. * you can register a `watchExpression` function with
  16195. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  16196. *
  16197. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  16198. *
  16199. * # Example
  16200. * ```js
  16201. var scope = ...;
  16202. scope.name = 'misko';
  16203. scope.counter = 0;
  16204. expect(scope.counter).toEqual(0);
  16205. scope.$watch('name', function(newValue, oldValue) {
  16206. scope.counter = scope.counter + 1;
  16207. });
  16208. expect(scope.counter).toEqual(0);
  16209. scope.$digest();
  16210. // the listener is always called during the first $digest loop after it was registered
  16211. expect(scope.counter).toEqual(1);
  16212. scope.$digest();
  16213. // but now it will not be called unless the value changes
  16214. expect(scope.counter).toEqual(1);
  16215. scope.name = 'adam';
  16216. scope.$digest();
  16217. expect(scope.counter).toEqual(2);
  16218. * ```
  16219. *
  16220. */
  16221. $digest: function() {
  16222. var watch, value, last, fn, get,
  16223. watchers,
  16224. dirty, ttl = TTL,
  16225. next, current, target = this,
  16226. watchLog = [],
  16227. logIdx, asyncTask;
  16228. beginPhase('$digest');
  16229. // Check for changes to browser url that happened in sync before the call to $digest
  16230. $browser.$$checkUrlChange();
  16231. if (this === $rootScope && applyAsyncId !== null) {
  16232. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  16233. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  16234. $browser.defer.cancel(applyAsyncId);
  16235. flushApplyAsync();
  16236. }
  16237. lastDirtyWatch = null;
  16238. do { // "while dirty" loop
  16239. dirty = false;
  16240. current = target;
  16241. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  16242. // be reentered recursively. Calling $digest from a function passed to $evalAsync would
  16243. // lead to a '$digest already in progress' error.
  16244. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  16245. try {
  16246. asyncTask = asyncQueue[asyncQueuePosition];
  16247. fn = asyncTask.fn;
  16248. fn(asyncTask.scope, asyncTask.locals);
  16249. } catch (e) {
  16250. $exceptionHandler(e);
  16251. }
  16252. lastDirtyWatch = null;
  16253. }
  16254. asyncQueue.length = 0;
  16255. traverseScopesLoop:
  16256. do { // "traverse the scopes" loop
  16257. if ((watchers = current.$$watchers)) {
  16258. // process our watches
  16259. watchers.$$digestWatchIndex = watchers.length;
  16260. while (watchers.$$digestWatchIndex--) {
  16261. try {
  16262. watch = watchers[watchers.$$digestWatchIndex];
  16263. // Most common watches are on primitives, in which case we can short
  16264. // circuit it with === operator, only when === fails do we use .equals
  16265. if (watch) {
  16266. get = watch.get;
  16267. if ((value = get(current)) !== (last = watch.last) &&
  16268. !(watch.eq
  16269. ? equals(value, last)
  16270. : (isNumberNaN(value) && isNumberNaN(last)))) {
  16271. dirty = true;
  16272. lastDirtyWatch = watch;
  16273. watch.last = watch.eq ? copy(value, null) : value;
  16274. fn = watch.fn;
  16275. fn(value, ((last === initWatchVal) ? value : last), current);
  16276. if (ttl < 5) {
  16277. logIdx = 4 - ttl;
  16278. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  16279. watchLog[logIdx].push({
  16280. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  16281. newVal: value,
  16282. oldVal: last
  16283. });
  16284. }
  16285. } else if (watch === lastDirtyWatch) {
  16286. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  16287. // have already been tested.
  16288. dirty = false;
  16289. break traverseScopesLoop;
  16290. }
  16291. }
  16292. } catch (e) {
  16293. $exceptionHandler(e);
  16294. }
  16295. }
  16296. }
  16297. // Insanity Warning: scope depth-first traversal
  16298. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16299. // this piece should be kept in sync with the traversal in $broadcast
  16300. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  16301. (current !== target && current.$$nextSibling)))) {
  16302. while (current !== target && !(next = current.$$nextSibling)) {
  16303. current = current.$parent;
  16304. }
  16305. }
  16306. } while ((current = next));
  16307. // `break traverseScopesLoop;` takes us to here
  16308. if ((dirty || asyncQueue.length) && !(ttl--)) {
  16309. clearPhase();
  16310. throw $rootScopeMinErr('infdig',
  16311. '{0} $digest() iterations reached. Aborting!\n' +
  16312. 'Watchers fired in the last 5 iterations: {1}',
  16313. TTL, watchLog);
  16314. }
  16315. } while (dirty || asyncQueue.length);
  16316. clearPhase();
  16317. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  16318. while (postDigestQueuePosition < postDigestQueue.length) {
  16319. try {
  16320. postDigestQueue[postDigestQueuePosition++]();
  16321. } catch (e) {
  16322. $exceptionHandler(e);
  16323. }
  16324. }
  16325. postDigestQueue.length = postDigestQueuePosition = 0;
  16326. // Check for changes to browser url that happened during the $digest
  16327. // (for which no event is fired; e.g. via `history.pushState()`)
  16328. $browser.$$checkUrlChange();
  16329. },
  16330. /**
  16331. * @ngdoc event
  16332. * @name $rootScope.Scope#$destroy
  16333. * @eventType broadcast on scope being destroyed
  16334. *
  16335. * @description
  16336. * Broadcasted when a scope and its children are being destroyed.
  16337. *
  16338. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16339. * clean up DOM bindings before an element is removed from the DOM.
  16340. */
  16341. /**
  16342. * @ngdoc method
  16343. * @name $rootScope.Scope#$destroy
  16344. * @kind function
  16345. *
  16346. * @description
  16347. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  16348. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  16349. * propagate to the current scope and its children. Removal also implies that the current
  16350. * scope is eligible for garbage collection.
  16351. *
  16352. * The `$destroy()` is usually used by directives such as
  16353. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  16354. * unrolling of the loop.
  16355. *
  16356. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  16357. * Application code can register a `$destroy` event handler that will give it a chance to
  16358. * perform any necessary cleanup.
  16359. *
  16360. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16361. * clean up DOM bindings before an element is removed from the DOM.
  16362. */
  16363. $destroy: function() {
  16364. // We can't destroy a scope that has been already destroyed.
  16365. if (this.$$destroyed) return;
  16366. var parent = this.$parent;
  16367. this.$broadcast('$destroy');
  16368. this.$$destroyed = true;
  16369. if (this === $rootScope) {
  16370. //Remove handlers attached to window when $rootScope is removed
  16371. $browser.$$applicationDestroyed();
  16372. }
  16373. incrementWatchersCount(this, -this.$$watchersCount);
  16374. for (var eventName in this.$$listenerCount) {
  16375. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  16376. }
  16377. // sever all the references to parent scopes (after this cleanup, the current scope should
  16378. // not be retained by any of our references and should be eligible for garbage collection)
  16379. if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
  16380. if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
  16381. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  16382. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  16383. // Disable listeners, watchers and apply/digest methods
  16384. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  16385. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  16386. this.$$listeners = {};
  16387. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  16388. this.$$nextSibling = null;
  16389. cleanUpScope(this);
  16390. },
  16391. /**
  16392. * @ngdoc method
  16393. * @name $rootScope.Scope#$eval
  16394. * @kind function
  16395. *
  16396. * @description
  16397. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  16398. * the expression are propagated (uncaught). This is useful when evaluating Angular
  16399. * expressions.
  16400. *
  16401. * # Example
  16402. * ```js
  16403. var scope = ng.$rootScope.Scope();
  16404. scope.a = 1;
  16405. scope.b = 2;
  16406. expect(scope.$eval('a+b')).toEqual(3);
  16407. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  16408. * ```
  16409. *
  16410. * @param {(string|function())=} expression An angular expression to be executed.
  16411. *
  16412. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16413. * - `function(scope)`: execute the function with the current `scope` parameter.
  16414. *
  16415. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16416. * @returns {*} The result of evaluating the expression.
  16417. */
  16418. $eval: function(expr, locals) {
  16419. return $parse(expr)(this, locals);
  16420. },
  16421. /**
  16422. * @ngdoc method
  16423. * @name $rootScope.Scope#$evalAsync
  16424. * @kind function
  16425. *
  16426. * @description
  16427. * Executes the expression on the current scope at a later point in time.
  16428. *
  16429. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  16430. * that:
  16431. *
  16432. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  16433. * rendering).
  16434. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  16435. * `expression` execution.
  16436. *
  16437. * Any exceptions from the execution of the expression are forwarded to the
  16438. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16439. *
  16440. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  16441. * will be scheduled. However, it is encouraged to always call code that changes the model
  16442. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  16443. *
  16444. * @param {(string|function())=} expression An angular expression to be executed.
  16445. *
  16446. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16447. * - `function(scope)`: execute the function with the current `scope` parameter.
  16448. *
  16449. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16450. */
  16451. $evalAsync: function(expr, locals) {
  16452. // if we are outside of an $digest loop and this is the first time we are scheduling async
  16453. // task also schedule async auto-flush
  16454. if (!$rootScope.$$phase && !asyncQueue.length) {
  16455. $browser.defer(function() {
  16456. if (asyncQueue.length) {
  16457. $rootScope.$digest();
  16458. }
  16459. });
  16460. }
  16461. asyncQueue.push({scope: this, fn: $parse(expr), locals: locals});
  16462. },
  16463. $$postDigest: function(fn) {
  16464. postDigestQueue.push(fn);
  16465. },
  16466. /**
  16467. * @ngdoc method
  16468. * @name $rootScope.Scope#$apply
  16469. * @kind function
  16470. *
  16471. * @description
  16472. * `$apply()` is used to execute an expression in angular from outside of the angular
  16473. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  16474. * Because we are calling into the angular framework we need to perform proper scope life
  16475. * cycle of {@link ng.$exceptionHandler exception handling},
  16476. * {@link ng.$rootScope.Scope#$digest executing watches}.
  16477. *
  16478. * ## Life cycle
  16479. *
  16480. * # Pseudo-Code of `$apply()`
  16481. * ```js
  16482. function $apply(expr) {
  16483. try {
  16484. return $eval(expr);
  16485. } catch (e) {
  16486. $exceptionHandler(e);
  16487. } finally {
  16488. $root.$digest();
  16489. }
  16490. }
  16491. * ```
  16492. *
  16493. *
  16494. * Scope's `$apply()` method transitions through the following stages:
  16495. *
  16496. * 1. The {@link guide/expression expression} is executed using the
  16497. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  16498. * 2. Any exceptions from the execution of the expression are forwarded to the
  16499. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16500. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  16501. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  16502. *
  16503. *
  16504. * @param {(string|function())=} exp An angular expression to be executed.
  16505. *
  16506. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16507. * - `function(scope)`: execute the function with current `scope` parameter.
  16508. *
  16509. * @returns {*} The result of evaluating the expression.
  16510. */
  16511. $apply: function(expr) {
  16512. try {
  16513. beginPhase('$apply');
  16514. try {
  16515. return this.$eval(expr);
  16516. } finally {
  16517. clearPhase();
  16518. }
  16519. } catch (e) {
  16520. $exceptionHandler(e);
  16521. } finally {
  16522. try {
  16523. $rootScope.$digest();
  16524. } catch (e) {
  16525. $exceptionHandler(e);
  16526. // eslint-disable-next-line no-unsafe-finally
  16527. throw e;
  16528. }
  16529. }
  16530. },
  16531. /**
  16532. * @ngdoc method
  16533. * @name $rootScope.Scope#$applyAsync
  16534. * @kind function
  16535. *
  16536. * @description
  16537. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  16538. * varies across browsers, but is typically around ~10 milliseconds.
  16539. *
  16540. * This can be used to queue up multiple expressions which need to be evaluated in the same
  16541. * digest.
  16542. *
  16543. * @param {(string|function())=} exp An angular expression to be executed.
  16544. *
  16545. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16546. * - `function(scope)`: execute the function with current `scope` parameter.
  16547. */
  16548. $applyAsync: function(expr) {
  16549. var scope = this;
  16550. if (expr) {
  16551. applyAsyncQueue.push($applyAsyncExpression);
  16552. }
  16553. expr = $parse(expr);
  16554. scheduleApplyAsync();
  16555. function $applyAsyncExpression() {
  16556. scope.$eval(expr);
  16557. }
  16558. },
  16559. /**
  16560. * @ngdoc method
  16561. * @name $rootScope.Scope#$on
  16562. * @kind function
  16563. *
  16564. * @description
  16565. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  16566. * discussion of event life cycle.
  16567. *
  16568. * The event listener function format is: `function(event, args...)`. The `event` object
  16569. * passed into the listener has the following attributes:
  16570. *
  16571. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  16572. * `$broadcast`-ed.
  16573. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  16574. * event propagates through the scope hierarchy, this property is set to null.
  16575. * - `name` - `{string}`: name of the event.
  16576. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  16577. * further event propagation (available only for events that were `$emit`-ed).
  16578. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  16579. * to true.
  16580. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  16581. *
  16582. * @param {string} name Event name to listen on.
  16583. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  16584. * @returns {function()} Returns a deregistration function for this listener.
  16585. */
  16586. $on: function(name, listener) {
  16587. var namedListeners = this.$$listeners[name];
  16588. if (!namedListeners) {
  16589. this.$$listeners[name] = namedListeners = [];
  16590. }
  16591. namedListeners.push(listener);
  16592. var current = this;
  16593. do {
  16594. if (!current.$$listenerCount[name]) {
  16595. current.$$listenerCount[name] = 0;
  16596. }
  16597. current.$$listenerCount[name]++;
  16598. } while ((current = current.$parent));
  16599. var self = this;
  16600. return function() {
  16601. var indexOfListener = namedListeners.indexOf(listener);
  16602. if (indexOfListener !== -1) {
  16603. namedListeners[indexOfListener] = null;
  16604. decrementListenerCount(self, 1, name);
  16605. }
  16606. };
  16607. },
  16608. /**
  16609. * @ngdoc method
  16610. * @name $rootScope.Scope#$emit
  16611. * @kind function
  16612. *
  16613. * @description
  16614. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  16615. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16616. *
  16617. * The event life cycle starts at the scope on which `$emit` was called. All
  16618. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16619. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  16620. * registered listeners along the way. The event will stop propagating if one of the listeners
  16621. * cancels it.
  16622. *
  16623. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16624. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16625. *
  16626. * @param {string} name Event name to emit.
  16627. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16628. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  16629. */
  16630. $emit: function(name, args) {
  16631. var empty = [],
  16632. namedListeners,
  16633. scope = this,
  16634. stopPropagation = false,
  16635. event = {
  16636. name: name,
  16637. targetScope: scope,
  16638. stopPropagation: function() {stopPropagation = true;},
  16639. preventDefault: function() {
  16640. event.defaultPrevented = true;
  16641. },
  16642. defaultPrevented: false
  16643. },
  16644. listenerArgs = concat([event], arguments, 1),
  16645. i, length;
  16646. do {
  16647. namedListeners = scope.$$listeners[name] || empty;
  16648. event.currentScope = scope;
  16649. for (i = 0, length = namedListeners.length; i < length; i++) {
  16650. // if listeners were deregistered, defragment the array
  16651. if (!namedListeners[i]) {
  16652. namedListeners.splice(i, 1);
  16653. i--;
  16654. length--;
  16655. continue;
  16656. }
  16657. try {
  16658. //allow all listeners attached to the current scope to run
  16659. namedListeners[i].apply(null, listenerArgs);
  16660. } catch (e) {
  16661. $exceptionHandler(e);
  16662. }
  16663. }
  16664. //if any listener on the current scope stops propagation, prevent bubbling
  16665. if (stopPropagation) {
  16666. event.currentScope = null;
  16667. return event;
  16668. }
  16669. //traverse upwards
  16670. scope = scope.$parent;
  16671. } while (scope);
  16672. event.currentScope = null;
  16673. return event;
  16674. },
  16675. /**
  16676. * @ngdoc method
  16677. * @name $rootScope.Scope#$broadcast
  16678. * @kind function
  16679. *
  16680. * @description
  16681. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  16682. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16683. *
  16684. * The event life cycle starts at the scope on which `$broadcast` was called. All
  16685. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16686. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  16687. * scope and calls all registered listeners along the way. The event cannot be canceled.
  16688. *
  16689. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16690. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16691. *
  16692. * @param {string} name Event name to broadcast.
  16693. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16694. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  16695. */
  16696. $broadcast: function(name, args) {
  16697. var target = this,
  16698. current = target,
  16699. next = target,
  16700. event = {
  16701. name: name,
  16702. targetScope: target,
  16703. preventDefault: function() {
  16704. event.defaultPrevented = true;
  16705. },
  16706. defaultPrevented: false
  16707. };
  16708. if (!target.$$listenerCount[name]) return event;
  16709. var listenerArgs = concat([event], arguments, 1),
  16710. listeners, i, length;
  16711. //down while you can, then up and next sibling or up and next sibling until back at root
  16712. while ((current = next)) {
  16713. event.currentScope = current;
  16714. listeners = current.$$listeners[name] || [];
  16715. for (i = 0, length = listeners.length; i < length; i++) {
  16716. // if listeners were deregistered, defragment the array
  16717. if (!listeners[i]) {
  16718. listeners.splice(i, 1);
  16719. i--;
  16720. length--;
  16721. continue;
  16722. }
  16723. try {
  16724. listeners[i].apply(null, listenerArgs);
  16725. } catch (e) {
  16726. $exceptionHandler(e);
  16727. }
  16728. }
  16729. // Insanity Warning: scope depth-first traversal
  16730. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16731. // this piece should be kept in sync with the traversal in $digest
  16732. // (though it differs due to having the extra check for $$listenerCount)
  16733. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  16734. (current !== target && current.$$nextSibling)))) {
  16735. while (current !== target && !(next = current.$$nextSibling)) {
  16736. current = current.$parent;
  16737. }
  16738. }
  16739. }
  16740. event.currentScope = null;
  16741. return event;
  16742. }
  16743. };
  16744. var $rootScope = new Scope();
  16745. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  16746. var asyncQueue = $rootScope.$$asyncQueue = [];
  16747. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  16748. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  16749. var postDigestQueuePosition = 0;
  16750. return $rootScope;
  16751. function beginPhase(phase) {
  16752. if ($rootScope.$$phase) {
  16753. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  16754. }
  16755. $rootScope.$$phase = phase;
  16756. }
  16757. function clearPhase() {
  16758. $rootScope.$$phase = null;
  16759. }
  16760. function incrementWatchersCount(current, count) {
  16761. do {
  16762. current.$$watchersCount += count;
  16763. } while ((current = current.$parent));
  16764. }
  16765. function decrementListenerCount(current, count, name) {
  16766. do {
  16767. current.$$listenerCount[name] -= count;
  16768. if (current.$$listenerCount[name] === 0) {
  16769. delete current.$$listenerCount[name];
  16770. }
  16771. } while ((current = current.$parent));
  16772. }
  16773. /**
  16774. * function used as an initial value for watchers.
  16775. * because it's unique we can easily tell it apart from other values
  16776. */
  16777. function initWatchVal() {}
  16778. function flushApplyAsync() {
  16779. while (applyAsyncQueue.length) {
  16780. try {
  16781. applyAsyncQueue.shift()();
  16782. } catch (e) {
  16783. $exceptionHandler(e);
  16784. }
  16785. }
  16786. applyAsyncId = null;
  16787. }
  16788. function scheduleApplyAsync() {
  16789. if (applyAsyncId === null) {
  16790. applyAsyncId = $browser.defer(function() {
  16791. $rootScope.$apply(flushApplyAsync);
  16792. });
  16793. }
  16794. }
  16795. }];
  16796. }
  16797. /**
  16798. * @ngdoc service
  16799. * @name $rootElement
  16800. *
  16801. * @description
  16802. * The root element of Angular application. This is either the element where {@link
  16803. * ng.directive:ngApp ngApp} was declared or the element passed into
  16804. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  16805. * location where the application's {@link auto.$injector $injector} service gets
  16806. * published, and can be retrieved using `$rootElement.injector()`.
  16807. */
  16808. // the implementation is in angular.bootstrap
  16809. /**
  16810. * @this
  16811. * @description
  16812. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  16813. */
  16814. function $$SanitizeUriProvider() {
  16815. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  16816. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  16817. /**
  16818. * @description
  16819. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16820. * urls during a[href] sanitization.
  16821. *
  16822. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16823. *
  16824. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  16825. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  16826. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16827. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16828. *
  16829. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16830. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16831. * chaining otherwise.
  16832. */
  16833. this.aHrefSanitizationWhitelist = function(regexp) {
  16834. if (isDefined(regexp)) {
  16835. aHrefSanitizationWhitelist = regexp;
  16836. return this;
  16837. }
  16838. return aHrefSanitizationWhitelist;
  16839. };
  16840. /**
  16841. * @description
  16842. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16843. * urls during img[src] sanitization.
  16844. *
  16845. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16846. *
  16847. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  16848. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  16849. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16850. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16851. *
  16852. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16853. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16854. * chaining otherwise.
  16855. */
  16856. this.imgSrcSanitizationWhitelist = function(regexp) {
  16857. if (isDefined(regexp)) {
  16858. imgSrcSanitizationWhitelist = regexp;
  16859. return this;
  16860. }
  16861. return imgSrcSanitizationWhitelist;
  16862. };
  16863. this.$get = function() {
  16864. return function sanitizeUri(uri, isImage) {
  16865. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  16866. var normalizedVal;
  16867. normalizedVal = urlResolve(uri).href;
  16868. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  16869. return 'unsafe:' + normalizedVal;
  16870. }
  16871. return uri;
  16872. };
  16873. };
  16874. }
  16875. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  16876. * Any commits to this file should be reviewed with security in mind. *
  16877. * Changes to this file can potentially create security vulnerabilities. *
  16878. * An approval from 2 Core members with history of modifying *
  16879. * this file is required. *
  16880. * *
  16881. * Does the change somehow allow for arbitrary javascript to be executed? *
  16882. * Or allows for someone to change the prototype of built-in objects? *
  16883. * Or gives undesired access to variables likes document or window? *
  16884. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  16885. /* exported $SceProvider, $SceDelegateProvider */
  16886. var $sceMinErr = minErr('$sce');
  16887. var SCE_CONTEXTS = {
  16888. // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding).
  16889. HTML: 'html',
  16890. // Style statements or stylesheets. Currently unused in AngularJS.
  16891. CSS: 'css',
  16892. // An URL used in a context where it does not refer to a resource that loads code. Currently
  16893. // unused in AngularJS.
  16894. URL: 'url',
  16895. // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as
  16896. // code. (e.g. ng-include, script src binding, templateUrl)
  16897. RESOURCE_URL: 'resourceUrl',
  16898. // Script. Currently unused in AngularJS.
  16899. JS: 'js'
  16900. };
  16901. // Helper functions follow.
  16902. var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;
  16903. function snakeToCamel(name) {
  16904. return name
  16905. .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);
  16906. }
  16907. function adjustMatcher(matcher) {
  16908. if (matcher === 'self') {
  16909. return matcher;
  16910. } else if (isString(matcher)) {
  16911. // Strings match exactly except for 2 wildcards - '*' and '**'.
  16912. // '*' matches any character except those from the set ':/.?&'.
  16913. // '**' matches any character (like .* in a RegExp).
  16914. // More than 2 *'s raises an error as it's ill defined.
  16915. if (matcher.indexOf('***') > -1) {
  16916. throw $sceMinErr('iwcard',
  16917. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  16918. }
  16919. matcher = escapeForRegexp(matcher).
  16920. replace(/\\\*\\\*/g, '.*').
  16921. replace(/\\\*/g, '[^:/.?&;]*');
  16922. return new RegExp('^' + matcher + '$');
  16923. } else if (isRegExp(matcher)) {
  16924. // The only other type of matcher allowed is a Regexp.
  16925. // Match entire URL / disallow partial matches.
  16926. // Flags are reset (i.e. no global, ignoreCase or multiline)
  16927. return new RegExp('^' + matcher.source + '$');
  16928. } else {
  16929. throw $sceMinErr('imatcher',
  16930. 'Matchers may only be "self", string patterns or RegExp objects');
  16931. }
  16932. }
  16933. function adjustMatchers(matchers) {
  16934. var adjustedMatchers = [];
  16935. if (isDefined(matchers)) {
  16936. forEach(matchers, function(matcher) {
  16937. adjustedMatchers.push(adjustMatcher(matcher));
  16938. });
  16939. }
  16940. return adjustedMatchers;
  16941. }
  16942. /**
  16943. * @ngdoc service
  16944. * @name $sceDelegate
  16945. * @kind function
  16946. *
  16947. * @description
  16948. *
  16949. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  16950. * Contextual Escaping (SCE)} services to AngularJS.
  16951. *
  16952. * For an overview of this service and the functionnality it provides in AngularJS, see the main
  16953. * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how
  16954. * SCE works in their application, which shouldn't be needed in most cases.
  16955. *
  16956. * <div class="alert alert-danger">
  16957. * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or
  16958. * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners,
  16959. * changes to this service will also influence users, so be extra careful and document your changes.
  16960. * </div>
  16961. *
  16962. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  16963. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  16964. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  16965. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  16966. * work because `$sce` delegates to `$sceDelegate` for these operations.
  16967. *
  16968. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  16969. *
  16970. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  16971. * can override it completely to change the behavior of `$sce`, the common case would
  16972. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  16973. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  16974. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  16975. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  16976. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16977. */
  16978. /**
  16979. * @ngdoc provider
  16980. * @name $sceDelegateProvider
  16981. * @this
  16982. *
  16983. * @description
  16984. *
  16985. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  16986. * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}.
  16987. *
  16988. * The `$sceDelegateProvider` allows one to get/set the whitelists and blacklists used to ensure
  16989. * that the URLs used for sourcing AngularJS templates and other script-running URLs are safe (all
  16990. * places that use the `$sce.RESOURCE_URL` context). See
  16991. * {@link ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist}
  16992. * and
  16993. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist},
  16994. *
  16995. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  16996. * Strict Contextual Escaping (SCE)}.
  16997. *
  16998. * **Example**: Consider the following case. <a name="example"></a>
  16999. *
  17000. * - your app is hosted at url `http://myapp.example.com/`
  17001. * - but some of your templates are hosted on other domains you control such as
  17002. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  17003. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  17004. *
  17005. * Here is what a secure configuration for this scenario might look like:
  17006. *
  17007. * ```
  17008. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  17009. * $sceDelegateProvider.resourceUrlWhitelist([
  17010. * // Allow same origin resource loads.
  17011. * 'self',
  17012. * // Allow loading from our assets domain. Notice the difference between * and **.
  17013. * 'http://srv*.assets.example.com/**'
  17014. * ]);
  17015. *
  17016. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  17017. * $sceDelegateProvider.resourceUrlBlacklist([
  17018. * 'http://myapp.example.com/clickThru**'
  17019. * ]);
  17020. * });
  17021. * ```
  17022. * Note that an empty whitelist will block every resource URL from being loaded, and will require
  17023. * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates
  17024. * requested by {@link ng.$templateRequest $templateRequest} that are present in
  17025. * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism
  17026. * to populate your templates in that cache at config time, then it is a good idea to remove 'self'
  17027. * from that whitelist. This helps to mitigate the security impact of certain types of issues, like
  17028. * for instance attacker-controlled `ng-includes`.
  17029. */
  17030. function $SceDelegateProvider() {
  17031. this.SCE_CONTEXTS = SCE_CONTEXTS;
  17032. // Resource URLs can also be trusted by policy.
  17033. var resourceUrlWhitelist = ['self'],
  17034. resourceUrlBlacklist = [];
  17035. /**
  17036. * @ngdoc method
  17037. * @name $sceDelegateProvider#resourceUrlWhitelist
  17038. * @kind function
  17039. *
  17040. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  17041. * provided. This must be an array or null. A snapshot of this array is used so further
  17042. * changes to the array are ignored.
  17043. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  17044. * allowed in this array.
  17045. *
  17046. * @return {Array} The currently set whitelist array.
  17047. *
  17048. * @description
  17049. * Sets/Gets the whitelist of trusted resource URLs.
  17050. *
  17051. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  17052. * same origin resource requests.
  17053. *
  17054. * <div class="alert alert-warning">
  17055. * **Note:** the default whitelist of 'self' is not recommended if your app shares its origin
  17056. * with other apps! It is a good idea to limit it to only your application's directory.
  17057. * </div>
  17058. */
  17059. this.resourceUrlWhitelist = function(value) {
  17060. if (arguments.length) {
  17061. resourceUrlWhitelist = adjustMatchers(value);
  17062. }
  17063. return resourceUrlWhitelist;
  17064. };
  17065. /**
  17066. * @ngdoc method
  17067. * @name $sceDelegateProvider#resourceUrlBlacklist
  17068. * @kind function
  17069. *
  17070. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  17071. * provided. This must be an array or null. A snapshot of this array is used so further
  17072. * changes to the array are ignored.</p><p>
  17073. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  17074. * allowed in this array.</p><p>
  17075. * The typical usage for the blacklist is to **block
  17076. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  17077. * these would otherwise be trusted but actually return content from the redirected domain.
  17078. * </p><p>
  17079. * Finally, **the blacklist overrides the whitelist** and has the final say.
  17080. *
  17081. * @return {Array} The currently set blacklist array.
  17082. *
  17083. * @description
  17084. * Sets/Gets the blacklist of trusted resource URLs.
  17085. *
  17086. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  17087. * is no blacklist.)
  17088. */
  17089. this.resourceUrlBlacklist = function(value) {
  17090. if (arguments.length) {
  17091. resourceUrlBlacklist = adjustMatchers(value);
  17092. }
  17093. return resourceUrlBlacklist;
  17094. };
  17095. this.$get = ['$injector', function($injector) {
  17096. var htmlSanitizer = function htmlSanitizer(html) {
  17097. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17098. };
  17099. if ($injector.has('$sanitize')) {
  17100. htmlSanitizer = $injector.get('$sanitize');
  17101. }
  17102. function matchUrl(matcher, parsedUrl) {
  17103. if (matcher === 'self') {
  17104. return urlIsSameOrigin(parsedUrl);
  17105. } else {
  17106. // definitely a regex. See adjustMatchers()
  17107. return !!matcher.exec(parsedUrl.href);
  17108. }
  17109. }
  17110. function isResourceUrlAllowedByPolicy(url) {
  17111. var parsedUrl = urlResolve(url.toString());
  17112. var i, n, allowed = false;
  17113. // Ensure that at least one item from the whitelist allows this url.
  17114. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  17115. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  17116. allowed = true;
  17117. break;
  17118. }
  17119. }
  17120. if (allowed) {
  17121. // Ensure that no item from the blacklist blocked this url.
  17122. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  17123. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  17124. allowed = false;
  17125. break;
  17126. }
  17127. }
  17128. }
  17129. return allowed;
  17130. }
  17131. function generateHolderType(Base) {
  17132. var holderType = function TrustedValueHolderType(trustedValue) {
  17133. this.$$unwrapTrustedValue = function() {
  17134. return trustedValue;
  17135. };
  17136. };
  17137. if (Base) {
  17138. holderType.prototype = new Base();
  17139. }
  17140. holderType.prototype.valueOf = function sceValueOf() {
  17141. return this.$$unwrapTrustedValue();
  17142. };
  17143. holderType.prototype.toString = function sceToString() {
  17144. return this.$$unwrapTrustedValue().toString();
  17145. };
  17146. return holderType;
  17147. }
  17148. var trustedValueHolderBase = generateHolderType(),
  17149. byType = {};
  17150. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  17151. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  17152. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  17153. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  17154. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  17155. /**
  17156. * @ngdoc method
  17157. * @name $sceDelegate#trustAs
  17158. *
  17159. * @description
  17160. * Returns a trusted representation of the parameter for the specified context. This trusted
  17161. * object will later on be used as-is, without any security check, by bindings or directives
  17162. * that require this security context.
  17163. * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass
  17164. * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as
  17165. * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the
  17166. * sanitizer loaded, passing the value itself will render all the HTML that does not pose a
  17167. * security risk.
  17168. *
  17169. * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those
  17170. * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual
  17171. * escaping.
  17172. *
  17173. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  17174. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  17175. *
  17176. * @param {*} value The value that should be considered trusted.
  17177. * @return {*} A trusted representation of value, that can be used in the given context.
  17178. */
  17179. function trustAs(type, trustedValue) {
  17180. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17181. if (!Constructor) {
  17182. throw $sceMinErr('icontext',
  17183. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  17184. type, trustedValue);
  17185. }
  17186. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  17187. return trustedValue;
  17188. }
  17189. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  17190. // mutable objects, we ensure here that the value passed in is actually a string.
  17191. if (typeof trustedValue !== 'string') {
  17192. throw $sceMinErr('itype',
  17193. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  17194. type);
  17195. }
  17196. return new Constructor(trustedValue);
  17197. }
  17198. /**
  17199. * @ngdoc method
  17200. * @name $sceDelegate#valueOf
  17201. *
  17202. * @description
  17203. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  17204. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  17205. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  17206. *
  17207. * If the passed parameter is not a value that had been returned by {@link
  17208. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is.
  17209. *
  17210. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  17211. * call or anything else.
  17212. * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  17213. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  17214. * `value` unchanged.
  17215. */
  17216. function valueOf(maybeTrusted) {
  17217. if (maybeTrusted instanceof trustedValueHolderBase) {
  17218. return maybeTrusted.$$unwrapTrustedValue();
  17219. } else {
  17220. return maybeTrusted;
  17221. }
  17222. }
  17223. /**
  17224. * @ngdoc method
  17225. * @name $sceDelegate#getTrusted
  17226. *
  17227. * @description
  17228. * Takes any input, and either returns a value that's safe to use in the specified context, or
  17229. * throws an exception.
  17230. *
  17231. * In practice, there are several cases. When given a string, this function runs checks
  17232. * and sanitization to make it safe without prior assumptions. When given the result of a {@link
  17233. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call, it returns the originally supplied
  17234. * value if that value's context is valid for this call's context. Finally, this function can
  17235. * also throw when there is no way to turn `maybeTrusted` in a safe value (e.g., no sanitization
  17236. * is available or possible.)
  17237. *
  17238. * @param {string} type The context in which this value is to be used (such as `$sce.HTML`).
  17239. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  17240. * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.)
  17241. * @return {*} A version of the value that's safe to use in the given context, or throws an
  17242. * exception if this is impossible.
  17243. */
  17244. function getTrusted(type, maybeTrusted) {
  17245. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  17246. return maybeTrusted;
  17247. }
  17248. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17249. // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return
  17250. // as-is.
  17251. if (constructor && maybeTrusted instanceof constructor) {
  17252. return maybeTrusted.$$unwrapTrustedValue();
  17253. }
  17254. // Otherwise, if we get here, then we may either make it safe, or throw an exception. This
  17255. // depends on the context: some are sanitizatible (HTML), some use whitelists (RESOURCE_URL),
  17256. // some are impossible to do (JS). This step isn't implemented for CSS and URL, as AngularJS
  17257. // has no corresponding sinks.
  17258. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  17259. // RESOURCE_URL uses a whitelist.
  17260. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  17261. return maybeTrusted;
  17262. } else {
  17263. throw $sceMinErr('insecurl',
  17264. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  17265. maybeTrusted.toString());
  17266. }
  17267. } else if (type === SCE_CONTEXTS.HTML) {
  17268. // htmlSanitizer throws its own error when no sanitizer is available.
  17269. return htmlSanitizer(maybeTrusted);
  17270. }
  17271. // Default error when the $sce service has no way to make the input safe.
  17272. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17273. }
  17274. return { trustAs: trustAs,
  17275. getTrusted: getTrusted,
  17276. valueOf: valueOf };
  17277. }];
  17278. }
  17279. /**
  17280. * @ngdoc provider
  17281. * @name $sceProvider
  17282. * @this
  17283. *
  17284. * @description
  17285. *
  17286. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  17287. * - enable/disable Strict Contextual Escaping (SCE) in a module
  17288. * - override the default implementation with a custom delegate
  17289. *
  17290. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17291. */
  17292. /**
  17293. * @ngdoc service
  17294. * @name $sce
  17295. * @kind function
  17296. *
  17297. * @description
  17298. *
  17299. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  17300. *
  17301. * # Strict Contextual Escaping
  17302. *
  17303. * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render
  17304. * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and
  17305. * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  17306. *
  17307. * ## Overview
  17308. *
  17309. * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in
  17310. * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically
  17311. * run security checks on them (sanitizations, whitelists, depending on context), or throw when it
  17312. * cannot guarantee the security of the result. That behavior depends strongly on contexts: HTML
  17313. * can be sanitized, but template URLs cannot, for instance.
  17314. *
  17315. * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML:
  17316. * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it
  17317. * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and
  17318. * render the input as-is, you will need to mark it as trusted for that context before attempting
  17319. * to bind it.
  17320. *
  17321. * As of version 1.2, AngularJS ships with SCE enabled by default.
  17322. *
  17323. * ## In practice
  17324. *
  17325. * Here's an example of a binding in a privileged context:
  17326. *
  17327. * ```
  17328. * <input ng-model="userHtml" aria-label="User input">
  17329. * <div ng-bind-html="userHtml"></div>
  17330. * ```
  17331. *
  17332. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  17333. * disabled, this application allows the user to render arbitrary HTML into the DIV, which would
  17334. * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog
  17335. * articles, etc. via bindings. (HTML is just one example of a context where rendering user
  17336. * controlled input creates security vulnerabilities.)
  17337. *
  17338. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  17339. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  17340. *
  17341. * How would you ensure that every place that used these types of bindings was bound to a value that
  17342. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  17343. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  17344. * properties/fields and forgot to update the binding to the sanitized value?
  17345. *
  17346. * To be secure by default, AngularJS makes sure bindings go through that sanitization, or
  17347. * any similar validation process, unless there's a good reason to trust the given value in this
  17348. * context. That trust is formalized with a function call. This means that as a developer, you
  17349. * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues,
  17350. * you just need to ensure the values you mark as trusted indeed are safe - because they were
  17351. * received from your server, sanitized by your library, etc. You can organize your codebase to
  17352. * help with this - perhaps allowing only the files in a specific directory to do this.
  17353. * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then
  17354. * becomes a more manageable task.
  17355. *
  17356. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  17357. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  17358. * build the trusted versions of your values.
  17359. *
  17360. * ## How does it work?
  17361. *
  17362. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  17363. * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as
  17364. * a way to enforce the required security context in your data sink. Directives use {@link
  17365. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs
  17366. * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also,
  17367. * when binding without directives, AngularJS will understand the context of your bindings
  17368. * automatically.
  17369. *
  17370. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  17371. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  17372. * simplified):
  17373. *
  17374. * ```
  17375. * var ngBindHtmlDirective = ['$sce', function($sce) {
  17376. * return function(scope, element, attr) {
  17377. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  17378. * element.html(value || '');
  17379. * });
  17380. * };
  17381. * }];
  17382. * ```
  17383. *
  17384. * ## Impact on loading templates
  17385. *
  17386. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  17387. * `templateUrl`'s specified by {@link guide/directive directives}.
  17388. *
  17389. * By default, Angular only loads templates from the same domain and protocol as the application
  17390. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17391. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  17392. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  17393. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  17394. *
  17395. * *Please note*:
  17396. * The browser's
  17397. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17398. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17399. * policy apply in addition to this and may further restrict whether the template is successfully
  17400. * loaded. This means that without the right CORS policy, loading templates from a different domain
  17401. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  17402. * browsers.
  17403. *
  17404. * ## This feels like too much overhead
  17405. *
  17406. * It's important to remember that SCE only applies to interpolation expressions.
  17407. *
  17408. * If your expressions are constant literals, they're automatically trusted and you don't need to
  17409. * call `$sce.trustAs` on them (e.g.
  17410. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works. The `$sceDelegate` will
  17411. * also use the `$sanitize` service if it is available when binding untrusted values to
  17412. * `$sce.HTML` context. AngularJS provides an implementation in `angular-sanitize.js`, and if you
  17413. * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in
  17414. * your application.
  17415. *
  17416. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  17417. * templates in `ng-include` from your application's domain without having to even know about SCE.
  17418. * It blocks loading templates from other domains or loading templates over http from an https
  17419. * served document. You can change these by setting your own custom {@link
  17420. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  17421. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  17422. *
  17423. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  17424. * application that's secure and can be audited to verify that with much more ease than bolting
  17425. * security onto an application later.
  17426. *
  17427. * <a name="contexts"></a>
  17428. * ## What trusted context types are supported?
  17429. *
  17430. * | Context | Notes |
  17431. * |---------------------|----------------|
  17432. * | `$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 $sanitize} service is available (implemented by the {@link ngSanitize ngSanitize} module) this will sanitize the value instead of throwing an error. |
  17433. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently, no bindings require this context. Feel free to use it in your own directives. |
  17434. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=`, `<img src=`, and some others sanitize their urls and don't constitute an SCE context.) |
  17435. * | `$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`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does (it's not just the URL that matters, but also what is at the end of it), and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  17436. * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently, no bindings require this context. Feel free to use it in your own directives. |
  17437. *
  17438. *
  17439. * Be aware that `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  17440. * through {@link ng.$sce#getTrusted $sce.getTrusted}. There's no CSS-, URL-, or JS-context bindings
  17441. * in AngularJS currently, so their corresponding `$sce.trustAs` functions aren't useful yet. This
  17442. * might evolve.
  17443. *
  17444. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  17445. *
  17446. * Each element in these arrays must be one of the following:
  17447. *
  17448. * - **'self'**
  17449. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  17450. * domain** as the application document using the **same protocol**.
  17451. * - **String** (except the special value `'self'`)
  17452. * - The string is matched against the full *normalized / absolute URL* of the resource
  17453. * being tested (substring matches are not good enough.)
  17454. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  17455. * match themselves.
  17456. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  17457. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  17458. * in a whitelist.
  17459. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  17460. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  17461. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  17462. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  17463. * http://foo.example.com/templates/**).
  17464. * - **RegExp** (*see caveat below*)
  17465. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  17466. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  17467. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  17468. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  17469. * small number of cases. A `.` character in the regex used when matching the scheme or a
  17470. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  17471. * is highly recommended to use the string patterns and only fall back to regular expressions
  17472. * as a last resort.
  17473. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  17474. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  17475. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  17476. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  17477. * - If you are generating your JavaScript from some other templating engine (not
  17478. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  17479. * remember to escape your regular expression (and be aware that you might need more than
  17480. * one level of escaping depending on your templating engine and the way you interpolated
  17481. * the value.) Do make use of your platform's escaping mechanism as it might be good
  17482. * enough before coding your own. E.g. Ruby has
  17483. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  17484. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  17485. * Javascript lacks a similar built in function for escaping. Take a look at Google
  17486. * Closure library's [goog.string.regExpEscape(s)](
  17487. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  17488. *
  17489. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  17490. *
  17491. * ## Show me an example using SCE.
  17492. *
  17493. * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
  17494. * <file name="index.html">
  17495. * <div ng-controller="AppController as myCtrl">
  17496. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  17497. * <b>User comments</b><br>
  17498. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  17499. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  17500. * exploit.
  17501. * <div class="well">
  17502. * <div ng-repeat="userComment in myCtrl.userComments">
  17503. * <b>{{userComment.name}}</b>:
  17504. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  17505. * <br>
  17506. * </div>
  17507. * </div>
  17508. * </div>
  17509. * </file>
  17510. *
  17511. * <file name="script.js">
  17512. * angular.module('mySceApp', ['ngSanitize'])
  17513. * .controller('AppController', ['$http', '$templateCache', '$sce',
  17514. * function AppController($http, $templateCache, $sce) {
  17515. * var self = this;
  17516. * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {
  17517. * self.userComments = response.data;
  17518. * });
  17519. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  17520. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17521. * 'sanitization.&quot;">Hover over this text.</span>');
  17522. * }]);
  17523. * </file>
  17524. *
  17525. * <file name="test_data.json">
  17526. * [
  17527. * { "name": "Alice",
  17528. * "htmlComment":
  17529. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  17530. * },
  17531. * { "name": "Bob",
  17532. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  17533. * }
  17534. * ]
  17535. * </file>
  17536. *
  17537. * <file name="protractor.js" type="protractor">
  17538. * describe('SCE doc demo', function() {
  17539. * it('should sanitize untrusted values', function() {
  17540. * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
  17541. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  17542. * });
  17543. *
  17544. * it('should NOT sanitize explicitly trusted values', function() {
  17545. * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
  17546. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17547. * 'sanitization.&quot;">Hover over this text.</span>');
  17548. * });
  17549. * });
  17550. * </file>
  17551. * </example>
  17552. *
  17553. *
  17554. *
  17555. * ## Can I disable SCE completely?
  17556. *
  17557. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  17558. * for little coding overhead. It will be much harder to take an SCE disabled application and
  17559. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  17560. * for cases where you have a lot of existing code that was written before SCE was introduced and
  17561. * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if
  17562. * you are writing a library, you will cause security bugs applications using it.
  17563. *
  17564. * That said, here's how you can completely disable SCE:
  17565. *
  17566. * ```
  17567. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  17568. * // Completely disable SCE. For demonstration purposes only!
  17569. * // Do not use in new projects or libraries.
  17570. * $sceProvider.enabled(false);
  17571. * });
  17572. * ```
  17573. *
  17574. */
  17575. function $SceProvider() {
  17576. var enabled = true;
  17577. /**
  17578. * @ngdoc method
  17579. * @name $sceProvider#enabled
  17580. * @kind function
  17581. *
  17582. * @param {boolean=} value If provided, then enables/disables SCE application-wide.
  17583. * @return {boolean} True if SCE is enabled, false otherwise.
  17584. *
  17585. * @description
  17586. * Enables/disables SCE and returns the current value.
  17587. */
  17588. this.enabled = function(value) {
  17589. if (arguments.length) {
  17590. enabled = !!value;
  17591. }
  17592. return enabled;
  17593. };
  17594. /* Design notes on the default implementation for SCE.
  17595. *
  17596. * The API contract for the SCE delegate
  17597. * -------------------------------------
  17598. * The SCE delegate object must provide the following 3 methods:
  17599. *
  17600. * - trustAs(contextEnum, value)
  17601. * This method is used to tell the SCE service that the provided value is OK to use in the
  17602. * contexts specified by contextEnum. It must return an object that will be accepted by
  17603. * getTrusted() for a compatible contextEnum and return this value.
  17604. *
  17605. * - valueOf(value)
  17606. * For values that were not produced by trustAs(), return them as is. For values that were
  17607. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  17608. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  17609. * such a value.
  17610. *
  17611. * - getTrusted(contextEnum, value)
  17612. * This function should return the a value that is safe to use in the context specified by
  17613. * contextEnum or throw and exception otherwise.
  17614. *
  17615. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  17616. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  17617. * instance, an implementation could maintain a registry of all trusted objects by context. In
  17618. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  17619. * return the same object passed in if it was found in the registry under a compatible context or
  17620. * throw an exception otherwise. An implementation might only wrap values some of the time based
  17621. * on some criteria. getTrusted() might return a value and not throw an exception for special
  17622. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  17623. *
  17624. *
  17625. * A note on the inheritance model for SCE contexts
  17626. * ------------------------------------------------
  17627. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  17628. * is purely an implementation details.
  17629. *
  17630. * The contract is simply this:
  17631. *
  17632. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  17633. * will also succeed.
  17634. *
  17635. * Inheritance happens to capture this in a natural way. In some future, we may not use
  17636. * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to
  17637. * be aware of this detail.
  17638. */
  17639. this.$get = ['$parse', '$sceDelegate', function(
  17640. $parse, $sceDelegate) {
  17641. // Support: IE 9-11 only
  17642. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  17643. // the "expression(javascript expression)" syntax which is insecure.
  17644. if (enabled && msie < 8) {
  17645. throw $sceMinErr('iequirks',
  17646. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  17647. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  17648. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  17649. }
  17650. var sce = shallowCopy(SCE_CONTEXTS);
  17651. /**
  17652. * @ngdoc method
  17653. * @name $sce#isEnabled
  17654. * @kind function
  17655. *
  17656. * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you
  17657. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  17658. *
  17659. * @description
  17660. * Returns a boolean indicating if SCE is enabled.
  17661. */
  17662. sce.isEnabled = function() {
  17663. return enabled;
  17664. };
  17665. sce.trustAs = $sceDelegate.trustAs;
  17666. sce.getTrusted = $sceDelegate.getTrusted;
  17667. sce.valueOf = $sceDelegate.valueOf;
  17668. if (!enabled) {
  17669. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  17670. sce.valueOf = identity;
  17671. }
  17672. /**
  17673. * @ngdoc method
  17674. * @name $sce#parseAs
  17675. *
  17676. * @description
  17677. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  17678. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  17679. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  17680. * *result*)}
  17681. *
  17682. * @param {string} type The SCE context in which this result will be used.
  17683. * @param {string} expression String expression to compile.
  17684. * @return {function(context, locals)} A function which represents the compiled expression:
  17685. *
  17686. * * `context` – `{object}` – an object against which any expressions embedded in the
  17687. * strings are evaluated against (typically a scope object).
  17688. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  17689. * in `context`.
  17690. */
  17691. sce.parseAs = function sceParseAs(type, expr) {
  17692. var parsed = $parse(expr);
  17693. if (parsed.literal && parsed.constant) {
  17694. return parsed;
  17695. } else {
  17696. return $parse(expr, function(value) {
  17697. return sce.getTrusted(type, value);
  17698. });
  17699. }
  17700. };
  17701. /**
  17702. * @ngdoc method
  17703. * @name $sce#trustAs
  17704. *
  17705. * @description
  17706. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a
  17707. * wrapped object that represents your value, and the trust you have in its safety for the given
  17708. * context. AngularJS can then use that value as-is in bindings of the specified secure context.
  17709. * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute
  17710. * interpolations. See {@link ng.$sce $sce} for strict contextual escaping.
  17711. *
  17712. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  17713. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  17714. *
  17715. * @param {*} value The value that that should be considered trusted.
  17716. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  17717. * in the context you specified.
  17718. */
  17719. /**
  17720. * @ngdoc method
  17721. * @name $sce#trustAsHtml
  17722. *
  17723. * @description
  17724. * Shorthand method. `$sce.trustAsHtml(value)` →
  17725. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  17726. *
  17727. * @param {*} value The value to mark as trusted for `$sce.HTML` context.
  17728. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  17729. * in `$sce.HTML` context (like `ng-bind-html`).
  17730. */
  17731. /**
  17732. * @ngdoc method
  17733. * @name $sce#trustAsCss
  17734. *
  17735. * @description
  17736. * Shorthand method. `$sce.trustAsCss(value)` →
  17737. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`}
  17738. *
  17739. * @param {*} value The value to mark as trusted for `$sce.CSS` context.
  17740. * @return {*} A wrapped version of value that can be used as a trusted variant
  17741. * of your `value` in `$sce.CSS` context. This context is currently unused, so there are
  17742. * almost no reasons to use this function so far.
  17743. */
  17744. /**
  17745. * @ngdoc method
  17746. * @name $sce#trustAsUrl
  17747. *
  17748. * @description
  17749. * Shorthand method. `$sce.trustAsUrl(value)` →
  17750. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  17751. *
  17752. * @param {*} value The value to mark as trusted for `$sce.URL` context.
  17753. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  17754. * in `$sce.URL` context. That context is currently unused, so there are almost no reasons
  17755. * to use this function so far.
  17756. */
  17757. /**
  17758. * @ngdoc method
  17759. * @name $sce#trustAsResourceUrl
  17760. *
  17761. * @description
  17762. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  17763. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  17764. *
  17765. * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context.
  17766. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  17767. * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute
  17768. * bindings, ...)
  17769. */
  17770. /**
  17771. * @ngdoc method
  17772. * @name $sce#trustAsJs
  17773. *
  17774. * @description
  17775. * Shorthand method. `$sce.trustAsJs(value)` →
  17776. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  17777. *
  17778. * @param {*} value The value to mark as trusted for `$sce.JS` context.
  17779. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  17780. * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to
  17781. * use this function so far.
  17782. */
  17783. /**
  17784. * @ngdoc method
  17785. * @name $sce#getTrusted
  17786. *
  17787. * @description
  17788. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  17789. * takes any input, and either returns a value that's safe to use in the specified context,
  17790. * or throws an exception. This function is aware of trusted values created by the `trustAs`
  17791. * function and its shorthands, and when contexts are appropriate, returns the unwrapped value
  17792. * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a
  17793. * safe value (e.g., no sanitization is available or possible.)
  17794. *
  17795. * @param {string} type The context in which this value is to be used.
  17796. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs
  17797. * `$sce.trustAs`} call, or anything else (which will not be considered trusted.)
  17798. * @return {*} A version of the value that's safe to use in the given context, or throws an
  17799. * exception if this is impossible.
  17800. */
  17801. /**
  17802. * @ngdoc method
  17803. * @name $sce#getTrustedHtml
  17804. *
  17805. * @description
  17806. * Shorthand method. `$sce.getTrustedHtml(value)` →
  17807. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  17808. *
  17809. * @param {*} value The value to pass to `$sce.getTrusted`.
  17810. * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  17811. */
  17812. /**
  17813. * @ngdoc method
  17814. * @name $sce#getTrustedCss
  17815. *
  17816. * @description
  17817. * Shorthand method. `$sce.getTrustedCss(value)` →
  17818. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  17819. *
  17820. * @param {*} value The value to pass to `$sce.getTrusted`.
  17821. * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  17822. */
  17823. /**
  17824. * @ngdoc method
  17825. * @name $sce#getTrustedUrl
  17826. *
  17827. * @description
  17828. * Shorthand method. `$sce.getTrustedUrl(value)` →
  17829. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  17830. *
  17831. * @param {*} value The value to pass to `$sce.getTrusted`.
  17832. * @return {*} The return value of `$sce.getTrusted($sce.URL, value)`
  17833. */
  17834. /**
  17835. * @ngdoc method
  17836. * @name $sce#getTrustedResourceUrl
  17837. *
  17838. * @description
  17839. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  17840. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  17841. *
  17842. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  17843. * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  17844. */
  17845. /**
  17846. * @ngdoc method
  17847. * @name $sce#getTrustedJs
  17848. *
  17849. * @description
  17850. * Shorthand method. `$sce.getTrustedJs(value)` →
  17851. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  17852. *
  17853. * @param {*} value The value to pass to `$sce.getTrusted`.
  17854. * @return {*} The return value of `$sce.getTrusted($sce.JS, value)`
  17855. */
  17856. /**
  17857. * @ngdoc method
  17858. * @name $sce#parseAsHtml
  17859. *
  17860. * @description
  17861. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  17862. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  17863. *
  17864. * @param {string} expression String expression to compile.
  17865. * @return {function(context, locals)} A function which represents the compiled expression:
  17866. *
  17867. * * `context` – `{object}` – an object against which any expressions embedded in the
  17868. * strings are evaluated against (typically a scope object).
  17869. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  17870. * in `context`.
  17871. */
  17872. /**
  17873. * @ngdoc method
  17874. * @name $sce#parseAsCss
  17875. *
  17876. * @description
  17877. * Shorthand method. `$sce.parseAsCss(value)` →
  17878. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  17879. *
  17880. * @param {string} expression String expression to compile.
  17881. * @return {function(context, locals)} A function which represents the compiled expression:
  17882. *
  17883. * * `context` – `{object}` – an object against which any expressions embedded in the
  17884. * strings are evaluated against (typically a scope object).
  17885. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  17886. * in `context`.
  17887. */
  17888. /**
  17889. * @ngdoc method
  17890. * @name $sce#parseAsUrl
  17891. *
  17892. * @description
  17893. * Shorthand method. `$sce.parseAsUrl(value)` →
  17894. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  17895. *
  17896. * @param {string} expression String expression to compile.
  17897. * @return {function(context, locals)} A function which represents the compiled expression:
  17898. *
  17899. * * `context` – `{object}` – an object against which any expressions embedded in the
  17900. * strings are evaluated against (typically a scope object).
  17901. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  17902. * in `context`.
  17903. */
  17904. /**
  17905. * @ngdoc method
  17906. * @name $sce#parseAsResourceUrl
  17907. *
  17908. * @description
  17909. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  17910. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  17911. *
  17912. * @param {string} expression String expression to compile.
  17913. * @return {function(context, locals)} A function which represents the compiled expression:
  17914. *
  17915. * * `context` – `{object}` – an object against which any expressions embedded in the
  17916. * strings are evaluated against (typically a scope object).
  17917. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  17918. * in `context`.
  17919. */
  17920. /**
  17921. * @ngdoc method
  17922. * @name $sce#parseAsJs
  17923. *
  17924. * @description
  17925. * Shorthand method. `$sce.parseAsJs(value)` →
  17926. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  17927. *
  17928. * @param {string} expression String expression to compile.
  17929. * @return {function(context, locals)} A function which represents the compiled expression:
  17930. *
  17931. * * `context` – `{object}` – an object against which any expressions embedded in the
  17932. * strings are evaluated against (typically a scope object).
  17933. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  17934. * in `context`.
  17935. */
  17936. // Shorthand delegations.
  17937. var parse = sce.parseAs,
  17938. getTrusted = sce.getTrusted,
  17939. trustAs = sce.trustAs;
  17940. forEach(SCE_CONTEXTS, function(enumValue, name) {
  17941. var lName = lowercase(name);
  17942. sce[snakeToCamel('parse_as_' + lName)] = function(expr) {
  17943. return parse(enumValue, expr);
  17944. };
  17945. sce[snakeToCamel('get_trusted_' + lName)] = function(value) {
  17946. return getTrusted(enumValue, value);
  17947. };
  17948. sce[snakeToCamel('trust_as_' + lName)] = function(value) {
  17949. return trustAs(enumValue, value);
  17950. };
  17951. });
  17952. return sce;
  17953. }];
  17954. }
  17955. /* exported $SnifferProvider */
  17956. /**
  17957. * !!! This is an undocumented "private" service !!!
  17958. *
  17959. * @name $sniffer
  17960. * @requires $window
  17961. * @requires $document
  17962. * @this
  17963. *
  17964. * @property {boolean} history Does the browser support html5 history api ?
  17965. * @property {boolean} transitions Does the browser support CSS transition events ?
  17966. * @property {boolean} animations Does the browser support CSS animation events ?
  17967. *
  17968. * @description
  17969. * This is very simple implementation of testing browser's features.
  17970. */
  17971. function $SnifferProvider() {
  17972. this.$get = ['$window', '$document', function($window, $document) {
  17973. var eventSupport = {},
  17974. // Chrome Packaged Apps are not allowed to access `history.pushState`.
  17975. // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
  17976. // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
  17977. // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
  17978. // (see https://developer.chrome.com/apps/manifest/sandbox).
  17979. // (NW.js apps have access to Chrome APIs, but do support `history`.)
  17980. isNw = $window.nw && $window.nw.process,
  17981. isChromePackagedApp =
  17982. !isNw &&
  17983. $window.chrome &&
  17984. ($window.chrome.app && $window.chrome.app.runtime ||
  17985. !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
  17986. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  17987. android =
  17988. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  17989. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  17990. document = $document[0] || {},
  17991. bodyStyle = document.body && document.body.style,
  17992. transitions = false,
  17993. animations = false;
  17994. if (bodyStyle) {
  17995. // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x
  17996. // Mentioned browsers need a -webkit- prefix for transitions & animations.
  17997. transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);
  17998. animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);
  17999. }
  18000. return {
  18001. // Android has history.pushState, but it does not update location correctly
  18002. // so let's not use the history API at all.
  18003. // http://code.google.com/p/android/issues/detail?id=17471
  18004. // https://github.com/angular/angular.js/issues/904
  18005. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  18006. // so let's not use the history API also
  18007. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  18008. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  18009. hasEvent: function(event) {
  18010. // Support: IE 9-11 only
  18011. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  18012. // it. In particular the event is not fired when backspace or delete key are pressed or
  18013. // when cut operation is performed.
  18014. // IE10+ implements 'input' event but it erroneously fires under various situations,
  18015. // e.g. when placeholder changes, or a form is focused.
  18016. if (event === 'input' && msie) return false;
  18017. if (isUndefined(eventSupport[event])) {
  18018. var divElm = document.createElement('div');
  18019. eventSupport[event] = 'on' + event in divElm;
  18020. }
  18021. return eventSupport[event];
  18022. },
  18023. csp: csp(),
  18024. transitions: transitions,
  18025. animations: animations,
  18026. android: android
  18027. };
  18028. }];
  18029. }
  18030. var $templateRequestMinErr = minErr('$compile');
  18031. /**
  18032. * @ngdoc provider
  18033. * @name $templateRequestProvider
  18034. * @this
  18035. *
  18036. * @description
  18037. * Used to configure the options passed to the {@link $http} service when making a template request.
  18038. *
  18039. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  18040. * requesting a template.
  18041. */
  18042. function $TemplateRequestProvider() {
  18043. var httpOptions;
  18044. /**
  18045. * @ngdoc method
  18046. * @name $templateRequestProvider#httpOptions
  18047. * @description
  18048. * The options to be passed to the {@link $http} service when making the request.
  18049. * You can use this to override options such as the "Accept" header for template requests.
  18050. *
  18051. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  18052. * options if not overridden here.
  18053. *
  18054. * @param {string=} value new value for the {@link $http} options.
  18055. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  18056. */
  18057. this.httpOptions = function(val) {
  18058. if (val) {
  18059. httpOptions = val;
  18060. return this;
  18061. }
  18062. return httpOptions;
  18063. };
  18064. /**
  18065. * @ngdoc service
  18066. * @name $templateRequest
  18067. *
  18068. * @description
  18069. * The `$templateRequest` service runs security checks then downloads the provided template using
  18070. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  18071. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  18072. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  18073. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  18074. * when `tpl` is of type string and `$templateCache` has the matching entry.
  18075. *
  18076. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  18077. * can configure this via {@link $templateRequestProvider#httpOptions}.
  18078. *
  18079. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  18080. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  18081. *
  18082. * @return {Promise} a promise for the HTTP response data of the given URL.
  18083. *
  18084. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  18085. */
  18086. this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',
  18087. function($exceptionHandler, $templateCache, $http, $q, $sce) {
  18088. function handleRequestFn(tpl, ignoreRequestError) {
  18089. handleRequestFn.totalPendingRequests++;
  18090. // We consider the template cache holds only trusted templates, so
  18091. // there's no need to go through whitelisting again for keys that already
  18092. // are included in there. This also makes Angular accept any script
  18093. // directive, no matter its name. However, we still need to unwrap trusted
  18094. // types.
  18095. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  18096. tpl = $sce.getTrustedResourceUrl(tpl);
  18097. }
  18098. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  18099. if (isArray(transformResponse)) {
  18100. transformResponse = transformResponse.filter(function(transformer) {
  18101. return transformer !== defaultHttpResponseTransform;
  18102. });
  18103. } else if (transformResponse === defaultHttpResponseTransform) {
  18104. transformResponse = null;
  18105. }
  18106. return $http.get(tpl, extend({
  18107. cache: $templateCache,
  18108. transformResponse: transformResponse
  18109. }, httpOptions))
  18110. .finally(function() {
  18111. handleRequestFn.totalPendingRequests--;
  18112. })
  18113. .then(function(response) {
  18114. $templateCache.put(tpl, response.data);
  18115. return response.data;
  18116. }, handleError);
  18117. function handleError(resp) {
  18118. if (!ignoreRequestError) {
  18119. resp = $templateRequestMinErr('tpload',
  18120. 'Failed to load template: {0} (HTTP status: {1} {2})',
  18121. tpl, resp.status, resp.statusText);
  18122. $exceptionHandler(resp);
  18123. }
  18124. return $q.reject(resp);
  18125. }
  18126. }
  18127. handleRequestFn.totalPendingRequests = 0;
  18128. return handleRequestFn;
  18129. }
  18130. ];
  18131. }
  18132. /** @this */
  18133. function $$TestabilityProvider() {
  18134. this.$get = ['$rootScope', '$browser', '$location',
  18135. function($rootScope, $browser, $location) {
  18136. /**
  18137. * @name $testability
  18138. *
  18139. * @description
  18140. * The private $$testability service provides a collection of methods for use when debugging
  18141. * or by automated test and debugging tools.
  18142. */
  18143. var testability = {};
  18144. /**
  18145. * @name $$testability#findBindings
  18146. *
  18147. * @description
  18148. * Returns an array of elements that are bound (via ng-bind or {{}})
  18149. * to expressions matching the input.
  18150. *
  18151. * @param {Element} element The element root to search from.
  18152. * @param {string} expression The binding expression to match.
  18153. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18154. * for the expression. Filters and whitespace are ignored.
  18155. */
  18156. testability.findBindings = function(element, expression, opt_exactMatch) {
  18157. var bindings = element.getElementsByClassName('ng-binding');
  18158. var matches = [];
  18159. forEach(bindings, function(binding) {
  18160. var dataBinding = angular.element(binding).data('$binding');
  18161. if (dataBinding) {
  18162. forEach(dataBinding, function(bindingName) {
  18163. if (opt_exactMatch) {
  18164. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  18165. if (matcher.test(bindingName)) {
  18166. matches.push(binding);
  18167. }
  18168. } else {
  18169. if (bindingName.indexOf(expression) !== -1) {
  18170. matches.push(binding);
  18171. }
  18172. }
  18173. });
  18174. }
  18175. });
  18176. return matches;
  18177. };
  18178. /**
  18179. * @name $$testability#findModels
  18180. *
  18181. * @description
  18182. * Returns an array of elements that are two-way found via ng-model to
  18183. * expressions matching the input.
  18184. *
  18185. * @param {Element} element The element root to search from.
  18186. * @param {string} expression The model expression to match.
  18187. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18188. * for the expression.
  18189. */
  18190. testability.findModels = function(element, expression, opt_exactMatch) {
  18191. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  18192. for (var p = 0; p < prefixes.length; ++p) {
  18193. var attributeEquals = opt_exactMatch ? '=' : '*=';
  18194. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  18195. var elements = element.querySelectorAll(selector);
  18196. if (elements.length) {
  18197. return elements;
  18198. }
  18199. }
  18200. };
  18201. /**
  18202. * @name $$testability#getLocation
  18203. *
  18204. * @description
  18205. * Shortcut for getting the location in a browser agnostic way. Returns
  18206. * the path, search, and hash. (e.g. /path?a=b#hash)
  18207. */
  18208. testability.getLocation = function() {
  18209. return $location.url();
  18210. };
  18211. /**
  18212. * @name $$testability#setLocation
  18213. *
  18214. * @description
  18215. * Shortcut for navigating to a location without doing a full page reload.
  18216. *
  18217. * @param {string} url The location url (path, search and hash,
  18218. * e.g. /path?a=b#hash) to go to.
  18219. */
  18220. testability.setLocation = function(url) {
  18221. if (url !== $location.url()) {
  18222. $location.url(url);
  18223. $rootScope.$digest();
  18224. }
  18225. };
  18226. /**
  18227. * @name $$testability#whenStable
  18228. *
  18229. * @description
  18230. * Calls the callback when $timeout and $http requests are completed.
  18231. *
  18232. * @param {function} callback
  18233. */
  18234. testability.whenStable = function(callback) {
  18235. $browser.notifyWhenNoOutstandingRequests(callback);
  18236. };
  18237. return testability;
  18238. }];
  18239. }
  18240. /** @this */
  18241. function $TimeoutProvider() {
  18242. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  18243. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  18244. var deferreds = {};
  18245. /**
  18246. * @ngdoc service
  18247. * @name $timeout
  18248. *
  18249. * @description
  18250. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  18251. * block and delegates any exceptions to
  18252. * {@link ng.$exceptionHandler $exceptionHandler} service.
  18253. *
  18254. * The return value of calling `$timeout` is a promise, which will be resolved when
  18255. * the delay has passed and the timeout function, if provided, is executed.
  18256. *
  18257. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  18258. *
  18259. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  18260. * synchronously flush the queue of deferred functions.
  18261. *
  18262. * If you only want a promise that will be resolved after some specified delay
  18263. * then you can call `$timeout` without the `fn` function.
  18264. *
  18265. * @param {function()=} fn A function, whose execution should be delayed.
  18266. * @param {number=} [delay=0] Delay in milliseconds.
  18267. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  18268. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  18269. * @param {...*=} Pass additional parameters to the executed function.
  18270. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  18271. * will be resolved with the return value of the `fn` function.
  18272. *
  18273. */
  18274. function timeout(fn, delay, invokeApply) {
  18275. if (!isFunction(fn)) {
  18276. invokeApply = delay;
  18277. delay = fn;
  18278. fn = noop;
  18279. }
  18280. var args = sliceArgs(arguments, 3),
  18281. skipApply = (isDefined(invokeApply) && !invokeApply),
  18282. deferred = (skipApply ? $$q : $q).defer(),
  18283. promise = deferred.promise,
  18284. timeoutId;
  18285. timeoutId = $browser.defer(function() {
  18286. try {
  18287. deferred.resolve(fn.apply(null, args));
  18288. } catch (e) {
  18289. deferred.reject(e);
  18290. $exceptionHandler(e);
  18291. } finally {
  18292. delete deferreds[promise.$$timeoutId];
  18293. }
  18294. if (!skipApply) $rootScope.$apply();
  18295. }, delay);
  18296. promise.$$timeoutId = timeoutId;
  18297. deferreds[timeoutId] = deferred;
  18298. return promise;
  18299. }
  18300. /**
  18301. * @ngdoc method
  18302. * @name $timeout#cancel
  18303. *
  18304. * @description
  18305. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  18306. * resolved with a rejection.
  18307. *
  18308. * @param {Promise=} promise Promise returned by the `$timeout` function.
  18309. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  18310. * canceled.
  18311. */
  18312. timeout.cancel = function(promise) {
  18313. if (promise && promise.$$timeoutId in deferreds) {
  18314. // Timeout cancels should not report an unhandled promise.
  18315. deferreds[promise.$$timeoutId].promise.catch(noop);
  18316. deferreds[promise.$$timeoutId].reject('canceled');
  18317. delete deferreds[promise.$$timeoutId];
  18318. return $browser.defer.cancel(promise.$$timeoutId);
  18319. }
  18320. return false;
  18321. };
  18322. return timeout;
  18323. }];
  18324. }
  18325. // NOTE: The usage of window and document instead of $window and $document here is
  18326. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  18327. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  18328. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  18329. // doesn't know about mocked locations and resolves URLs to the real document - which is
  18330. // exactly the behavior needed here. There is little value is mocking these out for this
  18331. // service.
  18332. var urlParsingNode = window.document.createElement('a');
  18333. var originUrl = urlResolve(window.location.href);
  18334. /**
  18335. *
  18336. * Implementation Notes for non-IE browsers
  18337. * ----------------------------------------
  18338. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  18339. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  18340. * URL will be resolved into an absolute URL in the context of the application document.
  18341. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  18342. * properties are all populated to reflect the normalized URL. This approach has wide
  18343. * compatibility - Safari 1+, Mozilla 1+ etc. See
  18344. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18345. *
  18346. * Implementation Notes for IE
  18347. * ---------------------------
  18348. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  18349. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  18350. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  18351. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  18352. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  18353. * properties such as protocol, hostname, port, etc.
  18354. *
  18355. * References:
  18356. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  18357. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18358. * http://url.spec.whatwg.org/#urlutils
  18359. * https://github.com/angular/angular.js/pull/2902
  18360. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  18361. *
  18362. * @kind function
  18363. * @param {string} url The URL to be parsed.
  18364. * @description Normalizes and parses a URL.
  18365. * @returns {object} Returns the normalized URL as a dictionary.
  18366. *
  18367. * | member name | Description |
  18368. * |---------------|----------------|
  18369. * | href | A normalized version of the provided URL if it was not an absolute URL |
  18370. * | protocol | The protocol including the trailing colon |
  18371. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  18372. * | search | The search params, minus the question mark |
  18373. * | hash | The hash string, minus the hash symbol
  18374. * | hostname | The hostname
  18375. * | port | The port, without ":"
  18376. * | pathname | The pathname, beginning with "/"
  18377. *
  18378. */
  18379. function urlResolve(url) {
  18380. var href = url;
  18381. // Support: IE 9-11 only
  18382. if (msie) {
  18383. // Normalize before parse. Refer Implementation Notes on why this is
  18384. // done in two steps on IE.
  18385. urlParsingNode.setAttribute('href', href);
  18386. href = urlParsingNode.href;
  18387. }
  18388. urlParsingNode.setAttribute('href', href);
  18389. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  18390. return {
  18391. href: urlParsingNode.href,
  18392. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  18393. host: urlParsingNode.host,
  18394. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  18395. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  18396. hostname: urlParsingNode.hostname,
  18397. port: urlParsingNode.port,
  18398. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  18399. ? urlParsingNode.pathname
  18400. : '/' + urlParsingNode.pathname
  18401. };
  18402. }
  18403. /**
  18404. * Parse a request URL and determine whether this is a same-origin request as the application document.
  18405. *
  18406. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  18407. * or a parsed URL object.
  18408. * @returns {boolean} Whether the request is for the same origin as the application document.
  18409. */
  18410. function urlIsSameOrigin(requestUrl) {
  18411. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  18412. return (parsed.protocol === originUrl.protocol &&
  18413. parsed.host === originUrl.host);
  18414. }
  18415. /**
  18416. * @ngdoc service
  18417. * @name $window
  18418. * @this
  18419. *
  18420. * @description
  18421. * A reference to the browser's `window` object. While `window`
  18422. * is globally available in JavaScript, it causes testability problems, because
  18423. * it is a global variable. In angular we always refer to it through the
  18424. * `$window` service, so it may be overridden, removed or mocked for testing.
  18425. *
  18426. * Expressions, like the one defined for the `ngClick` directive in the example
  18427. * below, are evaluated with respect to the current scope. Therefore, there is
  18428. * no risk of inadvertently coding in a dependency on a global value in such an
  18429. * expression.
  18430. *
  18431. * @example
  18432. <example module="windowExample" name="window-service">
  18433. <file name="index.html">
  18434. <script>
  18435. angular.module('windowExample', [])
  18436. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  18437. $scope.greeting = 'Hello, World!';
  18438. $scope.doGreeting = function(greeting) {
  18439. $window.alert(greeting);
  18440. };
  18441. }]);
  18442. </script>
  18443. <div ng-controller="ExampleController">
  18444. <input type="text" ng-model="greeting" aria-label="greeting" />
  18445. <button ng-click="doGreeting(greeting)">ALERT</button>
  18446. </div>
  18447. </file>
  18448. <file name="protractor.js" type="protractor">
  18449. it('should display the greeting in the input box', function() {
  18450. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  18451. // If we click the button it will block the test runner
  18452. // element(':button').click();
  18453. });
  18454. </file>
  18455. </example>
  18456. */
  18457. function $WindowProvider() {
  18458. this.$get = valueFn(window);
  18459. }
  18460. /**
  18461. * @name $$cookieReader
  18462. * @requires $document
  18463. *
  18464. * @description
  18465. * This is a private service for reading cookies used by $http and ngCookies
  18466. *
  18467. * @return {Object} a key/value map of the current cookies
  18468. */
  18469. function $$CookieReader($document) {
  18470. var rawDocument = $document[0] || {};
  18471. var lastCookies = {};
  18472. var lastCookieString = '';
  18473. function safeGetCookie(rawDocument) {
  18474. try {
  18475. return rawDocument.cookie || '';
  18476. } catch (e) {
  18477. return '';
  18478. }
  18479. }
  18480. function safeDecodeURIComponent(str) {
  18481. try {
  18482. return decodeURIComponent(str);
  18483. } catch (e) {
  18484. return str;
  18485. }
  18486. }
  18487. return function() {
  18488. var cookieArray, cookie, i, index, name;
  18489. var currentCookieString = safeGetCookie(rawDocument);
  18490. if (currentCookieString !== lastCookieString) {
  18491. lastCookieString = currentCookieString;
  18492. cookieArray = lastCookieString.split('; ');
  18493. lastCookies = {};
  18494. for (i = 0; i < cookieArray.length; i++) {
  18495. cookie = cookieArray[i];
  18496. index = cookie.indexOf('=');
  18497. if (index > 0) { //ignore nameless cookies
  18498. name = safeDecodeURIComponent(cookie.substring(0, index));
  18499. // the first value that is seen for a cookie is the most
  18500. // specific one. values for the same cookie name that
  18501. // follow are for less specific paths.
  18502. if (isUndefined(lastCookies[name])) {
  18503. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  18504. }
  18505. }
  18506. }
  18507. }
  18508. return lastCookies;
  18509. };
  18510. }
  18511. $$CookieReader.$inject = ['$document'];
  18512. /** @this */
  18513. function $$CookieReaderProvider() {
  18514. this.$get = $$CookieReader;
  18515. }
  18516. /* global currencyFilter: true,
  18517. dateFilter: true,
  18518. filterFilter: true,
  18519. jsonFilter: true,
  18520. limitToFilter: true,
  18521. lowercaseFilter: true,
  18522. numberFilter: true,
  18523. orderByFilter: true,
  18524. uppercaseFilter: true,
  18525. */
  18526. /**
  18527. * @ngdoc provider
  18528. * @name $filterProvider
  18529. * @description
  18530. *
  18531. * Filters are just functions which transform input to an output. However filters need to be
  18532. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  18533. * annotated with dependencies and is responsible for creating a filter function.
  18534. *
  18535. * <div class="alert alert-warning">
  18536. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18537. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18538. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18539. * (`myapp_subsection_filterx`).
  18540. * </div>
  18541. *
  18542. * ```js
  18543. * // Filter registration
  18544. * function MyModule($provide, $filterProvider) {
  18545. * // create a service to demonstrate injection (not always needed)
  18546. * $provide.value('greet', function(name){
  18547. * return 'Hello ' + name + '!';
  18548. * });
  18549. *
  18550. * // register a filter factory which uses the
  18551. * // greet service to demonstrate DI.
  18552. * $filterProvider.register('greet', function(greet){
  18553. * // return the filter function which uses the greet service
  18554. * // to generate salutation
  18555. * return function(text) {
  18556. * // filters need to be forgiving so check input validity
  18557. * return text && greet(text) || text;
  18558. * };
  18559. * });
  18560. * }
  18561. * ```
  18562. *
  18563. * The filter function is registered with the `$injector` under the filter name suffix with
  18564. * `Filter`.
  18565. *
  18566. * ```js
  18567. * it('should be the same instance', inject(
  18568. * function($filterProvider) {
  18569. * $filterProvider.register('reverse', function(){
  18570. * return ...;
  18571. * });
  18572. * },
  18573. * function($filter, reverseFilter) {
  18574. * expect($filter('reverse')).toBe(reverseFilter);
  18575. * });
  18576. * ```
  18577. *
  18578. *
  18579. * For more information about how angular filters work, and how to create your own filters, see
  18580. * {@link guide/filter Filters} in the Angular Developer Guide.
  18581. */
  18582. /**
  18583. * @ngdoc service
  18584. * @name $filter
  18585. * @kind function
  18586. * @description
  18587. * Filters are used for formatting data displayed to the user.
  18588. *
  18589. * They can be used in view templates, controllers or services.Angular comes
  18590. * with a collection of [built-in filters](api/ng/filter), but it is easy to
  18591. * define your own as well.
  18592. *
  18593. * The general syntax in templates is as follows:
  18594. *
  18595. * ```html
  18596. * {{ expression [| filter_name[:parameter_value] ... ] }}
  18597. * ```
  18598. *
  18599. * @param {String} name Name of the filter function to retrieve
  18600. * @return {Function} the filter function
  18601. * @example
  18602. <example name="$filter" module="filterExample">
  18603. <file name="index.html">
  18604. <div ng-controller="MainCtrl">
  18605. <h3>{{ originalText }}</h3>
  18606. <h3>{{ filteredText }}</h3>
  18607. </div>
  18608. </file>
  18609. <file name="script.js">
  18610. angular.module('filterExample', [])
  18611. .controller('MainCtrl', function($scope, $filter) {
  18612. $scope.originalText = 'hello';
  18613. $scope.filteredText = $filter('uppercase')($scope.originalText);
  18614. });
  18615. </file>
  18616. </example>
  18617. */
  18618. $FilterProvider.$inject = ['$provide'];
  18619. /** @this */
  18620. function $FilterProvider($provide) {
  18621. var suffix = 'Filter';
  18622. /**
  18623. * @ngdoc method
  18624. * @name $filterProvider#register
  18625. * @param {string|Object} name Name of the filter function, or an object map of filters where
  18626. * the keys are the filter names and the values are the filter factories.
  18627. *
  18628. * <div class="alert alert-warning">
  18629. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18630. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18631. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18632. * (`myapp_subsection_filterx`).
  18633. * </div>
  18634. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  18635. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  18636. * of the registered filter instances.
  18637. */
  18638. function register(name, factory) {
  18639. if (isObject(name)) {
  18640. var filters = {};
  18641. forEach(name, function(filter, key) {
  18642. filters[key] = register(key, filter);
  18643. });
  18644. return filters;
  18645. } else {
  18646. return $provide.factory(name + suffix, factory);
  18647. }
  18648. }
  18649. this.register = register;
  18650. this.$get = ['$injector', function($injector) {
  18651. return function(name) {
  18652. return $injector.get(name + suffix);
  18653. };
  18654. }];
  18655. ////////////////////////////////////////
  18656. /* global
  18657. currencyFilter: false,
  18658. dateFilter: false,
  18659. filterFilter: false,
  18660. jsonFilter: false,
  18661. limitToFilter: false,
  18662. lowercaseFilter: false,
  18663. numberFilter: false,
  18664. orderByFilter: false,
  18665. uppercaseFilter: false
  18666. */
  18667. register('currency', currencyFilter);
  18668. register('date', dateFilter);
  18669. register('filter', filterFilter);
  18670. register('json', jsonFilter);
  18671. register('limitTo', limitToFilter);
  18672. register('lowercase', lowercaseFilter);
  18673. register('number', numberFilter);
  18674. register('orderBy', orderByFilter);
  18675. register('uppercase', uppercaseFilter);
  18676. }
  18677. /**
  18678. * @ngdoc filter
  18679. * @name filter
  18680. * @kind function
  18681. *
  18682. * @description
  18683. * Selects a subset of items from `array` and returns it as a new array.
  18684. *
  18685. * @param {Array} array The source array.
  18686. * <div class="alert alert-info">
  18687. * **Note**: If the array contains objects that reference themselves, filtering is not possible.
  18688. * </div>
  18689. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  18690. * `array`.
  18691. *
  18692. * Can be one of:
  18693. *
  18694. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  18695. * objects with string properties in `array` that match this string will be returned. This also
  18696. * applies to nested object properties.
  18697. * The predicate can be negated by prefixing the string with `!`.
  18698. *
  18699. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  18700. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  18701. * which have property `name` containing "M" and property `phone` containing "1". A special
  18702. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  18703. * against any property of the object or its nested object properties. That's equivalent to the
  18704. * simple substring match with a `string` as described above. The special property name can be
  18705. * overwritten, using the `anyPropertyKey` parameter.
  18706. * The predicate can be negated by prefixing the string with `!`.
  18707. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  18708. * not containing "M".
  18709. *
  18710. * Note that a named property will match properties on the same level only, while the special
  18711. * `$` property will match properties on the same level or deeper. E.g. an array item like
  18712. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  18713. * **will** be matched by `{$: 'John'}`.
  18714. *
  18715. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  18716. * The function is called for each element of the array, with the element, its index, and
  18717. * the entire array itself as arguments.
  18718. *
  18719. * The final result is an array of those elements that the predicate returned true for.
  18720. *
  18721. * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
  18722. * determining if values retrieved using `expression` (when it is not a function) should be
  18723. * considered a match based on the the expected value (from the filter expression) and actual
  18724. * value (from the object in the array).
  18725. *
  18726. * Can be one of:
  18727. *
  18728. * - `function(actual, expected)`:
  18729. * The function will be given the object value and the predicate value to compare and
  18730. * should return true if both values should be considered equal.
  18731. *
  18732. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  18733. * This is essentially strict comparison of expected and actual.
  18734. *
  18735. * - `false`: A short hand for a function which will look for a substring match in a case
  18736. * insensitive way. Primitive values are converted to strings. Objects are not compared against
  18737. * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
  18738. *
  18739. *
  18740. * Defaults to `false`.
  18741. *
  18742. * @param {string} [anyPropertyKey] The special property name that matches against any property.
  18743. * By default `$`.
  18744. *
  18745. * @example
  18746. <example name="filter-filter">
  18747. <file name="index.html">
  18748. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  18749. {name:'Mary', phone:'800-BIG-MARY'},
  18750. {name:'Mike', phone:'555-4321'},
  18751. {name:'Adam', phone:'555-5678'},
  18752. {name:'Julie', phone:'555-8765'},
  18753. {name:'Juliette', phone:'555-5678'}]"></div>
  18754. <label>Search: <input ng-model="searchText"></label>
  18755. <table id="searchTextResults">
  18756. <tr><th>Name</th><th>Phone</th></tr>
  18757. <tr ng-repeat="friend in friends | filter:searchText">
  18758. <td>{{friend.name}}</td>
  18759. <td>{{friend.phone}}</td>
  18760. </tr>
  18761. </table>
  18762. <hr>
  18763. <label>Any: <input ng-model="search.$"></label> <br>
  18764. <label>Name only <input ng-model="search.name"></label><br>
  18765. <label>Phone only <input ng-model="search.phone"></label><br>
  18766. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  18767. <table id="searchObjResults">
  18768. <tr><th>Name</th><th>Phone</th></tr>
  18769. <tr ng-repeat="friendObj in friends | filter:search:strict">
  18770. <td>{{friendObj.name}}</td>
  18771. <td>{{friendObj.phone}}</td>
  18772. </tr>
  18773. </table>
  18774. </file>
  18775. <file name="protractor.js" type="protractor">
  18776. var expectFriendNames = function(expectedNames, key) {
  18777. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  18778. arr.forEach(function(wd, i) {
  18779. expect(wd.getText()).toMatch(expectedNames[i]);
  18780. });
  18781. });
  18782. };
  18783. it('should search across all fields when filtering with a string', function() {
  18784. var searchText = element(by.model('searchText'));
  18785. searchText.clear();
  18786. searchText.sendKeys('m');
  18787. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  18788. searchText.clear();
  18789. searchText.sendKeys('76');
  18790. expectFriendNames(['John', 'Julie'], 'friend');
  18791. });
  18792. it('should search in specific fields when filtering with a predicate object', function() {
  18793. var searchAny = element(by.model('search.$'));
  18794. searchAny.clear();
  18795. searchAny.sendKeys('i');
  18796. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  18797. });
  18798. it('should use a equal comparison when comparator is true', function() {
  18799. var searchName = element(by.model('search.name'));
  18800. var strict = element(by.model('strict'));
  18801. searchName.clear();
  18802. searchName.sendKeys('Julie');
  18803. strict.click();
  18804. expectFriendNames(['Julie'], 'friendObj');
  18805. });
  18806. </file>
  18807. </example>
  18808. */
  18809. function filterFilter() {
  18810. return function(array, expression, comparator, anyPropertyKey) {
  18811. if (!isArrayLike(array)) {
  18812. if (array == null) {
  18813. return array;
  18814. } else {
  18815. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  18816. }
  18817. }
  18818. anyPropertyKey = anyPropertyKey || '$';
  18819. var expressionType = getTypeForFilter(expression);
  18820. var predicateFn;
  18821. var matchAgainstAnyProp;
  18822. switch (expressionType) {
  18823. case 'function':
  18824. predicateFn = expression;
  18825. break;
  18826. case 'boolean':
  18827. case 'null':
  18828. case 'number':
  18829. case 'string':
  18830. matchAgainstAnyProp = true;
  18831. // falls through
  18832. case 'object':
  18833. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18834. break;
  18835. default:
  18836. return array;
  18837. }
  18838. return Array.prototype.filter.call(array, predicateFn);
  18839. };
  18840. }
  18841. // Helper functions for `filterFilter`
  18842. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  18843. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  18844. var predicateFn;
  18845. if (comparator === true) {
  18846. comparator = equals;
  18847. } else if (!isFunction(comparator)) {
  18848. comparator = function(actual, expected) {
  18849. if (isUndefined(actual)) {
  18850. // No substring matching against `undefined`
  18851. return false;
  18852. }
  18853. if ((actual === null) || (expected === null)) {
  18854. // No substring matching against `null`; only match against `null`
  18855. return actual === expected;
  18856. }
  18857. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  18858. // Should not compare primitives against objects, unless they have custom `toString` method
  18859. return false;
  18860. }
  18861. actual = lowercase('' + actual);
  18862. expected = lowercase('' + expected);
  18863. return actual.indexOf(expected) !== -1;
  18864. };
  18865. }
  18866. predicateFn = function(item) {
  18867. if (shouldMatchPrimitives && !isObject(item)) {
  18868. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  18869. }
  18870. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18871. };
  18872. return predicateFn;
  18873. }
  18874. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  18875. var actualType = getTypeForFilter(actual);
  18876. var expectedType = getTypeForFilter(expected);
  18877. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  18878. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  18879. } else if (isArray(actual)) {
  18880. // In case `actual` is an array, consider it a match
  18881. // if ANY of it's items matches `expected`
  18882. return actual.some(function(item) {
  18883. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  18884. });
  18885. }
  18886. switch (actualType) {
  18887. case 'object':
  18888. var key;
  18889. if (matchAgainstAnyProp) {
  18890. for (key in actual) {
  18891. // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined
  18892. // See: https://github.com/angular/angular.js/issues/15644
  18893. if (key.charAt && (key.charAt(0) !== '$') &&
  18894. deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  18895. return true;
  18896. }
  18897. }
  18898. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  18899. } else if (expectedType === 'object') {
  18900. for (key in expected) {
  18901. var expectedVal = expected[key];
  18902. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  18903. continue;
  18904. }
  18905. var matchAnyProperty = key === anyPropertyKey;
  18906. var actualVal = matchAnyProperty ? actual : actual[key];
  18907. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  18908. return false;
  18909. }
  18910. }
  18911. return true;
  18912. } else {
  18913. return comparator(actual, expected);
  18914. }
  18915. case 'function':
  18916. return false;
  18917. default:
  18918. return comparator(actual, expected);
  18919. }
  18920. }
  18921. // Used for easily differentiating between `null` and actual `object`
  18922. function getTypeForFilter(val) {
  18923. return (val === null) ? 'null' : typeof val;
  18924. }
  18925. var MAX_DIGITS = 22;
  18926. var DECIMAL_SEP = '.';
  18927. var ZERO_CHAR = '0';
  18928. /**
  18929. * @ngdoc filter
  18930. * @name currency
  18931. * @kind function
  18932. *
  18933. * @description
  18934. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  18935. * symbol for current locale is used.
  18936. *
  18937. * @param {number} amount Input to filter.
  18938. * @param {string=} symbol Currency symbol or identifier to be displayed.
  18939. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  18940. * @returns {string} Formatted number.
  18941. *
  18942. *
  18943. * @example
  18944. <example module="currencyExample" name="currency-filter">
  18945. <file name="index.html">
  18946. <script>
  18947. angular.module('currencyExample', [])
  18948. .controller('ExampleController', ['$scope', function($scope) {
  18949. $scope.amount = 1234.56;
  18950. }]);
  18951. </script>
  18952. <div ng-controller="ExampleController">
  18953. <input type="number" ng-model="amount" aria-label="amount"> <br>
  18954. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  18955. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
  18956. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  18957. </div>
  18958. </file>
  18959. <file name="protractor.js" type="protractor">
  18960. it('should init with 1234.56', function() {
  18961. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  18962. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  18963. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  18964. });
  18965. it('should update', function() {
  18966. if (browser.params.browser === 'safari') {
  18967. // Safari does not understand the minus key. See
  18968. // https://github.com/angular/protractor/issues/481
  18969. return;
  18970. }
  18971. element(by.model('amount')).clear();
  18972. element(by.model('amount')).sendKeys('-1234');
  18973. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  18974. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  18975. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  18976. });
  18977. </file>
  18978. </example>
  18979. */
  18980. currencyFilter.$inject = ['$locale'];
  18981. function currencyFilter($locale) {
  18982. var formats = $locale.NUMBER_FORMATS;
  18983. return function(amount, currencySymbol, fractionSize) {
  18984. if (isUndefined(currencySymbol)) {
  18985. currencySymbol = formats.CURRENCY_SYM;
  18986. }
  18987. if (isUndefined(fractionSize)) {
  18988. fractionSize = formats.PATTERNS[1].maxFrac;
  18989. }
  18990. // if null or undefined pass it through
  18991. return (amount == null)
  18992. ? amount
  18993. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  18994. replace(/\u00A4/g, currencySymbol);
  18995. };
  18996. }
  18997. /**
  18998. * @ngdoc filter
  18999. * @name number
  19000. * @kind function
  19001. *
  19002. * @description
  19003. * Formats a number as text.
  19004. *
  19005. * If the input is null or undefined, it will just be returned.
  19006. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  19007. * If the input is not a number an empty string is returned.
  19008. *
  19009. *
  19010. * @param {number|string} number Number to format.
  19011. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  19012. * If this is not provided then the fraction size is computed from the current locale's number
  19013. * formatting pattern. In the case of the default locale, it will be 3.
  19014. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  19015. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  19016. * include "," group separators after each third digit).
  19017. *
  19018. * @example
  19019. <example module="numberFilterExample" name="number-filter">
  19020. <file name="index.html">
  19021. <script>
  19022. angular.module('numberFilterExample', [])
  19023. .controller('ExampleController', ['$scope', function($scope) {
  19024. $scope.val = 1234.56789;
  19025. }]);
  19026. </script>
  19027. <div ng-controller="ExampleController">
  19028. <label>Enter number: <input ng-model='val'></label><br>
  19029. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  19030. No fractions: <span>{{val | number:0}}</span><br>
  19031. Negative number: <span>{{-val | number:4}}</span>
  19032. </div>
  19033. </file>
  19034. <file name="protractor.js" type="protractor">
  19035. it('should format numbers', function() {
  19036. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  19037. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  19038. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  19039. });
  19040. it('should update', function() {
  19041. element(by.model('val')).clear();
  19042. element(by.model('val')).sendKeys('3374.333');
  19043. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  19044. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  19045. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  19046. });
  19047. </file>
  19048. </example>
  19049. */
  19050. numberFilter.$inject = ['$locale'];
  19051. function numberFilter($locale) {
  19052. var formats = $locale.NUMBER_FORMATS;
  19053. return function(number, fractionSize) {
  19054. // if null or undefined pass it through
  19055. return (number == null)
  19056. ? number
  19057. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  19058. fractionSize);
  19059. };
  19060. }
  19061. /**
  19062. * Parse a number (as a string) into three components that can be used
  19063. * for formatting the number.
  19064. *
  19065. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  19066. *
  19067. * @param {string} numStr The number to parse
  19068. * @return {object} An object describing this number, containing the following keys:
  19069. * - d : an array of digits containing leading zeros as necessary
  19070. * - i : the number of the digits in `d` that are to the left of the decimal point
  19071. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  19072. *
  19073. */
  19074. function parse(numStr) {
  19075. var exponent = 0, digits, numberOfIntegerDigits;
  19076. var i, j, zeros;
  19077. // Decimal point?
  19078. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  19079. numStr = numStr.replace(DECIMAL_SEP, '');
  19080. }
  19081. // Exponential form?
  19082. if ((i = numStr.search(/e/i)) > 0) {
  19083. // Work out the exponent.
  19084. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  19085. numberOfIntegerDigits += +numStr.slice(i + 1);
  19086. numStr = numStr.substring(0, i);
  19087. } else if (numberOfIntegerDigits < 0) {
  19088. // There was no decimal point or exponent so it is an integer.
  19089. numberOfIntegerDigits = numStr.length;
  19090. }
  19091. // Count the number of leading zeros.
  19092. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
  19093. if (i === (zeros = numStr.length)) {
  19094. // The digits are all zero.
  19095. digits = [0];
  19096. numberOfIntegerDigits = 1;
  19097. } else {
  19098. // Count the number of trailing zeros
  19099. zeros--;
  19100. while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
  19101. // Trailing zeros are insignificant so ignore them
  19102. numberOfIntegerDigits -= i;
  19103. digits = [];
  19104. // Convert string to array of digits without leading/trailing zeros.
  19105. for (j = 0; i <= zeros; i++, j++) {
  19106. digits[j] = +numStr.charAt(i);
  19107. }
  19108. }
  19109. // If the number overflows the maximum allowed digits then use an exponent.
  19110. if (numberOfIntegerDigits > MAX_DIGITS) {
  19111. digits = digits.splice(0, MAX_DIGITS - 1);
  19112. exponent = numberOfIntegerDigits - 1;
  19113. numberOfIntegerDigits = 1;
  19114. }
  19115. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  19116. }
  19117. /**
  19118. * Round the parsed number to the specified number of decimal places
  19119. * This function changed the parsedNumber in-place
  19120. */
  19121. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  19122. var digits = parsedNumber.d;
  19123. var fractionLen = digits.length - parsedNumber.i;
  19124. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  19125. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  19126. // The index of the digit to where rounding is to occur
  19127. var roundAt = fractionSize + parsedNumber.i;
  19128. var digit = digits[roundAt];
  19129. if (roundAt > 0) {
  19130. // Drop fractional digits beyond `roundAt`
  19131. digits.splice(Math.max(parsedNumber.i, roundAt));
  19132. // Set non-fractional digits beyond `roundAt` to 0
  19133. for (var j = roundAt; j < digits.length; j++) {
  19134. digits[j] = 0;
  19135. }
  19136. } else {
  19137. // We rounded to zero so reset the parsedNumber
  19138. fractionLen = Math.max(0, fractionLen);
  19139. parsedNumber.i = 1;
  19140. digits.length = Math.max(1, roundAt = fractionSize + 1);
  19141. digits[0] = 0;
  19142. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  19143. }
  19144. if (digit >= 5) {
  19145. if (roundAt - 1 < 0) {
  19146. for (var k = 0; k > roundAt; k--) {
  19147. digits.unshift(0);
  19148. parsedNumber.i++;
  19149. }
  19150. digits.unshift(1);
  19151. parsedNumber.i++;
  19152. } else {
  19153. digits[roundAt - 1]++;
  19154. }
  19155. }
  19156. // Pad out with zeros to get the required fraction length
  19157. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  19158. // Do any carrying, e.g. a digit was rounded up to 10
  19159. var carry = digits.reduceRight(function(carry, d, i, digits) {
  19160. d = d + carry;
  19161. digits[i] = d % 10;
  19162. return Math.floor(d / 10);
  19163. }, 0);
  19164. if (carry) {
  19165. digits.unshift(carry);
  19166. parsedNumber.i++;
  19167. }
  19168. }
  19169. /**
  19170. * Format a number into a string
  19171. * @param {number} number The number to format
  19172. * @param {{
  19173. * minFrac, // the minimum number of digits required in the fraction part of the number
  19174. * maxFrac, // the maximum number of digits required in the fraction part of the number
  19175. * gSize, // number of digits in each group of separated digits
  19176. * lgSize, // number of digits in the last group of digits before the decimal separator
  19177. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  19178. * posPre, // the string to go in front of a positive number
  19179. * negSuf, // the string to go after a negative number (e.g. `)`)
  19180. * posSuf // the string to go after a positive number
  19181. * }} pattern
  19182. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  19183. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  19184. * @param {[type]} fractionSize The size of the fractional part of the number
  19185. * @return {string} The number formatted as a string
  19186. */
  19187. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  19188. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  19189. var isInfinity = !isFinite(number);
  19190. var isZero = false;
  19191. var numStr = Math.abs(number) + '',
  19192. formattedText = '',
  19193. parsedNumber;
  19194. if (isInfinity) {
  19195. formattedText = '\u221e';
  19196. } else {
  19197. parsedNumber = parse(numStr);
  19198. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  19199. var digits = parsedNumber.d;
  19200. var integerLen = parsedNumber.i;
  19201. var exponent = parsedNumber.e;
  19202. var decimals = [];
  19203. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  19204. // pad zeros for small numbers
  19205. while (integerLen < 0) {
  19206. digits.unshift(0);
  19207. integerLen++;
  19208. }
  19209. // extract decimals digits
  19210. if (integerLen > 0) {
  19211. decimals = digits.splice(integerLen, digits.length);
  19212. } else {
  19213. decimals = digits;
  19214. digits = [0];
  19215. }
  19216. // format the integer digits with grouping separators
  19217. var groups = [];
  19218. if (digits.length >= pattern.lgSize) {
  19219. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  19220. }
  19221. while (digits.length > pattern.gSize) {
  19222. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  19223. }
  19224. if (digits.length) {
  19225. groups.unshift(digits.join(''));
  19226. }
  19227. formattedText = groups.join(groupSep);
  19228. // append the decimal digits
  19229. if (decimals.length) {
  19230. formattedText += decimalSep + decimals.join('');
  19231. }
  19232. if (exponent) {
  19233. formattedText += 'e+' + exponent;
  19234. }
  19235. }
  19236. if (number < 0 && !isZero) {
  19237. return pattern.negPre + formattedText + pattern.negSuf;
  19238. } else {
  19239. return pattern.posPre + formattedText + pattern.posSuf;
  19240. }
  19241. }
  19242. function padNumber(num, digits, trim, negWrap) {
  19243. var neg = '';
  19244. if (num < 0 || (negWrap && num <= 0)) {
  19245. if (negWrap) {
  19246. num = -num + 1;
  19247. } else {
  19248. num = -num;
  19249. neg = '-';
  19250. }
  19251. }
  19252. num = '' + num;
  19253. while (num.length < digits) num = ZERO_CHAR + num;
  19254. if (trim) {
  19255. num = num.substr(num.length - digits);
  19256. }
  19257. return neg + num;
  19258. }
  19259. function dateGetter(name, size, offset, trim, negWrap) {
  19260. offset = offset || 0;
  19261. return function(date) {
  19262. var value = date['get' + name]();
  19263. if (offset > 0 || value > -offset) {
  19264. value += offset;
  19265. }
  19266. if (value === 0 && offset === -12) value = 12;
  19267. return padNumber(value, size, trim, negWrap);
  19268. };
  19269. }
  19270. function dateStrGetter(name, shortForm, standAlone) {
  19271. return function(date, formats) {
  19272. var value = date['get' + name]();
  19273. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  19274. var get = uppercase(propPrefix + name);
  19275. return formats[get][value];
  19276. };
  19277. }
  19278. function timeZoneGetter(date, formats, offset) {
  19279. var zone = -1 * offset;
  19280. var paddedZone = (zone >= 0) ? '+' : '';
  19281. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  19282. padNumber(Math.abs(zone % 60), 2);
  19283. return paddedZone;
  19284. }
  19285. function getFirstThursdayOfYear(year) {
  19286. // 0 = index of January
  19287. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  19288. // 4 = index of Thursday (+1 to account for 1st = 5)
  19289. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  19290. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  19291. }
  19292. function getThursdayThisWeek(datetime) {
  19293. return new Date(datetime.getFullYear(), datetime.getMonth(),
  19294. // 4 = index of Thursday
  19295. datetime.getDate() + (4 - datetime.getDay()));
  19296. }
  19297. function weekGetter(size) {
  19298. return function(date) {
  19299. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  19300. thisThurs = getThursdayThisWeek(date);
  19301. var diff = +thisThurs - +firstThurs,
  19302. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  19303. return padNumber(result, size);
  19304. };
  19305. }
  19306. function ampmGetter(date, formats) {
  19307. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  19308. }
  19309. function eraGetter(date, formats) {
  19310. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  19311. }
  19312. function longEraGetter(date, formats) {
  19313. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  19314. }
  19315. var DATE_FORMATS = {
  19316. yyyy: dateGetter('FullYear', 4, 0, false, true),
  19317. yy: dateGetter('FullYear', 2, 0, true, true),
  19318. y: dateGetter('FullYear', 1, 0, false, true),
  19319. MMMM: dateStrGetter('Month'),
  19320. MMM: dateStrGetter('Month', true),
  19321. MM: dateGetter('Month', 2, 1),
  19322. M: dateGetter('Month', 1, 1),
  19323. LLLL: dateStrGetter('Month', false, true),
  19324. dd: dateGetter('Date', 2),
  19325. d: dateGetter('Date', 1),
  19326. HH: dateGetter('Hours', 2),
  19327. H: dateGetter('Hours', 1),
  19328. hh: dateGetter('Hours', 2, -12),
  19329. h: dateGetter('Hours', 1, -12),
  19330. mm: dateGetter('Minutes', 2),
  19331. m: dateGetter('Minutes', 1),
  19332. ss: dateGetter('Seconds', 2),
  19333. s: dateGetter('Seconds', 1),
  19334. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  19335. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  19336. sss: dateGetter('Milliseconds', 3),
  19337. EEEE: dateStrGetter('Day'),
  19338. EEE: dateStrGetter('Day', true),
  19339. a: ampmGetter,
  19340. Z: timeZoneGetter,
  19341. ww: weekGetter(2),
  19342. w: weekGetter(1),
  19343. G: eraGetter,
  19344. GG: eraGetter,
  19345. GGG: eraGetter,
  19346. GGGG: longEraGetter
  19347. };
  19348. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/,
  19349. NUMBER_STRING = /^-?\d+$/;
  19350. /**
  19351. * @ngdoc filter
  19352. * @name date
  19353. * @kind function
  19354. *
  19355. * @description
  19356. * Formats `date` to a string based on the requested `format`.
  19357. *
  19358. * `format` string can be composed of the following elements:
  19359. *
  19360. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  19361. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  19362. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  19363. * * `'MMMM'`: Month in year (January-December)
  19364. * * `'MMM'`: Month in year (Jan-Dec)
  19365. * * `'MM'`: Month in year, padded (01-12)
  19366. * * `'M'`: Month in year (1-12)
  19367. * * `'LLLL'`: Stand-alone month in year (January-December)
  19368. * * `'dd'`: Day in month, padded (01-31)
  19369. * * `'d'`: Day in month (1-31)
  19370. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  19371. * * `'EEE'`: Day in Week, (Sun-Sat)
  19372. * * `'HH'`: Hour in day, padded (00-23)
  19373. * * `'H'`: Hour in day (0-23)
  19374. * * `'hh'`: Hour in AM/PM, padded (01-12)
  19375. * * `'h'`: Hour in AM/PM, (1-12)
  19376. * * `'mm'`: Minute in hour, padded (00-59)
  19377. * * `'m'`: Minute in hour (0-59)
  19378. * * `'ss'`: Second in minute, padded (00-59)
  19379. * * `'s'`: Second in minute (0-59)
  19380. * * `'sss'`: Millisecond in second, padded (000-999)
  19381. * * `'a'`: AM/PM marker
  19382. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  19383. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  19384. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  19385. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  19386. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  19387. *
  19388. * `format` string can also be one of the following predefined
  19389. * {@link guide/i18n localizable formats}:
  19390. *
  19391. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  19392. * (e.g. Sep 3, 2010 12:05:08 PM)
  19393. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  19394. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  19395. * (e.g. Friday, September 3, 2010)
  19396. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  19397. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  19398. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  19399. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  19400. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  19401. *
  19402. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  19403. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  19404. * (e.g. `"h 'o''clock'"`).
  19405. *
  19406. * Any other characters in the `format` string will be output as-is.
  19407. *
  19408. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  19409. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  19410. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  19411. * specified in the string input, the time is considered to be in the local timezone.
  19412. * @param {string=} format Formatting rules (see Description). If not specified,
  19413. * `mediumDate` is used.
  19414. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  19415. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  19416. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  19417. * If not specified, the timezone of the browser will be used.
  19418. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  19419. *
  19420. * @example
  19421. <example name="filter-date">
  19422. <file name="index.html">
  19423. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  19424. <span>{{1288323623006 | date:'medium'}}</span><br>
  19425. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  19426. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  19427. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  19428. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  19429. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  19430. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  19431. </file>
  19432. <file name="protractor.js" type="protractor">
  19433. it('should format date', function() {
  19434. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  19435. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  19436. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  19437. toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
  19438. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  19439. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  19440. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  19441. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  19442. });
  19443. </file>
  19444. </example>
  19445. */
  19446. dateFilter.$inject = ['$locale'];
  19447. function dateFilter($locale) {
  19448. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  19449. // 1 2 3 4 5 6 7 8 9 10 11
  19450. function jsonStringToDate(string) {
  19451. var match;
  19452. if ((match = string.match(R_ISO8601_STR))) {
  19453. var date = new Date(0),
  19454. tzHour = 0,
  19455. tzMin = 0,
  19456. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  19457. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  19458. if (match[9]) {
  19459. tzHour = toInt(match[9] + match[10]);
  19460. tzMin = toInt(match[9] + match[11]);
  19461. }
  19462. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  19463. var h = toInt(match[4] || 0) - tzHour;
  19464. var m = toInt(match[5] || 0) - tzMin;
  19465. var s = toInt(match[6] || 0);
  19466. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  19467. timeSetter.call(date, h, m, s, ms);
  19468. return date;
  19469. }
  19470. return string;
  19471. }
  19472. return function(date, format, timezone) {
  19473. var text = '',
  19474. parts = [],
  19475. fn, match;
  19476. format = format || 'mediumDate';
  19477. format = $locale.DATETIME_FORMATS[format] || format;
  19478. if (isString(date)) {
  19479. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  19480. }
  19481. if (isNumber(date)) {
  19482. date = new Date(date);
  19483. }
  19484. if (!isDate(date) || !isFinite(date.getTime())) {
  19485. return date;
  19486. }
  19487. while (format) {
  19488. match = DATE_FORMATS_SPLIT.exec(format);
  19489. if (match) {
  19490. parts = concat(parts, match, 1);
  19491. format = parts.pop();
  19492. } else {
  19493. parts.push(format);
  19494. format = null;
  19495. }
  19496. }
  19497. var dateTimezoneOffset = date.getTimezoneOffset();
  19498. if (timezone) {
  19499. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  19500. date = convertTimezoneToLocal(date, timezone, true);
  19501. }
  19502. forEach(parts, function(value) {
  19503. fn = DATE_FORMATS[value];
  19504. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  19505. : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  19506. });
  19507. return text;
  19508. };
  19509. }
  19510. /**
  19511. * @ngdoc filter
  19512. * @name json
  19513. * @kind function
  19514. *
  19515. * @description
  19516. * Allows you to convert a JavaScript object into JSON string.
  19517. *
  19518. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  19519. * the binding is automatically converted to JSON.
  19520. *
  19521. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  19522. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  19523. * @returns {string} JSON string.
  19524. *
  19525. *
  19526. * @example
  19527. <example name="filter-json">
  19528. <file name="index.html">
  19529. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  19530. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  19531. </file>
  19532. <file name="protractor.js" type="protractor">
  19533. it('should jsonify filtered objects', function() {
  19534. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
  19535. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
  19536. });
  19537. </file>
  19538. </example>
  19539. *
  19540. */
  19541. function jsonFilter() {
  19542. return function(object, spacing) {
  19543. if (isUndefined(spacing)) {
  19544. spacing = 2;
  19545. }
  19546. return toJson(object, spacing);
  19547. };
  19548. }
  19549. /**
  19550. * @ngdoc filter
  19551. * @name lowercase
  19552. * @kind function
  19553. * @description
  19554. * Converts string to lowercase.
  19555. * @see angular.lowercase
  19556. */
  19557. var lowercaseFilter = valueFn(lowercase);
  19558. /**
  19559. * @ngdoc filter
  19560. * @name uppercase
  19561. * @kind function
  19562. * @description
  19563. * Converts string to uppercase.
  19564. * @see angular.uppercase
  19565. */
  19566. var uppercaseFilter = valueFn(uppercase);
  19567. /**
  19568. * @ngdoc filter
  19569. * @name limitTo
  19570. * @kind function
  19571. *
  19572. * @description
  19573. * Creates a new array or string containing only a specified number of elements. The elements are
  19574. * taken from either the beginning or the end of the source array, string or number, as specified by
  19575. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  19576. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  19577. * it is converted to a string.
  19578. *
  19579. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  19580. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  19581. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  19582. * If the number is negative, `limit` number of items from the end of the source array/string
  19583. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  19584. * the input will be returned unchanged.
  19585. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  19586. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  19587. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  19588. * less than `limit` elements.
  19589. *
  19590. * @example
  19591. <example module="limitToExample" name="limit-to-filter">
  19592. <file name="index.html">
  19593. <script>
  19594. angular.module('limitToExample', [])
  19595. .controller('ExampleController', ['$scope', function($scope) {
  19596. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  19597. $scope.letters = "abcdefghi";
  19598. $scope.longNumber = 2345432342;
  19599. $scope.numLimit = 3;
  19600. $scope.letterLimit = 3;
  19601. $scope.longNumberLimit = 3;
  19602. }]);
  19603. </script>
  19604. <div ng-controller="ExampleController">
  19605. <label>
  19606. Limit {{numbers}} to:
  19607. <input type="number" step="1" ng-model="numLimit">
  19608. </label>
  19609. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  19610. <label>
  19611. Limit {{letters}} to:
  19612. <input type="number" step="1" ng-model="letterLimit">
  19613. </label>
  19614. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  19615. <label>
  19616. Limit {{longNumber}} to:
  19617. <input type="number" step="1" ng-model="longNumberLimit">
  19618. </label>
  19619. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  19620. </div>
  19621. </file>
  19622. <file name="protractor.js" type="protractor">
  19623. var numLimitInput = element(by.model('numLimit'));
  19624. var letterLimitInput = element(by.model('letterLimit'));
  19625. var longNumberLimitInput = element(by.model('longNumberLimit'));
  19626. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  19627. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  19628. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  19629. it('should limit the number array to first three items', function() {
  19630. expect(numLimitInput.getAttribute('value')).toBe('3');
  19631. expect(letterLimitInput.getAttribute('value')).toBe('3');
  19632. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  19633. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  19634. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  19635. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  19636. });
  19637. // There is a bug in safari and protractor that doesn't like the minus key
  19638. // it('should update the output when -3 is entered', function() {
  19639. // numLimitInput.clear();
  19640. // numLimitInput.sendKeys('-3');
  19641. // letterLimitInput.clear();
  19642. // letterLimitInput.sendKeys('-3');
  19643. // longNumberLimitInput.clear();
  19644. // longNumberLimitInput.sendKeys('-3');
  19645. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  19646. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  19647. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  19648. // });
  19649. it('should not exceed the maximum size of input array', function() {
  19650. numLimitInput.clear();
  19651. numLimitInput.sendKeys('100');
  19652. letterLimitInput.clear();
  19653. letterLimitInput.sendKeys('100');
  19654. longNumberLimitInput.clear();
  19655. longNumberLimitInput.sendKeys('100');
  19656. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  19657. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  19658. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  19659. });
  19660. </file>
  19661. </example>
  19662. */
  19663. function limitToFilter() {
  19664. return function(input, limit, begin) {
  19665. if (Math.abs(Number(limit)) === Infinity) {
  19666. limit = Number(limit);
  19667. } else {
  19668. limit = toInt(limit);
  19669. }
  19670. if (isNumberNaN(limit)) return input;
  19671. if (isNumber(input)) input = input.toString();
  19672. if (!isArrayLike(input)) return input;
  19673. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  19674. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  19675. if (limit >= 0) {
  19676. return sliceFn(input, begin, begin + limit);
  19677. } else {
  19678. if (begin === 0) {
  19679. return sliceFn(input, limit, input.length);
  19680. } else {
  19681. return sliceFn(input, Math.max(0, begin + limit), begin);
  19682. }
  19683. }
  19684. };
  19685. }
  19686. function sliceFn(input, begin, end) {
  19687. if (isString(input)) return input.slice(begin, end);
  19688. return slice.call(input, begin, end);
  19689. }
  19690. /**
  19691. * @ngdoc filter
  19692. * @name orderBy
  19693. * @kind function
  19694. *
  19695. * @description
  19696. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  19697. * function based on the values computed using the `expression` predicate.
  19698. *
  19699. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  19700. * `[{id: 'bar'}, {id: 'foo'}]`.
  19701. *
  19702. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  19703. * String, etc).
  19704. *
  19705. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  19706. * for the preceding one. The `expression` is evaluated against each item and the output is used
  19707. * for comparing with other items.
  19708. *
  19709. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  19710. * ascending order.
  19711. *
  19712. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  19713. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  19714. * strings alphabetically).
  19715. *
  19716. * ### Under the hood
  19717. *
  19718. * Ordering the specified `collection` happens in two phases:
  19719. *
  19720. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  19721. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  19722. * through a predicate that extracts the value of the `label` property, would be transformed to:
  19723. * ```
  19724. * {
  19725. * value: 'foo',
  19726. * type: 'string',
  19727. * index: ...
  19728. * }
  19729. * ```
  19730. * 2. The comparator function is used to sort the items, based on the derived values, types and
  19731. * indices.
  19732. *
  19733. * If you use a custom comparator, it will be called with pairs of objects of the form
  19734. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  19735. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  19736. * second, or `1` otherwise.
  19737. *
  19738. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  19739. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  19740. * dummy predicate that returns the item's index as `value`.
  19741. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  19742. *
  19743. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  19744. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  19745. * it to the comparator. The following rules govern the conversion:
  19746. *
  19747. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  19748. * used instead.<br />
  19749. * (If the object has a `valueOf()` method that returns another object, then the returned object
  19750. * will be used in subsequent steps.)
  19751. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  19752. * returns a primitive, its return value will be used instead.<br />
  19753. * (If the object has a `toString()` method that returns another object, then the returned object
  19754. * will be used in subsequent steps.)
  19755. * 3. No conversion; the object itself is used.
  19756. *
  19757. * ### The default comparator
  19758. *
  19759. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  19760. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  19761. * using their index in the original collection, and sorts values of different types by type.
  19762. *
  19763. * More specifically, it follows these steps to determine the relative order of items:
  19764. *
  19765. * 1. If the compared values are of different types, compare the types themselves alphabetically.
  19766. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  19767. * locale-insensitive way.
  19768. * 3. If both values are objects, compare their indices instead.
  19769. * 4. Otherwise, return:
  19770. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  19771. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  19772. * - `1`, otherwise.
  19773. *
  19774. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  19775. * saved as numbers and not strings.
  19776. * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e.
  19777. * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to
  19778. * other values.
  19779. *
  19780. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  19781. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  19782. * predicates) to be used by the comparator to determine the order of elements.
  19783. *
  19784. * Can be one of:
  19785. *
  19786. * - `Function`: A getter function. This function will be called with each item as argument and
  19787. * the return value will be used for sorting.
  19788. * - `string`: An Angular expression. This expression will be evaluated against each item and the
  19789. * result will be used for sorting. For example, use `'label'` to sort by a property called
  19790. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  19791. * property.<br />
  19792. * (The result of a constant expression is interpreted as a property name to be used for
  19793. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  19794. * property called `special name`.)<br />
  19795. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  19796. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  19797. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  19798. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  19799. * relative order of two items, the next predicate is used as a tie-breaker.
  19800. *
  19801. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  19802. *
  19803. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  19804. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  19805. * value pairs. If omitted, the built-in comparator will be used.
  19806. *
  19807. * @returns {Array} - The sorted array.
  19808. *
  19809. *
  19810. * @example
  19811. * ### Ordering a table with `ngRepeat`
  19812. *
  19813. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  19814. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  19815. * it defaults to the built-in comparator.
  19816. *
  19817. <example name="orderBy-static" module="orderByExample1">
  19818. <file name="index.html">
  19819. <div ng-controller="ExampleController">
  19820. <table class="friends">
  19821. <tr>
  19822. <th>Name</th>
  19823. <th>Phone Number</th>
  19824. <th>Age</th>
  19825. </tr>
  19826. <tr ng-repeat="friend in friends | orderBy:'-age'">
  19827. <td>{{friend.name}}</td>
  19828. <td>{{friend.phone}}</td>
  19829. <td>{{friend.age}}</td>
  19830. </tr>
  19831. </table>
  19832. </div>
  19833. </file>
  19834. <file name="script.js">
  19835. angular.module('orderByExample1', [])
  19836. .controller('ExampleController', ['$scope', function($scope) {
  19837. $scope.friends = [
  19838. {name: 'John', phone: '555-1212', age: 10},
  19839. {name: 'Mary', phone: '555-9876', age: 19},
  19840. {name: 'Mike', phone: '555-4321', age: 21},
  19841. {name: 'Adam', phone: '555-5678', age: 35},
  19842. {name: 'Julie', phone: '555-8765', age: 29}
  19843. ];
  19844. }]);
  19845. </file>
  19846. <file name="style.css">
  19847. .friends {
  19848. border-collapse: collapse;
  19849. }
  19850. .friends th {
  19851. border-bottom: 1px solid;
  19852. }
  19853. .friends td, .friends th {
  19854. border-left: 1px solid;
  19855. padding: 5px 10px;
  19856. }
  19857. .friends td:first-child, .friends th:first-child {
  19858. border-left: none;
  19859. }
  19860. </file>
  19861. <file name="protractor.js" type="protractor">
  19862. // Element locators
  19863. var names = element.all(by.repeater('friends').column('friend.name'));
  19864. it('should sort friends by age in reverse order', function() {
  19865. expect(names.get(0).getText()).toBe('Adam');
  19866. expect(names.get(1).getText()).toBe('Julie');
  19867. expect(names.get(2).getText()).toBe('Mike');
  19868. expect(names.get(3).getText()).toBe('Mary');
  19869. expect(names.get(4).getText()).toBe('John');
  19870. });
  19871. </file>
  19872. </example>
  19873. * <hr />
  19874. *
  19875. * @example
  19876. * ### Changing parameters dynamically
  19877. *
  19878. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  19879. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  19880. *
  19881. <example name="orderBy-dynamic" module="orderByExample2">
  19882. <file name="index.html">
  19883. <div ng-controller="ExampleController">
  19884. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19885. <hr/>
  19886. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  19887. <hr/>
  19888. <table class="friends">
  19889. <tr>
  19890. <th>
  19891. <button ng-click="sortBy('name')">Name</button>
  19892. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19893. </th>
  19894. <th>
  19895. <button ng-click="sortBy('phone')">Phone Number</button>
  19896. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19897. </th>
  19898. <th>
  19899. <button ng-click="sortBy('age')">Age</button>
  19900. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19901. </th>
  19902. </tr>
  19903. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  19904. <td>{{friend.name}}</td>
  19905. <td>{{friend.phone}}</td>
  19906. <td>{{friend.age}}</td>
  19907. </tr>
  19908. </table>
  19909. </div>
  19910. </file>
  19911. <file name="script.js">
  19912. angular.module('orderByExample2', [])
  19913. .controller('ExampleController', ['$scope', function($scope) {
  19914. var friends = [
  19915. {name: 'John', phone: '555-1212', age: 10},
  19916. {name: 'Mary', phone: '555-9876', age: 19},
  19917. {name: 'Mike', phone: '555-4321', age: 21},
  19918. {name: 'Adam', phone: '555-5678', age: 35},
  19919. {name: 'Julie', phone: '555-8765', age: 29}
  19920. ];
  19921. $scope.propertyName = 'age';
  19922. $scope.reverse = true;
  19923. $scope.friends = friends;
  19924. $scope.sortBy = function(propertyName) {
  19925. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  19926. $scope.propertyName = propertyName;
  19927. };
  19928. }]);
  19929. </file>
  19930. <file name="style.css">
  19931. .friends {
  19932. border-collapse: collapse;
  19933. }
  19934. .friends th {
  19935. border-bottom: 1px solid;
  19936. }
  19937. .friends td, .friends th {
  19938. border-left: 1px solid;
  19939. padding: 5px 10px;
  19940. }
  19941. .friends td:first-child, .friends th:first-child {
  19942. border-left: none;
  19943. }
  19944. .sortorder:after {
  19945. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19946. }
  19947. .sortorder.reverse:after {
  19948. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19949. }
  19950. </file>
  19951. <file name="protractor.js" type="protractor">
  19952. // Element locators
  19953. var unsortButton = element(by.partialButtonText('unsorted'));
  19954. var nameHeader = element(by.partialButtonText('Name'));
  19955. var phoneHeader = element(by.partialButtonText('Phone'));
  19956. var ageHeader = element(by.partialButtonText('Age'));
  19957. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19958. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19959. it('should sort friends by some property, when clicking on the column header', function() {
  19960. expect(firstName.getText()).toBe('Adam');
  19961. expect(lastName.getText()).toBe('John');
  19962. phoneHeader.click();
  19963. expect(firstName.getText()).toBe('John');
  19964. expect(lastName.getText()).toBe('Mary');
  19965. nameHeader.click();
  19966. expect(firstName.getText()).toBe('Adam');
  19967. expect(lastName.getText()).toBe('Mike');
  19968. ageHeader.click();
  19969. expect(firstName.getText()).toBe('John');
  19970. expect(lastName.getText()).toBe('Adam');
  19971. });
  19972. it('should sort friends in reverse order, when clicking on the same column', function() {
  19973. expect(firstName.getText()).toBe('Adam');
  19974. expect(lastName.getText()).toBe('John');
  19975. ageHeader.click();
  19976. expect(firstName.getText()).toBe('John');
  19977. expect(lastName.getText()).toBe('Adam');
  19978. ageHeader.click();
  19979. expect(firstName.getText()).toBe('Adam');
  19980. expect(lastName.getText()).toBe('John');
  19981. });
  19982. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19983. expect(firstName.getText()).toBe('Adam');
  19984. expect(lastName.getText()).toBe('John');
  19985. unsortButton.click();
  19986. expect(firstName.getText()).toBe('John');
  19987. expect(lastName.getText()).toBe('Julie');
  19988. });
  19989. </file>
  19990. </example>
  19991. * <hr />
  19992. *
  19993. * @example
  19994. * ### Using `orderBy` inside a controller
  19995. *
  19996. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  19997. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  19998. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  19999. *
  20000. <example name="orderBy-call-manually" module="orderByExample3">
  20001. <file name="index.html">
  20002. <div ng-controller="ExampleController">
  20003. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  20004. <hr/>
  20005. <button ng-click="sortBy(null)">Set to unsorted</button>
  20006. <hr/>
  20007. <table class="friends">
  20008. <tr>
  20009. <th>
  20010. <button ng-click="sortBy('name')">Name</button>
  20011. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  20012. </th>
  20013. <th>
  20014. <button ng-click="sortBy('phone')">Phone Number</button>
  20015. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  20016. </th>
  20017. <th>
  20018. <button ng-click="sortBy('age')">Age</button>
  20019. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  20020. </th>
  20021. </tr>
  20022. <tr ng-repeat="friend in friends">
  20023. <td>{{friend.name}}</td>
  20024. <td>{{friend.phone}}</td>
  20025. <td>{{friend.age}}</td>
  20026. </tr>
  20027. </table>
  20028. </div>
  20029. </file>
  20030. <file name="script.js">
  20031. angular.module('orderByExample3', [])
  20032. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  20033. var friends = [
  20034. {name: 'John', phone: '555-1212', age: 10},
  20035. {name: 'Mary', phone: '555-9876', age: 19},
  20036. {name: 'Mike', phone: '555-4321', age: 21},
  20037. {name: 'Adam', phone: '555-5678', age: 35},
  20038. {name: 'Julie', phone: '555-8765', age: 29}
  20039. ];
  20040. $scope.propertyName = 'age';
  20041. $scope.reverse = true;
  20042. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  20043. $scope.sortBy = function(propertyName) {
  20044. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  20045. ? !$scope.reverse : false;
  20046. $scope.propertyName = propertyName;
  20047. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  20048. };
  20049. }]);
  20050. </file>
  20051. <file name="style.css">
  20052. .friends {
  20053. border-collapse: collapse;
  20054. }
  20055. .friends th {
  20056. border-bottom: 1px solid;
  20057. }
  20058. .friends td, .friends th {
  20059. border-left: 1px solid;
  20060. padding: 5px 10px;
  20061. }
  20062. .friends td:first-child, .friends th:first-child {
  20063. border-left: none;
  20064. }
  20065. .sortorder:after {
  20066. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  20067. }
  20068. .sortorder.reverse:after {
  20069. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  20070. }
  20071. </file>
  20072. <file name="protractor.js" type="protractor">
  20073. // Element locators
  20074. var unsortButton = element(by.partialButtonText('unsorted'));
  20075. var nameHeader = element(by.partialButtonText('Name'));
  20076. var phoneHeader = element(by.partialButtonText('Phone'));
  20077. var ageHeader = element(by.partialButtonText('Age'));
  20078. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  20079. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  20080. it('should sort friends by some property, when clicking on the column header', function() {
  20081. expect(firstName.getText()).toBe('Adam');
  20082. expect(lastName.getText()).toBe('John');
  20083. phoneHeader.click();
  20084. expect(firstName.getText()).toBe('John');
  20085. expect(lastName.getText()).toBe('Mary');
  20086. nameHeader.click();
  20087. expect(firstName.getText()).toBe('Adam');
  20088. expect(lastName.getText()).toBe('Mike');
  20089. ageHeader.click();
  20090. expect(firstName.getText()).toBe('John');
  20091. expect(lastName.getText()).toBe('Adam');
  20092. });
  20093. it('should sort friends in reverse order, when clicking on the same column', function() {
  20094. expect(firstName.getText()).toBe('Adam');
  20095. expect(lastName.getText()).toBe('John');
  20096. ageHeader.click();
  20097. expect(firstName.getText()).toBe('John');
  20098. expect(lastName.getText()).toBe('Adam');
  20099. ageHeader.click();
  20100. expect(firstName.getText()).toBe('Adam');
  20101. expect(lastName.getText()).toBe('John');
  20102. });
  20103. it('should restore the original order, when clicking "Set to unsorted"', function() {
  20104. expect(firstName.getText()).toBe('Adam');
  20105. expect(lastName.getText()).toBe('John');
  20106. unsortButton.click();
  20107. expect(firstName.getText()).toBe('John');
  20108. expect(lastName.getText()).toBe('Julie');
  20109. });
  20110. </file>
  20111. </example>
  20112. * <hr />
  20113. *
  20114. * @example
  20115. * ### Using a custom comparator
  20116. *
  20117. * If you have very specific requirements about the way items are sorted, you can pass your own
  20118. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  20119. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  20120. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  20121. *
  20122. <example name="orderBy-custom-comparator" module="orderByExample4">
  20123. <file name="index.html">
  20124. <div ng-controller="ExampleController">
  20125. <div class="friends-container custom-comparator">
  20126. <h3>Locale-sensitive Comparator</h3>
  20127. <table class="friends">
  20128. <tr>
  20129. <th>Name</th>
  20130. <th>Favorite Letter</th>
  20131. </tr>
  20132. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  20133. <td>{{friend.name}}</td>
  20134. <td>{{friend.favoriteLetter}}</td>
  20135. </tr>
  20136. </table>
  20137. </div>
  20138. <div class="friends-container default-comparator">
  20139. <h3>Default Comparator</h3>
  20140. <table class="friends">
  20141. <tr>
  20142. <th>Name</th>
  20143. <th>Favorite Letter</th>
  20144. </tr>
  20145. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  20146. <td>{{friend.name}}</td>
  20147. <td>{{friend.favoriteLetter}}</td>
  20148. </tr>
  20149. </table>
  20150. </div>
  20151. </div>
  20152. </file>
  20153. <file name="script.js">
  20154. angular.module('orderByExample4', [])
  20155. .controller('ExampleController', ['$scope', function($scope) {
  20156. $scope.friends = [
  20157. {name: 'John', favoriteLetter: 'Ä'},
  20158. {name: 'Mary', favoriteLetter: 'Ü'},
  20159. {name: 'Mike', favoriteLetter: 'Ö'},
  20160. {name: 'Adam', favoriteLetter: 'H'},
  20161. {name: 'Julie', favoriteLetter: 'Z'}
  20162. ];
  20163. $scope.localeSensitiveComparator = function(v1, v2) {
  20164. // If we don't get strings, just compare by index
  20165. if (v1.type !== 'string' || v2.type !== 'string') {
  20166. return (v1.index < v2.index) ? -1 : 1;
  20167. }
  20168. // Compare strings alphabetically, taking locale into account
  20169. return v1.value.localeCompare(v2.value);
  20170. };
  20171. }]);
  20172. </file>
  20173. <file name="style.css">
  20174. .friends-container {
  20175. display: inline-block;
  20176. margin: 0 30px;
  20177. }
  20178. .friends {
  20179. border-collapse: collapse;
  20180. }
  20181. .friends th {
  20182. border-bottom: 1px solid;
  20183. }
  20184. .friends td, .friends th {
  20185. border-left: 1px solid;
  20186. padding: 5px 10px;
  20187. }
  20188. .friends td:first-child, .friends th:first-child {
  20189. border-left: none;
  20190. }
  20191. </file>
  20192. <file name="protractor.js" type="protractor">
  20193. // Element locators
  20194. var container = element(by.css('.custom-comparator'));
  20195. var names = container.all(by.repeater('friends').column('friend.name'));
  20196. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  20197. expect(names.get(0).getText()).toBe('John');
  20198. expect(names.get(1).getText()).toBe('Adam');
  20199. expect(names.get(2).getText()).toBe('Mike');
  20200. expect(names.get(3).getText()).toBe('Mary');
  20201. expect(names.get(4).getText()).toBe('Julie');
  20202. });
  20203. </file>
  20204. </example>
  20205. *
  20206. */
  20207. orderByFilter.$inject = ['$parse'];
  20208. function orderByFilter($parse) {
  20209. return function(array, sortPredicate, reverseOrder, compareFn) {
  20210. if (array == null) return array;
  20211. if (!isArrayLike(array)) {
  20212. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  20213. }
  20214. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  20215. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  20216. var predicates = processPredicates(sortPredicate);
  20217. var descending = reverseOrder ? -1 : 1;
  20218. // Define the `compare()` function. Use a default comparator if none is specified.
  20219. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  20220. // The next three lines are a version of a Swartzian Transform idiom from Perl
  20221. // (sometimes called the Decorate-Sort-Undecorate idiom)
  20222. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  20223. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  20224. compareValues.sort(doComparison);
  20225. array = compareValues.map(function(item) { return item.value; });
  20226. return array;
  20227. function getComparisonObject(value, index) {
  20228. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  20229. // This will be used to keep the sort stable when none of the input predicates can
  20230. // distinguish between two elements.
  20231. return {
  20232. value: value,
  20233. tieBreaker: {value: index, type: 'number', index: index},
  20234. predicateValues: predicates.map(function(predicate) {
  20235. return getPredicateValue(predicate.get(value), index);
  20236. })
  20237. };
  20238. }
  20239. function doComparison(v1, v2) {
  20240. for (var i = 0, ii = predicates.length; i < ii; i++) {
  20241. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  20242. if (result) {
  20243. return result * predicates[i].descending * descending;
  20244. }
  20245. }
  20246. return compare(v1.tieBreaker, v2.tieBreaker) * descending;
  20247. }
  20248. };
  20249. function processPredicates(sortPredicates) {
  20250. return sortPredicates.map(function(predicate) {
  20251. var descending = 1, get = identity;
  20252. if (isFunction(predicate)) {
  20253. get = predicate;
  20254. } else if (isString(predicate)) {
  20255. if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
  20256. descending = predicate.charAt(0) === '-' ? -1 : 1;
  20257. predicate = predicate.substring(1);
  20258. }
  20259. if (predicate !== '') {
  20260. get = $parse(predicate);
  20261. if (get.constant) {
  20262. var key = get();
  20263. get = function(value) { return value[key]; };
  20264. }
  20265. }
  20266. }
  20267. return {get: get, descending: descending};
  20268. });
  20269. }
  20270. function isPrimitive(value) {
  20271. switch (typeof value) {
  20272. case 'number': /* falls through */
  20273. case 'boolean': /* falls through */
  20274. case 'string':
  20275. return true;
  20276. default:
  20277. return false;
  20278. }
  20279. }
  20280. function objectValue(value) {
  20281. // If `valueOf` is a valid function use that
  20282. if (isFunction(value.valueOf)) {
  20283. value = value.valueOf();
  20284. if (isPrimitive(value)) return value;
  20285. }
  20286. // If `toString` is a valid function and not the one from `Object.prototype` use that
  20287. if (hasCustomToString(value)) {
  20288. value = value.toString();
  20289. if (isPrimitive(value)) return value;
  20290. }
  20291. return value;
  20292. }
  20293. function getPredicateValue(value, index) {
  20294. var type = typeof value;
  20295. if (value === null) {
  20296. type = 'string';
  20297. value = 'null';
  20298. } else if (type === 'object') {
  20299. value = objectValue(value);
  20300. }
  20301. return {value: value, type: type, index: index};
  20302. }
  20303. function defaultCompare(v1, v2) {
  20304. var result = 0;
  20305. var type1 = v1.type;
  20306. var type2 = v2.type;
  20307. if (type1 === type2) {
  20308. var value1 = v1.value;
  20309. var value2 = v2.value;
  20310. if (type1 === 'string') {
  20311. // Compare strings case-insensitively
  20312. value1 = value1.toLowerCase();
  20313. value2 = value2.toLowerCase();
  20314. } else if (type1 === 'object') {
  20315. // For basic objects, use the position of the object
  20316. // in the collection instead of the value
  20317. if (isObject(value1)) value1 = v1.index;
  20318. if (isObject(value2)) value2 = v2.index;
  20319. }
  20320. if (value1 !== value2) {
  20321. result = value1 < value2 ? -1 : 1;
  20322. }
  20323. } else {
  20324. result = type1 < type2 ? -1 : 1;
  20325. }
  20326. return result;
  20327. }
  20328. }
  20329. function ngDirective(directive) {
  20330. if (isFunction(directive)) {
  20331. directive = {
  20332. link: directive
  20333. };
  20334. }
  20335. directive.restrict = directive.restrict || 'AC';
  20336. return valueFn(directive);
  20337. }
  20338. /**
  20339. * @ngdoc directive
  20340. * @name a
  20341. * @restrict E
  20342. *
  20343. * @description
  20344. * Modifies the default behavior of the html a tag so that the default action is prevented when
  20345. * the href attribute is empty.
  20346. *
  20347. * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
  20348. */
  20349. var htmlAnchorDirective = valueFn({
  20350. restrict: 'E',
  20351. compile: function(element, attr) {
  20352. if (!attr.href && !attr.xlinkHref) {
  20353. return function(scope, element) {
  20354. // If the linked element is not an anchor tag anymore, do nothing
  20355. if (element[0].nodeName.toLowerCase() !== 'a') return;
  20356. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  20357. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  20358. 'xlink:href' : 'href';
  20359. element.on('click', function(event) {
  20360. // if we have no href url, then don't navigate anywhere.
  20361. if (!element.attr(href)) {
  20362. event.preventDefault();
  20363. }
  20364. });
  20365. };
  20366. }
  20367. }
  20368. });
  20369. /**
  20370. * @ngdoc directive
  20371. * @name ngHref
  20372. * @restrict A
  20373. * @priority 99
  20374. *
  20375. * @description
  20376. * Using Angular markup like `{{hash}}` in an href attribute will
  20377. * make the link go to the wrong URL if the user clicks it before
  20378. * Angular has a chance to replace the `{{hash}}` markup with its
  20379. * value. Until Angular replaces the markup the link will be broken
  20380. * and will most likely return a 404 error. The `ngHref` directive
  20381. * solves this problem.
  20382. *
  20383. * The wrong way to write it:
  20384. * ```html
  20385. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20386. * ```
  20387. *
  20388. * The correct way to write it:
  20389. * ```html
  20390. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20391. * ```
  20392. *
  20393. * @element A
  20394. * @param {template} ngHref any string which can contain `{{}}` markup.
  20395. *
  20396. * @example
  20397. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  20398. * in links and their different behaviors:
  20399. <example name="ng-href">
  20400. <file name="index.html">
  20401. <input ng-model="value" /><br />
  20402. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  20403. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  20404. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  20405. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  20406. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  20407. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  20408. </file>
  20409. <file name="protractor.js" type="protractor">
  20410. it('should execute ng-click but not reload when href without value', function() {
  20411. element(by.id('link-1')).click();
  20412. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  20413. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  20414. });
  20415. it('should execute ng-click but not reload when href empty string', function() {
  20416. element(by.id('link-2')).click();
  20417. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  20418. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  20419. });
  20420. it('should execute ng-click and change url when ng-href specified', function() {
  20421. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  20422. element(by.id('link-3')).click();
  20423. // At this point, we navigate away from an Angular page, so we need
  20424. // to use browser.driver to get the base webdriver.
  20425. browser.wait(function() {
  20426. return browser.driver.getCurrentUrl().then(function(url) {
  20427. return url.match(/\/123$/);
  20428. });
  20429. }, 5000, 'page should navigate to /123');
  20430. });
  20431. it('should execute ng-click but not reload when href empty string and name specified', function() {
  20432. element(by.id('link-4')).click();
  20433. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  20434. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  20435. });
  20436. it('should execute ng-click but not reload when no href but name specified', function() {
  20437. element(by.id('link-5')).click();
  20438. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  20439. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  20440. });
  20441. it('should only change url when only ng-href', function() {
  20442. element(by.model('value')).clear();
  20443. element(by.model('value')).sendKeys('6');
  20444. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  20445. element(by.id('link-6')).click();
  20446. // At this point, we navigate away from an Angular page, so we need
  20447. // to use browser.driver to get the base webdriver.
  20448. browser.wait(function() {
  20449. return browser.driver.getCurrentUrl().then(function(url) {
  20450. return url.match(/\/6$/);
  20451. });
  20452. }, 5000, 'page should navigate to /6');
  20453. });
  20454. </file>
  20455. </example>
  20456. */
  20457. /**
  20458. * @ngdoc directive
  20459. * @name ngSrc
  20460. * @restrict A
  20461. * @priority 99
  20462. *
  20463. * @description
  20464. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  20465. * work right: The browser will fetch from the URL with the literal
  20466. * text `{{hash}}` until Angular replaces the expression inside
  20467. * `{{hash}}`. The `ngSrc` directive solves this problem.
  20468. *
  20469. * The buggy way to write it:
  20470. * ```html
  20471. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  20472. * ```
  20473. *
  20474. * The correct way to write it:
  20475. * ```html
  20476. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  20477. * ```
  20478. *
  20479. * @element IMG
  20480. * @param {template} ngSrc any string which can contain `{{}}` markup.
  20481. */
  20482. /**
  20483. * @ngdoc directive
  20484. * @name ngSrcset
  20485. * @restrict A
  20486. * @priority 99
  20487. *
  20488. * @description
  20489. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  20490. * work right: The browser will fetch from the URL with the literal
  20491. * text `{{hash}}` until Angular replaces the expression inside
  20492. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  20493. *
  20494. * The buggy way to write it:
  20495. * ```html
  20496. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  20497. * ```
  20498. *
  20499. * The correct way to write it:
  20500. * ```html
  20501. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  20502. * ```
  20503. *
  20504. * @element IMG
  20505. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  20506. */
  20507. /**
  20508. * @ngdoc directive
  20509. * @name ngDisabled
  20510. * @restrict A
  20511. * @priority 100
  20512. *
  20513. * @description
  20514. *
  20515. * This directive sets the `disabled` attribute on the element (typically a form control,
  20516. * e.g. `input`, `button`, `select` etc.) if the
  20517. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  20518. *
  20519. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  20520. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20521. *
  20522. * @example
  20523. <example name="ng-disabled">
  20524. <file name="index.html">
  20525. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  20526. <button ng-model="button" ng-disabled="checked">Button</button>
  20527. </file>
  20528. <file name="protractor.js" type="protractor">
  20529. it('should toggle button', function() {
  20530. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  20531. element(by.model('checked')).click();
  20532. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  20533. });
  20534. </file>
  20535. </example>
  20536. *
  20537. * @element INPUT
  20538. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  20539. * then the `disabled` attribute will be set on the element
  20540. */
  20541. /**
  20542. * @ngdoc directive
  20543. * @name ngChecked
  20544. * @restrict A
  20545. * @priority 100
  20546. *
  20547. * @description
  20548. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  20549. *
  20550. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  20551. * as this can lead to unexpected behavior.
  20552. *
  20553. * A special directive is necessary because we cannot use interpolation inside the `checked`
  20554. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20555. *
  20556. * @example
  20557. <example name="ng-checked">
  20558. <file name="index.html">
  20559. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  20560. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  20561. </file>
  20562. <file name="protractor.js" type="protractor">
  20563. it('should check both checkBoxes', function() {
  20564. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  20565. element(by.model('master')).click();
  20566. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  20567. });
  20568. </file>
  20569. </example>
  20570. *
  20571. * @element INPUT
  20572. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  20573. * then the `checked` attribute will be set on the element
  20574. */
  20575. /**
  20576. * @ngdoc directive
  20577. * @name ngReadonly
  20578. * @restrict A
  20579. * @priority 100
  20580. *
  20581. * @description
  20582. *
  20583. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  20584. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  20585. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  20586. *
  20587. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  20588. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20589. *
  20590. * @example
  20591. <example name="ng-readonly">
  20592. <file name="index.html">
  20593. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  20594. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  20595. </file>
  20596. <file name="protractor.js" type="protractor">
  20597. it('should toggle readonly attr', function() {
  20598. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  20599. element(by.model('checked')).click();
  20600. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  20601. });
  20602. </file>
  20603. </example>
  20604. *
  20605. * @element INPUT
  20606. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  20607. * then special attribute "readonly" will be set on the element
  20608. */
  20609. /**
  20610. * @ngdoc directive
  20611. * @name ngSelected
  20612. * @restrict A
  20613. * @priority 100
  20614. *
  20615. * @description
  20616. *
  20617. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  20618. *
  20619. * A special directive is necessary because we cannot use interpolation inside the `selected`
  20620. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20621. *
  20622. * <div class="alert alert-warning">
  20623. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  20624. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  20625. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  20626. * selected options.
  20627. * </div>
  20628. *
  20629. * @example
  20630. <example name="ng-selected">
  20631. <file name="index.html">
  20632. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  20633. <select aria-label="ngSelected demo">
  20634. <option>Hello!</option>
  20635. <option id="greet" ng-selected="selected">Greetings!</option>
  20636. </select>
  20637. </file>
  20638. <file name="protractor.js" type="protractor">
  20639. it('should select Greetings!', function() {
  20640. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  20641. element(by.model('selected')).click();
  20642. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  20643. });
  20644. </file>
  20645. </example>
  20646. *
  20647. * @element OPTION
  20648. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  20649. * then special attribute "selected" will be set on the element
  20650. */
  20651. /**
  20652. * @ngdoc directive
  20653. * @name ngOpen
  20654. * @restrict A
  20655. * @priority 100
  20656. *
  20657. * @description
  20658. *
  20659. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  20660. *
  20661. * A special directive is necessary because we cannot use interpolation inside the `open`
  20662. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20663. *
  20664. * ## A note about browser compatibility
  20665. *
  20666. * Edge, Firefox, and Internet Explorer do not support the `details` element, it is
  20667. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  20668. *
  20669. * @example
  20670. <example name="ng-open">
  20671. <file name="index.html">
  20672. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  20673. <details id="details" ng-open="open">
  20674. <summary>Show/Hide me</summary>
  20675. </details>
  20676. </file>
  20677. <file name="protractor.js" type="protractor">
  20678. it('should toggle open', function() {
  20679. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  20680. element(by.model('open')).click();
  20681. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  20682. });
  20683. </file>
  20684. </example>
  20685. *
  20686. * @element DETAILS
  20687. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  20688. * then special attribute "open" will be set on the element
  20689. */
  20690. var ngAttributeAliasDirectives = {};
  20691. // boolean attrs are evaluated
  20692. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  20693. // binding to multiple is not supported
  20694. if (propName === 'multiple') return;
  20695. function defaultLinkFn(scope, element, attr) {
  20696. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  20697. attr.$set(attrName, !!value);
  20698. });
  20699. }
  20700. var normalized = directiveNormalize('ng-' + attrName);
  20701. var linkFn = defaultLinkFn;
  20702. if (propName === 'checked') {
  20703. linkFn = function(scope, element, attr) {
  20704. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  20705. if (attr.ngModel !== attr[normalized]) {
  20706. defaultLinkFn(scope, element, attr);
  20707. }
  20708. };
  20709. }
  20710. ngAttributeAliasDirectives[normalized] = function() {
  20711. return {
  20712. restrict: 'A',
  20713. priority: 100,
  20714. link: linkFn
  20715. };
  20716. };
  20717. });
  20718. // aliased input attrs are evaluated
  20719. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  20720. ngAttributeAliasDirectives[ngAttr] = function() {
  20721. return {
  20722. priority: 100,
  20723. link: function(scope, element, attr) {
  20724. //special case ngPattern when a literal regular expression value
  20725. //is used as the expression (this way we don't have to watch anything).
  20726. if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
  20727. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  20728. if (match) {
  20729. attr.$set('ngPattern', new RegExp(match[1], match[2]));
  20730. return;
  20731. }
  20732. }
  20733. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  20734. attr.$set(ngAttr, value);
  20735. });
  20736. }
  20737. };
  20738. };
  20739. });
  20740. // ng-src, ng-srcset, ng-href are interpolated
  20741. forEach(['src', 'srcset', 'href'], function(attrName) {
  20742. var normalized = directiveNormalize('ng-' + attrName);
  20743. ngAttributeAliasDirectives[normalized] = function() {
  20744. return {
  20745. priority: 99, // it needs to run after the attributes are interpolated
  20746. link: function(scope, element, attr) {
  20747. var propName = attrName,
  20748. name = attrName;
  20749. if (attrName === 'href' &&
  20750. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  20751. name = 'xlinkHref';
  20752. attr.$attr[name] = 'xlink:href';
  20753. propName = null;
  20754. }
  20755. attr.$observe(normalized, function(value) {
  20756. if (!value) {
  20757. if (attrName === 'href') {
  20758. attr.$set(name, null);
  20759. }
  20760. return;
  20761. }
  20762. attr.$set(name, value);
  20763. // Support: IE 9-11 only
  20764. // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  20765. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  20766. // to set the property as well to achieve the desired effect.
  20767. // We use attr[attrName] value since $set can sanitize the url.
  20768. if (msie && propName) element.prop(propName, attr[name]);
  20769. });
  20770. }
  20771. };
  20772. };
  20773. });
  20774. /* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS
  20775. */
  20776. var nullFormCtrl = {
  20777. $addControl: noop,
  20778. $$renameControl: nullFormRenameControl,
  20779. $removeControl: noop,
  20780. $setValidity: noop,
  20781. $setDirty: noop,
  20782. $setPristine: noop,
  20783. $setSubmitted: noop
  20784. },
  20785. PENDING_CLASS = 'ng-pending',
  20786. SUBMITTED_CLASS = 'ng-submitted';
  20787. function nullFormRenameControl(control, name) {
  20788. control.$name = name;
  20789. }
  20790. /**
  20791. * @ngdoc type
  20792. * @name form.FormController
  20793. *
  20794. * @property {boolean} $pristine True if user has not interacted with the form yet.
  20795. * @property {boolean} $dirty True if user has already interacted with the form.
  20796. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  20797. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  20798. * @property {boolean} $pending True if at least one containing control or form is pending.
  20799. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  20800. *
  20801. * @property {Object} $error Is an object hash, containing references to controls or
  20802. * forms with failing validators, where:
  20803. *
  20804. * - keys are validation tokens (error names),
  20805. * - values are arrays of controls or forms that have a failing validator for given error name.
  20806. *
  20807. * Built-in validation tokens:
  20808. *
  20809. * - `email`
  20810. * - `max`
  20811. * - `maxlength`
  20812. * - `min`
  20813. * - `minlength`
  20814. * - `number`
  20815. * - `pattern`
  20816. * - `required`
  20817. * - `url`
  20818. * - `date`
  20819. * - `datetimelocal`
  20820. * - `time`
  20821. * - `week`
  20822. * - `month`
  20823. *
  20824. * @description
  20825. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  20826. * such as being valid/invalid or dirty/pristine.
  20827. *
  20828. * Each {@link ng.directive:form form} directive creates an instance
  20829. * of `FormController`.
  20830. *
  20831. */
  20832. //asks for $scope to fool the BC controller module
  20833. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  20834. function FormController($element, $attrs, $scope, $animate, $interpolate) {
  20835. this.$$controls = [];
  20836. // init state
  20837. this.$error = {};
  20838. this.$$success = {};
  20839. this.$pending = undefined;
  20840. this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);
  20841. this.$dirty = false;
  20842. this.$pristine = true;
  20843. this.$valid = true;
  20844. this.$invalid = false;
  20845. this.$submitted = false;
  20846. this.$$parentForm = nullFormCtrl;
  20847. this.$$element = $element;
  20848. this.$$animate = $animate;
  20849. setupValidity(this);
  20850. }
  20851. FormController.prototype = {
  20852. /**
  20853. * @ngdoc method
  20854. * @name form.FormController#$rollbackViewValue
  20855. *
  20856. * @description
  20857. * Rollback all form controls pending updates to the `$modelValue`.
  20858. *
  20859. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20860. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  20861. * a form that uses `ng-model-options` to pend updates.
  20862. */
  20863. $rollbackViewValue: function() {
  20864. forEach(this.$$controls, function(control) {
  20865. control.$rollbackViewValue();
  20866. });
  20867. },
  20868. /**
  20869. * @ngdoc method
  20870. * @name form.FormController#$commitViewValue
  20871. *
  20872. * @description
  20873. * Commit all form controls pending updates to the `$modelValue`.
  20874. *
  20875. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20876. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  20877. * usually handles calling this in response to input events.
  20878. */
  20879. $commitViewValue: function() {
  20880. forEach(this.$$controls, function(control) {
  20881. control.$commitViewValue();
  20882. });
  20883. },
  20884. /**
  20885. * @ngdoc method
  20886. * @name form.FormController#$addControl
  20887. * @param {object} control control object, either a {@link form.FormController} or an
  20888. * {@link ngModel.NgModelController}
  20889. *
  20890. * @description
  20891. * Register a control with the form. Input elements using ngModelController do this automatically
  20892. * when they are linked.
  20893. *
  20894. * Note that the current state of the control will not be reflected on the new parent form. This
  20895. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  20896. * state.
  20897. *
  20898. * However, if the method is used programmatically, for example by adding dynamically created controls,
  20899. * or controls that have been previously removed without destroying their corresponding DOM element,
  20900. * it's the developers responsibility to make sure the current state propagates to the parent form.
  20901. *
  20902. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  20903. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  20904. */
  20905. $addControl: function(control) {
  20906. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  20907. // and not added to the scope. Now we throw an error.
  20908. assertNotHasOwnProperty(control.$name, 'input');
  20909. this.$$controls.push(control);
  20910. if (control.$name) {
  20911. this[control.$name] = control;
  20912. }
  20913. control.$$parentForm = this;
  20914. },
  20915. // Private API: rename a form control
  20916. $$renameControl: function(control, newName) {
  20917. var oldName = control.$name;
  20918. if (this[oldName] === control) {
  20919. delete this[oldName];
  20920. }
  20921. this[newName] = control;
  20922. control.$name = newName;
  20923. },
  20924. /**
  20925. * @ngdoc method
  20926. * @name form.FormController#$removeControl
  20927. * @param {object} control control object, either a {@link form.FormController} or an
  20928. * {@link ngModel.NgModelController}
  20929. *
  20930. * @description
  20931. * Deregister a control from the form.
  20932. *
  20933. * Input elements using ngModelController do this automatically when they are destroyed.
  20934. *
  20935. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  20936. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  20937. * different from case to case. For example, removing the only `$dirty` control from a form may or
  20938. * may not mean that the form is still `$dirty`.
  20939. */
  20940. $removeControl: function(control) {
  20941. if (control.$name && this[control.$name] === control) {
  20942. delete this[control.$name];
  20943. }
  20944. forEach(this.$pending, function(value, name) {
  20945. // eslint-disable-next-line no-invalid-this
  20946. this.$setValidity(name, null, control);
  20947. }, this);
  20948. forEach(this.$error, function(value, name) {
  20949. // eslint-disable-next-line no-invalid-this
  20950. this.$setValidity(name, null, control);
  20951. }, this);
  20952. forEach(this.$$success, function(value, name) {
  20953. // eslint-disable-next-line no-invalid-this
  20954. this.$setValidity(name, null, control);
  20955. }, this);
  20956. arrayRemove(this.$$controls, control);
  20957. control.$$parentForm = nullFormCtrl;
  20958. },
  20959. /**
  20960. * @ngdoc method
  20961. * @name form.FormController#$setDirty
  20962. *
  20963. * @description
  20964. * Sets the form to a dirty state.
  20965. *
  20966. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  20967. * state (ng-dirty class). This method will also propagate to parent forms.
  20968. */
  20969. $setDirty: function() {
  20970. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  20971. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  20972. this.$dirty = true;
  20973. this.$pristine = false;
  20974. this.$$parentForm.$setDirty();
  20975. },
  20976. /**
  20977. * @ngdoc method
  20978. * @name form.FormController#$setPristine
  20979. *
  20980. * @description
  20981. * Sets the form to its pristine state.
  20982. *
  20983. * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
  20984. * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
  20985. * state to false.
  20986. *
  20987. * This method will also propagate to all the controls contained in this form.
  20988. *
  20989. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  20990. * saving or resetting it.
  20991. */
  20992. $setPristine: function() {
  20993. this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  20994. this.$dirty = false;
  20995. this.$pristine = true;
  20996. this.$submitted = false;
  20997. forEach(this.$$controls, function(control) {
  20998. control.$setPristine();
  20999. });
  21000. },
  21001. /**
  21002. * @ngdoc method
  21003. * @name form.FormController#$setUntouched
  21004. *
  21005. * @description
  21006. * Sets the form to its untouched state.
  21007. *
  21008. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  21009. * untouched state (ng-untouched class).
  21010. *
  21011. * Setting a form controls back to their untouched state is often useful when setting the form
  21012. * back to its pristine state.
  21013. */
  21014. $setUntouched: function() {
  21015. forEach(this.$$controls, function(control) {
  21016. control.$setUntouched();
  21017. });
  21018. },
  21019. /**
  21020. * @ngdoc method
  21021. * @name form.FormController#$setSubmitted
  21022. *
  21023. * @description
  21024. * Sets the form to its submitted state.
  21025. */
  21026. $setSubmitted: function() {
  21027. this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);
  21028. this.$submitted = true;
  21029. this.$$parentForm.$setSubmitted();
  21030. }
  21031. };
  21032. /**
  21033. * @ngdoc method
  21034. * @name form.FormController#$setValidity
  21035. *
  21036. * @description
  21037. * Sets the validity of a form control.
  21038. *
  21039. * This method will also propagate to parent forms.
  21040. */
  21041. addSetValidityMethod({
  21042. clazz: FormController,
  21043. set: function(object, property, controller) {
  21044. var list = object[property];
  21045. if (!list) {
  21046. object[property] = [controller];
  21047. } else {
  21048. var index = list.indexOf(controller);
  21049. if (index === -1) {
  21050. list.push(controller);
  21051. }
  21052. }
  21053. },
  21054. unset: function(object, property, controller) {
  21055. var list = object[property];
  21056. if (!list) {
  21057. return;
  21058. }
  21059. arrayRemove(list, controller);
  21060. if (list.length === 0) {
  21061. delete object[property];
  21062. }
  21063. }
  21064. });
  21065. /**
  21066. * @ngdoc directive
  21067. * @name ngForm
  21068. * @restrict EAC
  21069. *
  21070. * @description
  21071. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  21072. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  21073. * sub-group of controls needs to be determined.
  21074. *
  21075. * Note: the purpose of `ngForm` is to group controls,
  21076. * but not to be a replacement for the `<form>` tag with all of its capabilities
  21077. * (e.g. posting to the server, ...).
  21078. *
  21079. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  21080. * related scope, under this name.
  21081. *
  21082. */
  21083. /**
  21084. * @ngdoc directive
  21085. * @name form
  21086. * @restrict E
  21087. *
  21088. * @description
  21089. * Directive that instantiates
  21090. * {@link form.FormController FormController}.
  21091. *
  21092. * If the `name` attribute is specified, the form controller is published onto the current scope under
  21093. * this name.
  21094. *
  21095. * # Alias: {@link ng.directive:ngForm `ngForm`}
  21096. *
  21097. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  21098. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  21099. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  21100. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  21101. * of controls needs to be determined.
  21102. *
  21103. * # CSS classes
  21104. * - `ng-valid` is set if the form is valid.
  21105. * - `ng-invalid` is set if the form is invalid.
  21106. * - `ng-pending` is set if the form is pending.
  21107. * - `ng-pristine` is set if the form is pristine.
  21108. * - `ng-dirty` is set if the form is dirty.
  21109. * - `ng-submitted` is set if the form was submitted.
  21110. *
  21111. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  21112. *
  21113. *
  21114. * # Submitting a form and preventing the default action
  21115. *
  21116. * Since the role of forms in client-side Angular applications is different than in classical
  21117. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  21118. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  21119. * to handle the form submission in an application-specific way.
  21120. *
  21121. * For this reason, Angular prevents the default action (form submission to the server) unless the
  21122. * `<form>` element has an `action` attribute specified.
  21123. *
  21124. * You can use one of the following two ways to specify what javascript method should be called when
  21125. * a form is submitted:
  21126. *
  21127. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  21128. * - {@link ng.directive:ngClick ngClick} directive on the first
  21129. * button or input field of type submit (input[type=submit])
  21130. *
  21131. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  21132. * or {@link ng.directive:ngClick ngClick} directives.
  21133. * This is because of the following form submission rules in the HTML specification:
  21134. *
  21135. * - If a form has only one input field then hitting enter in this field triggers form submit
  21136. * (`ngSubmit`)
  21137. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  21138. * doesn't trigger submit
  21139. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  21140. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  21141. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  21142. *
  21143. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  21144. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  21145. * to have access to the updated model.
  21146. *
  21147. * ## Animation Hooks
  21148. *
  21149. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  21150. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  21151. * other validations that are performed within the form. Animations in ngForm are similar to how
  21152. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  21153. * as JS animations.
  21154. *
  21155. * The following example shows a simple way to utilize CSS transitions to style a form element
  21156. * that has been rendered as invalid after it has been validated:
  21157. *
  21158. * <pre>
  21159. * //be sure to include ngAnimate as a module to hook into more
  21160. * //advanced animations
  21161. * .my-form {
  21162. * transition:0.5s linear all;
  21163. * background: white;
  21164. * }
  21165. * .my-form.ng-invalid {
  21166. * background: red;
  21167. * color:white;
  21168. * }
  21169. * </pre>
  21170. *
  21171. * @example
  21172. <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  21173. <file name="index.html">
  21174. <script>
  21175. angular.module('formExample', [])
  21176. .controller('FormController', ['$scope', function($scope) {
  21177. $scope.userType = 'guest';
  21178. }]);
  21179. </script>
  21180. <style>
  21181. .my-form {
  21182. transition:all linear 0.5s;
  21183. background: transparent;
  21184. }
  21185. .my-form.ng-invalid {
  21186. background: red;
  21187. }
  21188. </style>
  21189. <form name="myForm" ng-controller="FormController" class="my-form">
  21190. userType: <input name="input" ng-model="userType" required>
  21191. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  21192. <code>userType = {{userType}}</code><br>
  21193. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  21194. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  21195. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  21196. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  21197. </form>
  21198. </file>
  21199. <file name="protractor.js" type="protractor">
  21200. it('should initialize to model', function() {
  21201. var userType = element(by.binding('userType'));
  21202. var valid = element(by.binding('myForm.input.$valid'));
  21203. expect(userType.getText()).toContain('guest');
  21204. expect(valid.getText()).toContain('true');
  21205. });
  21206. it('should be invalid if empty', function() {
  21207. var userType = element(by.binding('userType'));
  21208. var valid = element(by.binding('myForm.input.$valid'));
  21209. var userInput = element(by.model('userType'));
  21210. userInput.clear();
  21211. userInput.sendKeys('');
  21212. expect(userType.getText()).toEqual('userType =');
  21213. expect(valid.getText()).toContain('false');
  21214. });
  21215. </file>
  21216. </example>
  21217. *
  21218. * @param {string=} name Name of the form. If specified, the form controller will be published into
  21219. * related scope, under this name.
  21220. */
  21221. var formDirectiveFactory = function(isNgForm) {
  21222. return ['$timeout', '$parse', function($timeout, $parse) {
  21223. var formDirective = {
  21224. name: 'form',
  21225. restrict: isNgForm ? 'EAC' : 'E',
  21226. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  21227. controller: FormController,
  21228. compile: function ngFormCompile(formElement, attr) {
  21229. // Setup initial state of the control
  21230. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  21231. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  21232. return {
  21233. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  21234. var controller = ctrls[0];
  21235. // if `action` attr is not present on the form, prevent the default action (submission)
  21236. if (!('action' in attr)) {
  21237. // we can't use jq events because if a form is destroyed during submission the default
  21238. // action is not prevented. see #1238
  21239. //
  21240. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  21241. // page reload if the form was destroyed by submission of the form via a click handler
  21242. // on a button in the form. Looks like an IE9 specific bug.
  21243. var handleFormSubmission = function(event) {
  21244. scope.$apply(function() {
  21245. controller.$commitViewValue();
  21246. controller.$setSubmitted();
  21247. });
  21248. event.preventDefault();
  21249. };
  21250. formElement[0].addEventListener('submit', handleFormSubmission);
  21251. // unregister the preventDefault listener so that we don't not leak memory but in a
  21252. // way that will achieve the prevention of the default action.
  21253. formElement.on('$destroy', function() {
  21254. $timeout(function() {
  21255. formElement[0].removeEventListener('submit', handleFormSubmission);
  21256. }, 0, false);
  21257. });
  21258. }
  21259. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  21260. parentFormCtrl.$addControl(controller);
  21261. var setter = nameAttr ? getSetter(controller.$name) : noop;
  21262. if (nameAttr) {
  21263. setter(scope, controller);
  21264. attr.$observe(nameAttr, function(newValue) {
  21265. if (controller.$name === newValue) return;
  21266. setter(scope, undefined);
  21267. controller.$$parentForm.$$renameControl(controller, newValue);
  21268. setter = getSetter(controller.$name);
  21269. setter(scope, controller);
  21270. });
  21271. }
  21272. formElement.on('$destroy', function() {
  21273. controller.$$parentForm.$removeControl(controller);
  21274. setter(scope, undefined);
  21275. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  21276. });
  21277. }
  21278. };
  21279. }
  21280. };
  21281. return formDirective;
  21282. function getSetter(expression) {
  21283. if (expression === '') {
  21284. //create an assignable expression, so forms with an empty name can be renamed later
  21285. return $parse('this[""]').assign;
  21286. }
  21287. return $parse(expression).assign || noop;
  21288. }
  21289. }];
  21290. };
  21291. var formDirective = formDirectiveFactory();
  21292. var ngFormDirective = formDirectiveFactory(true);
  21293. // helper methods
  21294. function setupValidity(instance) {
  21295. instance.$$classCache = {};
  21296. instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));
  21297. }
  21298. function addSetValidityMethod(context) {
  21299. var clazz = context.clazz,
  21300. set = context.set,
  21301. unset = context.unset;
  21302. clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {
  21303. if (isUndefined(state)) {
  21304. createAndSet(this, '$pending', validationErrorKey, controller);
  21305. } else {
  21306. unsetAndCleanup(this, '$pending', validationErrorKey, controller);
  21307. }
  21308. if (!isBoolean(state)) {
  21309. unset(this.$error, validationErrorKey, controller);
  21310. unset(this.$$success, validationErrorKey, controller);
  21311. } else {
  21312. if (state) {
  21313. unset(this.$error, validationErrorKey, controller);
  21314. set(this.$$success, validationErrorKey, controller);
  21315. } else {
  21316. set(this.$error, validationErrorKey, controller);
  21317. unset(this.$$success, validationErrorKey, controller);
  21318. }
  21319. }
  21320. if (this.$pending) {
  21321. cachedToggleClass(this, PENDING_CLASS, true);
  21322. this.$valid = this.$invalid = undefined;
  21323. toggleValidationCss(this, '', null);
  21324. } else {
  21325. cachedToggleClass(this, PENDING_CLASS, false);
  21326. this.$valid = isObjectEmpty(this.$error);
  21327. this.$invalid = !this.$valid;
  21328. toggleValidationCss(this, '', this.$valid);
  21329. }
  21330. // re-read the state as the set/unset methods could have
  21331. // combined state in this.$error[validationError] (used for forms),
  21332. // where setting/unsetting only increments/decrements the value,
  21333. // and does not replace it.
  21334. var combinedState;
  21335. if (this.$pending && this.$pending[validationErrorKey]) {
  21336. combinedState = undefined;
  21337. } else if (this.$error[validationErrorKey]) {
  21338. combinedState = false;
  21339. } else if (this.$$success[validationErrorKey]) {
  21340. combinedState = true;
  21341. } else {
  21342. combinedState = null;
  21343. }
  21344. toggleValidationCss(this, validationErrorKey, combinedState);
  21345. this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);
  21346. };
  21347. function createAndSet(ctrl, name, value, controller) {
  21348. if (!ctrl[name]) {
  21349. ctrl[name] = {};
  21350. }
  21351. set(ctrl[name], value, controller);
  21352. }
  21353. function unsetAndCleanup(ctrl, name, value, controller) {
  21354. if (ctrl[name]) {
  21355. unset(ctrl[name], value, controller);
  21356. }
  21357. if (isObjectEmpty(ctrl[name])) {
  21358. ctrl[name] = undefined;
  21359. }
  21360. }
  21361. function cachedToggleClass(ctrl, className, switchValue) {
  21362. if (switchValue && !ctrl.$$classCache[className]) {
  21363. ctrl.$$animate.addClass(ctrl.$$element, className);
  21364. ctrl.$$classCache[className] = true;
  21365. } else if (!switchValue && ctrl.$$classCache[className]) {
  21366. ctrl.$$animate.removeClass(ctrl.$$element, className);
  21367. ctrl.$$classCache[className] = false;
  21368. }
  21369. }
  21370. function toggleValidationCss(ctrl, validationErrorKey, isValid) {
  21371. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  21372. cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);
  21373. cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);
  21374. }
  21375. }
  21376. function isObjectEmpty(obj) {
  21377. if (obj) {
  21378. for (var prop in obj) {
  21379. if (obj.hasOwnProperty(prop)) {
  21380. return false;
  21381. }
  21382. }
  21383. }
  21384. return true;
  21385. }
  21386. /* global
  21387. VALID_CLASS: false,
  21388. INVALID_CLASS: false,
  21389. PRISTINE_CLASS: false,
  21390. DIRTY_CLASS: false,
  21391. ngModelMinErr: false
  21392. */
  21393. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  21394. 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)$/;
  21395. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  21396. // Note: We are being more lenient, because browsers are too.
  21397. // 1. Scheme
  21398. // 2. Slashes
  21399. // 3. Username
  21400. // 4. Password
  21401. // 5. Hostname
  21402. // 6. Port
  21403. // 7. Path
  21404. // 8. Query
  21405. // 9. Fragment
  21406. // 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
  21407. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  21408. // eslint-disable-next-line max-len
  21409. var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
  21410. var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  21411. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  21412. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21413. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  21414. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  21415. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21416. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  21417. var PARTIAL_VALIDATION_TYPES = createMap();
  21418. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  21419. PARTIAL_VALIDATION_TYPES[type] = true;
  21420. });
  21421. var inputType = {
  21422. /**
  21423. * @ngdoc input
  21424. * @name input[text]
  21425. *
  21426. * @description
  21427. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  21428. *
  21429. *
  21430. * @param {string} ngModel Assignable angular expression to data-bind to.
  21431. * @param {string=} name Property name of the form under which the control is published.
  21432. * @param {string=} required Adds `required` validation error key if the value is not entered.
  21433. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21434. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21435. * `required` when you want to data-bind to the `required` attribute.
  21436. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21437. * minlength.
  21438. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21439. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21440. * any length.
  21441. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21442. * that contains the regular expression body that will be converted to a regular expression
  21443. * as in the ngPattern directive.
  21444. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21445. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21446. * If the expression evaluates to a RegExp object, then this is used directly.
  21447. * If the expression evaluates to a string, then it will be converted to a RegExp
  21448. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21449. * `new RegExp('^abc$')`.<br />
  21450. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21451. * start at the index of the last search's match, thus not taking the whole input value into
  21452. * account.
  21453. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21454. * interaction with the input element.
  21455. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21456. * This parameter is ignored for input[type=password] controls, which will never trim the
  21457. * input.
  21458. *
  21459. * @example
  21460. <example name="text-input-directive" module="textInputExample">
  21461. <file name="index.html">
  21462. <script>
  21463. angular.module('textInputExample', [])
  21464. .controller('ExampleController', ['$scope', function($scope) {
  21465. $scope.example = {
  21466. text: 'guest',
  21467. word: /^\s*\w*\s*$/
  21468. };
  21469. }]);
  21470. </script>
  21471. <form name="myForm" ng-controller="ExampleController">
  21472. <label>Single word:
  21473. <input type="text" name="input" ng-model="example.text"
  21474. ng-pattern="example.word" required ng-trim="false">
  21475. </label>
  21476. <div role="alert">
  21477. <span class="error" ng-show="myForm.input.$error.required">
  21478. Required!</span>
  21479. <span class="error" ng-show="myForm.input.$error.pattern">
  21480. Single word only!</span>
  21481. </div>
  21482. <code>text = {{example.text}}</code><br/>
  21483. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  21484. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  21485. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  21486. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  21487. </form>
  21488. </file>
  21489. <file name="protractor.js" type="protractor">
  21490. var text = element(by.binding('example.text'));
  21491. var valid = element(by.binding('myForm.input.$valid'));
  21492. var input = element(by.model('example.text'));
  21493. it('should initialize to model', function() {
  21494. expect(text.getText()).toContain('guest');
  21495. expect(valid.getText()).toContain('true');
  21496. });
  21497. it('should be invalid if empty', function() {
  21498. input.clear();
  21499. input.sendKeys('');
  21500. expect(text.getText()).toEqual('text =');
  21501. expect(valid.getText()).toContain('false');
  21502. });
  21503. it('should be invalid if multi word', function() {
  21504. input.clear();
  21505. input.sendKeys('hello world');
  21506. expect(valid.getText()).toContain('false');
  21507. });
  21508. </file>
  21509. </example>
  21510. */
  21511. 'text': textInputType,
  21512. /**
  21513. * @ngdoc input
  21514. * @name input[date]
  21515. *
  21516. * @description
  21517. * Input with date validation and transformation. In browsers that do not yet support
  21518. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  21519. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  21520. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  21521. * expected input format via a placeholder or label.
  21522. *
  21523. * The model must always be a Date object, otherwise Angular will throw an error.
  21524. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21525. *
  21526. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21527. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21528. *
  21529. * @param {string} ngModel Assignable angular expression to data-bind to.
  21530. * @param {string=} name Property name of the form under which the control is published.
  21531. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  21532. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21533. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  21534. * constraint validation.
  21535. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  21536. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21537. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  21538. * constraint validation.
  21539. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  21540. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21541. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  21542. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21543. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21544. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21545. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21546. * `required` when you want to data-bind to the `required` attribute.
  21547. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21548. * interaction with the input element.
  21549. *
  21550. * @example
  21551. <example name="date-input-directive" module="dateInputExample">
  21552. <file name="index.html">
  21553. <script>
  21554. angular.module('dateInputExample', [])
  21555. .controller('DateController', ['$scope', function($scope) {
  21556. $scope.example = {
  21557. value: new Date(2013, 9, 22)
  21558. };
  21559. }]);
  21560. </script>
  21561. <form name="myForm" ng-controller="DateController as dateCtrl">
  21562. <label for="exampleInput">Pick a date in 2013:</label>
  21563. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  21564. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  21565. <div role="alert">
  21566. <span class="error" ng-show="myForm.input.$error.required">
  21567. Required!</span>
  21568. <span class="error" ng-show="myForm.input.$error.date">
  21569. Not a valid date!</span>
  21570. </div>
  21571. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  21572. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21573. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21574. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21575. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21576. </form>
  21577. </file>
  21578. <file name="protractor.js" type="protractor">
  21579. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  21580. var valid = element(by.binding('myForm.input.$valid'));
  21581. // currently protractor/webdriver does not support
  21582. // sending keys to all known HTML5 input controls
  21583. // for various browsers (see https://github.com/angular/protractor/issues/562).
  21584. function setInput(val) {
  21585. // set the value of the element and force validation.
  21586. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21587. "ipt.value = '" + val + "';" +
  21588. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21589. browser.executeScript(scr);
  21590. }
  21591. it('should initialize to model', function() {
  21592. expect(value.getText()).toContain('2013-10-22');
  21593. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21594. });
  21595. it('should be invalid if empty', function() {
  21596. setInput('');
  21597. expect(value.getText()).toEqual('value =');
  21598. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21599. });
  21600. it('should be invalid if over max', function() {
  21601. setInput('2015-01-01');
  21602. expect(value.getText()).toContain('');
  21603. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21604. });
  21605. </file>
  21606. </example>
  21607. */
  21608. 'date': createDateInputType('date', DATE_REGEXP,
  21609. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  21610. 'yyyy-MM-dd'),
  21611. /**
  21612. * @ngdoc input
  21613. * @name input[datetime-local]
  21614. *
  21615. * @description
  21616. * Input with datetime validation and transformation. In browsers that do not yet support
  21617. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21618. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  21619. *
  21620. * The model must always be a Date object, otherwise Angular will throw an error.
  21621. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21622. *
  21623. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21624. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21625. *
  21626. * @param {string} ngModel Assignable angular expression to data-bind to.
  21627. * @param {string=} name Property name of the form under which the control is published.
  21628. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21629. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21630. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21631. * Note that `min` will also add native HTML5 constraint validation.
  21632. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21633. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21634. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21635. * Note that `max` will also add native HTML5 constraint validation.
  21636. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  21637. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21638. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  21639. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21640. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21641. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21642. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21643. * `required` when you want to data-bind to the `required` attribute.
  21644. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21645. * interaction with the input element.
  21646. *
  21647. * @example
  21648. <example name="datetimelocal-input-directive" module="dateExample">
  21649. <file name="index.html">
  21650. <script>
  21651. angular.module('dateExample', [])
  21652. .controller('DateController', ['$scope', function($scope) {
  21653. $scope.example = {
  21654. value: new Date(2010, 11, 28, 14, 57)
  21655. };
  21656. }]);
  21657. </script>
  21658. <form name="myForm" ng-controller="DateController as dateCtrl">
  21659. <label for="exampleInput">Pick a date between in 2013:</label>
  21660. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  21661. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  21662. <div role="alert">
  21663. <span class="error" ng-show="myForm.input.$error.required">
  21664. Required!</span>
  21665. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  21666. Not a valid date!</span>
  21667. </div>
  21668. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  21669. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21670. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21671. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21672. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21673. </form>
  21674. </file>
  21675. <file name="protractor.js" type="protractor">
  21676. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  21677. var valid = element(by.binding('myForm.input.$valid'));
  21678. // currently protractor/webdriver does not support
  21679. // sending keys to all known HTML5 input controls
  21680. // for various browsers (https://github.com/angular/protractor/issues/562).
  21681. function setInput(val) {
  21682. // set the value of the element and force validation.
  21683. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21684. "ipt.value = '" + val + "';" +
  21685. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21686. browser.executeScript(scr);
  21687. }
  21688. it('should initialize to model', function() {
  21689. expect(value.getText()).toContain('2010-12-28T14:57:00');
  21690. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21691. });
  21692. it('should be invalid if empty', function() {
  21693. setInput('');
  21694. expect(value.getText()).toEqual('value =');
  21695. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21696. });
  21697. it('should be invalid if over max', function() {
  21698. setInput('2015-01-01T23:59:00');
  21699. expect(value.getText()).toContain('');
  21700. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21701. });
  21702. </file>
  21703. </example>
  21704. */
  21705. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  21706. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  21707. 'yyyy-MM-ddTHH:mm:ss.sss'),
  21708. /**
  21709. * @ngdoc input
  21710. * @name input[time]
  21711. *
  21712. * @description
  21713. * Input with time validation and transformation. In browsers that do not yet support
  21714. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21715. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  21716. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  21717. *
  21718. * The model must always be a Date object, otherwise Angular will throw an error.
  21719. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21720. *
  21721. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21722. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21723. *
  21724. * @param {string} ngModel Assignable angular expression to data-bind to.
  21725. * @param {string=} name Property name of the form under which the control is published.
  21726. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21727. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21728. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  21729. * native HTML5 constraint validation.
  21730. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21731. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21732. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  21733. * native HTML5 constraint validation.
  21734. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  21735. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21736. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  21737. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21738. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21739. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21740. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21741. * `required` when you want to data-bind to the `required` attribute.
  21742. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21743. * interaction with the input element.
  21744. *
  21745. * @example
  21746. <example name="time-input-directive" module="timeExample">
  21747. <file name="index.html">
  21748. <script>
  21749. angular.module('timeExample', [])
  21750. .controller('DateController', ['$scope', function($scope) {
  21751. $scope.example = {
  21752. value: new Date(1970, 0, 1, 14, 57, 0)
  21753. };
  21754. }]);
  21755. </script>
  21756. <form name="myForm" ng-controller="DateController as dateCtrl">
  21757. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  21758. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  21759. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  21760. <div role="alert">
  21761. <span class="error" ng-show="myForm.input.$error.required">
  21762. Required!</span>
  21763. <span class="error" ng-show="myForm.input.$error.time">
  21764. Not a valid date!</span>
  21765. </div>
  21766. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  21767. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21768. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21769. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21770. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21771. </form>
  21772. </file>
  21773. <file name="protractor.js" type="protractor">
  21774. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  21775. var valid = element(by.binding('myForm.input.$valid'));
  21776. // currently protractor/webdriver does not support
  21777. // sending keys to all known HTML5 input controls
  21778. // for various browsers (https://github.com/angular/protractor/issues/562).
  21779. function setInput(val) {
  21780. // set the value of the element and force validation.
  21781. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21782. "ipt.value = '" + val + "';" +
  21783. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21784. browser.executeScript(scr);
  21785. }
  21786. it('should initialize to model', function() {
  21787. expect(value.getText()).toContain('14:57:00');
  21788. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21789. });
  21790. it('should be invalid if empty', function() {
  21791. setInput('');
  21792. expect(value.getText()).toEqual('value =');
  21793. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21794. });
  21795. it('should be invalid if over max', function() {
  21796. setInput('23:59:00');
  21797. expect(value.getText()).toContain('');
  21798. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21799. });
  21800. </file>
  21801. </example>
  21802. */
  21803. 'time': createDateInputType('time', TIME_REGEXP,
  21804. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  21805. 'HH:mm:ss.sss'),
  21806. /**
  21807. * @ngdoc input
  21808. * @name input[week]
  21809. *
  21810. * @description
  21811. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  21812. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21813. * week format (yyyy-W##), for example: `2013-W02`.
  21814. *
  21815. * The model must always be a Date object, otherwise Angular will throw an error.
  21816. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21817. *
  21818. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21819. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21820. *
  21821. * @param {string} ngModel Assignable angular expression to data-bind to.
  21822. * @param {string=} name Property name of the form under which the control is published.
  21823. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21824. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21825. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  21826. * native HTML5 constraint validation.
  21827. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21828. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21829. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  21830. * native HTML5 constraint validation.
  21831. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21832. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21833. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21834. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21835. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21836. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21837. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21838. * `required` when you want to data-bind to the `required` attribute.
  21839. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21840. * interaction with the input element.
  21841. *
  21842. * @example
  21843. <example name="week-input-directive" module="weekExample">
  21844. <file name="index.html">
  21845. <script>
  21846. angular.module('weekExample', [])
  21847. .controller('DateController', ['$scope', function($scope) {
  21848. $scope.example = {
  21849. value: new Date(2013, 0, 3)
  21850. };
  21851. }]);
  21852. </script>
  21853. <form name="myForm" ng-controller="DateController as dateCtrl">
  21854. <label>Pick a date between in 2013:
  21855. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  21856. placeholder="YYYY-W##" min="2012-W32"
  21857. max="2013-W52" required />
  21858. </label>
  21859. <div role="alert">
  21860. <span class="error" ng-show="myForm.input.$error.required">
  21861. Required!</span>
  21862. <span class="error" ng-show="myForm.input.$error.week">
  21863. Not a valid date!</span>
  21864. </div>
  21865. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  21866. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21867. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21868. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21869. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21870. </form>
  21871. </file>
  21872. <file name="protractor.js" type="protractor">
  21873. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  21874. var valid = element(by.binding('myForm.input.$valid'));
  21875. // currently protractor/webdriver does not support
  21876. // sending keys to all known HTML5 input controls
  21877. // for various browsers (https://github.com/angular/protractor/issues/562).
  21878. function setInput(val) {
  21879. // set the value of the element and force validation.
  21880. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21881. "ipt.value = '" + val + "';" +
  21882. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21883. browser.executeScript(scr);
  21884. }
  21885. it('should initialize to model', function() {
  21886. expect(value.getText()).toContain('2013-W01');
  21887. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21888. });
  21889. it('should be invalid if empty', function() {
  21890. setInput('');
  21891. expect(value.getText()).toEqual('value =');
  21892. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21893. });
  21894. it('should be invalid if over max', function() {
  21895. setInput('2015-W01');
  21896. expect(value.getText()).toContain('');
  21897. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21898. });
  21899. </file>
  21900. </example>
  21901. */
  21902. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  21903. /**
  21904. * @ngdoc input
  21905. * @name input[month]
  21906. *
  21907. * @description
  21908. * Input with month validation and transformation. In browsers that do not yet support
  21909. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21910. * month format (yyyy-MM), for example: `2009-01`.
  21911. *
  21912. * The model must always be a Date object, otherwise Angular will throw an error.
  21913. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21914. * If the model is not set to the first of the month, the next view to model update will set it
  21915. * to the first of the month.
  21916. *
  21917. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21918. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21919. *
  21920. * @param {string} ngModel Assignable angular expression to data-bind to.
  21921. * @param {string=} name Property name of the form under which the control is published.
  21922. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21923. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21924. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  21925. * native HTML5 constraint validation.
  21926. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21927. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21928. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  21929. * native HTML5 constraint validation.
  21930. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21931. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21932. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21933. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21934. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21935. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21936. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21937. * `required` when you want to data-bind to the `required` attribute.
  21938. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21939. * interaction with the input element.
  21940. *
  21941. * @example
  21942. <example name="month-input-directive" module="monthExample">
  21943. <file name="index.html">
  21944. <script>
  21945. angular.module('monthExample', [])
  21946. .controller('DateController', ['$scope', function($scope) {
  21947. $scope.example = {
  21948. value: new Date(2013, 9, 1)
  21949. };
  21950. }]);
  21951. </script>
  21952. <form name="myForm" ng-controller="DateController as dateCtrl">
  21953. <label for="exampleInput">Pick a month in 2013:</label>
  21954. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  21955. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  21956. <div role="alert">
  21957. <span class="error" ng-show="myForm.input.$error.required">
  21958. Required!</span>
  21959. <span class="error" ng-show="myForm.input.$error.month">
  21960. Not a valid month!</span>
  21961. </div>
  21962. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  21963. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21964. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21965. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21966. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21967. </form>
  21968. </file>
  21969. <file name="protractor.js" type="protractor">
  21970. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  21971. var valid = element(by.binding('myForm.input.$valid'));
  21972. // currently protractor/webdriver does not support
  21973. // sending keys to all known HTML5 input controls
  21974. // for various browsers (https://github.com/angular/protractor/issues/562).
  21975. function setInput(val) {
  21976. // set the value of the element and force validation.
  21977. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21978. "ipt.value = '" + val + "';" +
  21979. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21980. browser.executeScript(scr);
  21981. }
  21982. it('should initialize to model', function() {
  21983. expect(value.getText()).toContain('2013-10');
  21984. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21985. });
  21986. it('should be invalid if empty', function() {
  21987. setInput('');
  21988. expect(value.getText()).toEqual('value =');
  21989. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21990. });
  21991. it('should be invalid if over max', function() {
  21992. setInput('2015-01');
  21993. expect(value.getText()).toContain('');
  21994. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21995. });
  21996. </file>
  21997. </example>
  21998. */
  21999. 'month': createDateInputType('month', MONTH_REGEXP,
  22000. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  22001. 'yyyy-MM'),
  22002. /**
  22003. * @ngdoc input
  22004. * @name input[number]
  22005. *
  22006. * @description
  22007. * Text input with number validation and transformation. Sets the `number` validation
  22008. * error if not a valid number.
  22009. *
  22010. * <div class="alert alert-warning">
  22011. * The model must always be of type `number` otherwise Angular will throw an error.
  22012. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  22013. * error docs for more information and an example of how to convert your model if necessary.
  22014. * </div>
  22015. *
  22016. * ## Issues with HTML5 constraint validation
  22017. *
  22018. * In browsers that follow the
  22019. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  22020. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  22021. * If a non-number is entered in the input, the browser will report the value as an empty string,
  22022. * which means the view / model values in `ngModel` and subsequently the scope value
  22023. * will also be an empty string.
  22024. *
  22025. *
  22026. * @param {string} ngModel Assignable angular expression to data-bind to.
  22027. * @param {string=} name Property name of the form under which the control is published.
  22028. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22029. * Can be interpolated.
  22030. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22031. * Can be interpolated.
  22032. * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
  22033. * but does not trigger HTML5 native validation. Takes an expression.
  22034. * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
  22035. * but does not trigger HTML5 native validation. Takes an expression.
  22036. * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
  22037. * Can be interpolated.
  22038. * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
  22039. * but does not trigger HTML5 native validation. Takes an expression.
  22040. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22041. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22042. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22043. * `required` when you want to data-bind to the `required` attribute.
  22044. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22045. * minlength.
  22046. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22047. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22048. * any length.
  22049. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22050. * that contains the regular expression body that will be converted to a regular expression
  22051. * as in the ngPattern directive.
  22052. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22053. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22054. * If the expression evaluates to a RegExp object, then this is used directly.
  22055. * If the expression evaluates to a string, then it will be converted to a RegExp
  22056. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22057. * `new RegExp('^abc$')`.<br />
  22058. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22059. * start at the index of the last search's match, thus not taking the whole input value into
  22060. * account.
  22061. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22062. * interaction with the input element.
  22063. *
  22064. * @example
  22065. <example name="number-input-directive" module="numberExample">
  22066. <file name="index.html">
  22067. <script>
  22068. angular.module('numberExample', [])
  22069. .controller('ExampleController', ['$scope', function($scope) {
  22070. $scope.example = {
  22071. value: 12
  22072. };
  22073. }]);
  22074. </script>
  22075. <form name="myForm" ng-controller="ExampleController">
  22076. <label>Number:
  22077. <input type="number" name="input" ng-model="example.value"
  22078. min="0" max="99" required>
  22079. </label>
  22080. <div role="alert">
  22081. <span class="error" ng-show="myForm.input.$error.required">
  22082. Required!</span>
  22083. <span class="error" ng-show="myForm.input.$error.number">
  22084. Not valid number!</span>
  22085. </div>
  22086. <tt>value = {{example.value}}</tt><br/>
  22087. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22088. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22089. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22090. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22091. </form>
  22092. </file>
  22093. <file name="protractor.js" type="protractor">
  22094. var value = element(by.binding('example.value'));
  22095. var valid = element(by.binding('myForm.input.$valid'));
  22096. var input = element(by.model('example.value'));
  22097. it('should initialize to model', function() {
  22098. expect(value.getText()).toContain('12');
  22099. expect(valid.getText()).toContain('true');
  22100. });
  22101. it('should be invalid if empty', function() {
  22102. input.clear();
  22103. input.sendKeys('');
  22104. expect(value.getText()).toEqual('value =');
  22105. expect(valid.getText()).toContain('false');
  22106. });
  22107. it('should be invalid if over max', function() {
  22108. input.clear();
  22109. input.sendKeys('123');
  22110. expect(value.getText()).toEqual('value =');
  22111. expect(valid.getText()).toContain('false');
  22112. });
  22113. </file>
  22114. </example>
  22115. */
  22116. 'number': numberInputType,
  22117. /**
  22118. * @ngdoc input
  22119. * @name input[url]
  22120. *
  22121. * @description
  22122. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  22123. * valid URL.
  22124. *
  22125. * <div class="alert alert-warning">
  22126. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  22127. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  22128. * the built-in validators (see the {@link guide/forms Forms guide})
  22129. * </div>
  22130. *
  22131. * @param {string} ngModel Assignable angular expression to data-bind to.
  22132. * @param {string=} name Property name of the form under which the control is published.
  22133. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22134. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22135. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22136. * `required` when you want to data-bind to the `required` attribute.
  22137. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22138. * minlength.
  22139. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22140. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22141. * any length.
  22142. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22143. * that contains the regular expression body that will be converted to a regular expression
  22144. * as in the ngPattern directive.
  22145. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22146. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22147. * If the expression evaluates to a RegExp object, then this is used directly.
  22148. * If the expression evaluates to a string, then it will be converted to a RegExp
  22149. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22150. * `new RegExp('^abc$')`.<br />
  22151. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22152. * start at the index of the last search's match, thus not taking the whole input value into
  22153. * account.
  22154. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22155. * interaction with the input element.
  22156. *
  22157. * @example
  22158. <example name="url-input-directive" module="urlExample">
  22159. <file name="index.html">
  22160. <script>
  22161. angular.module('urlExample', [])
  22162. .controller('ExampleController', ['$scope', function($scope) {
  22163. $scope.url = {
  22164. text: 'http://google.com'
  22165. };
  22166. }]);
  22167. </script>
  22168. <form name="myForm" ng-controller="ExampleController">
  22169. <label>URL:
  22170. <input type="url" name="input" ng-model="url.text" required>
  22171. <label>
  22172. <div role="alert">
  22173. <span class="error" ng-show="myForm.input.$error.required">
  22174. Required!</span>
  22175. <span class="error" ng-show="myForm.input.$error.url">
  22176. Not valid url!</span>
  22177. </div>
  22178. <tt>text = {{url.text}}</tt><br/>
  22179. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22180. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22181. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22182. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22183. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  22184. </form>
  22185. </file>
  22186. <file name="protractor.js" type="protractor">
  22187. var text = element(by.binding('url.text'));
  22188. var valid = element(by.binding('myForm.input.$valid'));
  22189. var input = element(by.model('url.text'));
  22190. it('should initialize to model', function() {
  22191. expect(text.getText()).toContain('http://google.com');
  22192. expect(valid.getText()).toContain('true');
  22193. });
  22194. it('should be invalid if empty', function() {
  22195. input.clear();
  22196. input.sendKeys('');
  22197. expect(text.getText()).toEqual('text =');
  22198. expect(valid.getText()).toContain('false');
  22199. });
  22200. it('should be invalid if not url', function() {
  22201. input.clear();
  22202. input.sendKeys('box');
  22203. expect(valid.getText()).toContain('false');
  22204. });
  22205. </file>
  22206. </example>
  22207. */
  22208. 'url': urlInputType,
  22209. /**
  22210. * @ngdoc input
  22211. * @name input[email]
  22212. *
  22213. * @description
  22214. * Text input with email validation. Sets the `email` validation error key if not a valid email
  22215. * address.
  22216. *
  22217. * <div class="alert alert-warning">
  22218. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  22219. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  22220. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  22221. * </div>
  22222. *
  22223. * @param {string} ngModel Assignable angular expression to data-bind to.
  22224. * @param {string=} name Property name of the form under which the control is published.
  22225. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22226. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22227. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22228. * `required` when you want to data-bind to the `required` attribute.
  22229. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22230. * minlength.
  22231. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22232. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22233. * any length.
  22234. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22235. * that contains the regular expression body that will be converted to a regular expression
  22236. * as in the ngPattern directive.
  22237. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22238. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22239. * If the expression evaluates to a RegExp object, then this is used directly.
  22240. * If the expression evaluates to a string, then it will be converted to a RegExp
  22241. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22242. * `new RegExp('^abc$')`.<br />
  22243. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22244. * start at the index of the last search's match, thus not taking the whole input value into
  22245. * account.
  22246. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22247. * interaction with the input element.
  22248. *
  22249. * @example
  22250. <example name="email-input-directive" module="emailExample">
  22251. <file name="index.html">
  22252. <script>
  22253. angular.module('emailExample', [])
  22254. .controller('ExampleController', ['$scope', function($scope) {
  22255. $scope.email = {
  22256. text: 'me@example.com'
  22257. };
  22258. }]);
  22259. </script>
  22260. <form name="myForm" ng-controller="ExampleController">
  22261. <label>Email:
  22262. <input type="email" name="input" ng-model="email.text" required>
  22263. </label>
  22264. <div role="alert">
  22265. <span class="error" ng-show="myForm.input.$error.required">
  22266. Required!</span>
  22267. <span class="error" ng-show="myForm.input.$error.email">
  22268. Not valid email!</span>
  22269. </div>
  22270. <tt>text = {{email.text}}</tt><br/>
  22271. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22272. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22273. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22274. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22275. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  22276. </form>
  22277. </file>
  22278. <file name="protractor.js" type="protractor">
  22279. var text = element(by.binding('email.text'));
  22280. var valid = element(by.binding('myForm.input.$valid'));
  22281. var input = element(by.model('email.text'));
  22282. it('should initialize to model', function() {
  22283. expect(text.getText()).toContain('me@example.com');
  22284. expect(valid.getText()).toContain('true');
  22285. });
  22286. it('should be invalid if empty', function() {
  22287. input.clear();
  22288. input.sendKeys('');
  22289. expect(text.getText()).toEqual('text =');
  22290. expect(valid.getText()).toContain('false');
  22291. });
  22292. it('should be invalid if not email', function() {
  22293. input.clear();
  22294. input.sendKeys('xxx');
  22295. expect(valid.getText()).toContain('false');
  22296. });
  22297. </file>
  22298. </example>
  22299. */
  22300. 'email': emailInputType,
  22301. /**
  22302. * @ngdoc input
  22303. * @name input[radio]
  22304. *
  22305. * @description
  22306. * HTML radio button.
  22307. *
  22308. * @param {string} ngModel Assignable angular expression to data-bind to.
  22309. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  22310. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  22311. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  22312. * @param {string=} name Property name of the form under which the control is published.
  22313. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22314. * interaction with the input element.
  22315. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  22316. * is selected. Should be used instead of the `value` attribute if you need
  22317. * a non-string `ngModel` (`boolean`, `array`, ...).
  22318. *
  22319. * @example
  22320. <example name="radio-input-directive" module="radioExample">
  22321. <file name="index.html">
  22322. <script>
  22323. angular.module('radioExample', [])
  22324. .controller('ExampleController', ['$scope', function($scope) {
  22325. $scope.color = {
  22326. name: 'blue'
  22327. };
  22328. $scope.specialValue = {
  22329. "id": "12345",
  22330. "value": "green"
  22331. };
  22332. }]);
  22333. </script>
  22334. <form name="myForm" ng-controller="ExampleController">
  22335. <label>
  22336. <input type="radio" ng-model="color.name" value="red">
  22337. Red
  22338. </label><br/>
  22339. <label>
  22340. <input type="radio" ng-model="color.name" ng-value="specialValue">
  22341. Green
  22342. </label><br/>
  22343. <label>
  22344. <input type="radio" ng-model="color.name" value="blue">
  22345. Blue
  22346. </label><br/>
  22347. <tt>color = {{color.name | json}}</tt><br/>
  22348. </form>
  22349. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  22350. </file>
  22351. <file name="protractor.js" type="protractor">
  22352. it('should change state', function() {
  22353. var inputs = element.all(by.model('color.name'));
  22354. var color = element(by.binding('color.name'));
  22355. expect(color.getText()).toContain('blue');
  22356. inputs.get(0).click();
  22357. expect(color.getText()).toContain('red');
  22358. inputs.get(1).click();
  22359. expect(color.getText()).toContain('green');
  22360. });
  22361. </file>
  22362. </example>
  22363. */
  22364. 'radio': radioInputType,
  22365. /**
  22366. * @ngdoc input
  22367. * @name input[range]
  22368. *
  22369. * @description
  22370. * Native range input with validation and transformation.
  22371. *
  22372. * The model for the range input must always be a `Number`.
  22373. *
  22374. * IE9 and other browsers that do not support the `range` type fall back
  22375. * to a text input without any default values for `min`, `max` and `step`. Model binding,
  22376. * validation and number parsing are nevertheless supported.
  22377. *
  22378. * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
  22379. * in a way that never allows the input to hold an invalid value. That means:
  22380. * - any non-numerical value is set to `(max + min) / 2`.
  22381. * - any numerical value that is less than the current min val, or greater than the current max val
  22382. * is set to the min / max val respectively.
  22383. * - additionally, the current `step` is respected, so the nearest value that satisfies a step
  22384. * is used.
  22385. *
  22386. * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
  22387. * for more info.
  22388. *
  22389. * This has the following consequences for Angular:
  22390. *
  22391. * Since the element value should always reflect the current model value, a range input
  22392. * will set the bound ngModel expression to the value that the browser has set for the
  22393. * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
  22394. * if the application sets `model.value = null`, the browser will set the input to `'50'`.
  22395. * Angular will then set the model to `50`, to prevent input and model value being out of sync.
  22396. *
  22397. * That means the model for range will immediately be set to `50` after `ngModel` has been
  22398. * initialized. It also means a range input can never have the required error.
  22399. *
  22400. * This does not only affect changes to the model value, but also to the values of the `min`,
  22401. * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
  22402. * the input value, Angular will also update the model value.
  22403. *
  22404. * Automatic value adjustment also means that a range input element can never have the `required`,
  22405. * `min`, or `max` errors.
  22406. *
  22407. * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
  22408. * when the step value changes dynamically - they do not adjust the element value correctly, but
  22409. * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`
  22410. * error on the input, and set the model to `undefined`.
  22411. *
  22412. * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
  22413. * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
  22414. * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
  22415. *
  22416. * @param {string} ngModel Assignable angular expression to data-bind to.
  22417. * @param {string=} name Property name of the form under which the control is published.
  22418. * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
  22419. * than `min`. Can be interpolated.
  22420. * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
  22421. * Can be interpolated.
  22422. * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
  22423. * Can be interpolated.
  22424. * @param {string=} ngChange Angular expression to be executed when the ngModel value changes due
  22425. * to user interaction with the input element.
  22426. * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
  22427. * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
  22428. * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
  22429. *
  22430. * @example
  22431. <example name="range-input-directive" module="rangeExample">
  22432. <file name="index.html">
  22433. <script>
  22434. angular.module('rangeExample', [])
  22435. .controller('ExampleController', ['$scope', function($scope) {
  22436. $scope.value = 75;
  22437. $scope.min = 10;
  22438. $scope.max = 90;
  22439. }]);
  22440. </script>
  22441. <form name="myForm" ng-controller="ExampleController">
  22442. Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
  22443. <hr>
  22444. Model as number: <input type="number" ng-model="value"><br>
  22445. Min: <input type="number" ng-model="min"><br>
  22446. Max: <input type="number" ng-model="max"><br>
  22447. value = <code>{{value}}</code><br/>
  22448. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22449. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22450. </form>
  22451. </file>
  22452. </example>
  22453. * ## Range Input with ngMin & ngMax attributes
  22454. * @example
  22455. <example name="range-input-directive-ng" module="rangeExample">
  22456. <file name="index.html">
  22457. <script>
  22458. angular.module('rangeExample', [])
  22459. .controller('ExampleController', ['$scope', function($scope) {
  22460. $scope.value = 75;
  22461. $scope.min = 10;
  22462. $scope.max = 90;
  22463. }]);
  22464. </script>
  22465. <form name="myForm" ng-controller="ExampleController">
  22466. Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
  22467. <hr>
  22468. Model as number: <input type="number" ng-model="value"><br>
  22469. Min: <input type="number" ng-model="min"><br>
  22470. Max: <input type="number" ng-model="max"><br>
  22471. value = <code>{{value}}</code><br/>
  22472. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22473. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22474. </form>
  22475. </file>
  22476. </example>
  22477. */
  22478. 'range': rangeInputType,
  22479. /**
  22480. * @ngdoc input
  22481. * @name input[checkbox]
  22482. *
  22483. * @description
  22484. * HTML checkbox.
  22485. *
  22486. * @param {string} ngModel Assignable angular expression to data-bind to.
  22487. * @param {string=} name Property name of the form under which the control is published.
  22488. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  22489. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  22490. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22491. * interaction with the input element.
  22492. *
  22493. * @example
  22494. <example name="checkbox-input-directive" module="checkboxExample">
  22495. <file name="index.html">
  22496. <script>
  22497. angular.module('checkboxExample', [])
  22498. .controller('ExampleController', ['$scope', function($scope) {
  22499. $scope.checkboxModel = {
  22500. value1 : true,
  22501. value2 : 'YES'
  22502. };
  22503. }]);
  22504. </script>
  22505. <form name="myForm" ng-controller="ExampleController">
  22506. <label>Value1:
  22507. <input type="checkbox" ng-model="checkboxModel.value1">
  22508. </label><br/>
  22509. <label>Value2:
  22510. <input type="checkbox" ng-model="checkboxModel.value2"
  22511. ng-true-value="'YES'" ng-false-value="'NO'">
  22512. </label><br/>
  22513. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  22514. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  22515. </form>
  22516. </file>
  22517. <file name="protractor.js" type="protractor">
  22518. it('should change state', function() {
  22519. var value1 = element(by.binding('checkboxModel.value1'));
  22520. var value2 = element(by.binding('checkboxModel.value2'));
  22521. expect(value1.getText()).toContain('true');
  22522. expect(value2.getText()).toContain('YES');
  22523. element(by.model('checkboxModel.value1')).click();
  22524. element(by.model('checkboxModel.value2')).click();
  22525. expect(value1.getText()).toContain('false');
  22526. expect(value2.getText()).toContain('NO');
  22527. });
  22528. </file>
  22529. </example>
  22530. */
  22531. 'checkbox': checkboxInputType,
  22532. 'hidden': noop,
  22533. 'button': noop,
  22534. 'submit': noop,
  22535. 'reset': noop,
  22536. 'file': noop
  22537. };
  22538. function stringBasedInputType(ctrl) {
  22539. ctrl.$formatters.push(function(value) {
  22540. return ctrl.$isEmpty(value) ? value : value.toString();
  22541. });
  22542. }
  22543. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22544. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22545. stringBasedInputType(ctrl);
  22546. }
  22547. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22548. var type = lowercase(element[0].type);
  22549. // In composition mode, users are still inputting intermediate text buffer,
  22550. // hold the listener until composition is done.
  22551. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  22552. if (!$sniffer.android) {
  22553. var composing = false;
  22554. element.on('compositionstart', function() {
  22555. composing = true;
  22556. });
  22557. element.on('compositionend', function() {
  22558. composing = false;
  22559. listener();
  22560. });
  22561. }
  22562. var timeout;
  22563. var listener = function(ev) {
  22564. if (timeout) {
  22565. $browser.defer.cancel(timeout);
  22566. timeout = null;
  22567. }
  22568. if (composing) return;
  22569. var value = element.val(),
  22570. event = ev && ev.type;
  22571. // By default we will trim the value
  22572. // If the attribute ng-trim exists we will avoid trimming
  22573. // If input type is 'password', the value is never trimmed
  22574. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  22575. value = trim(value);
  22576. }
  22577. // If a control is suffering from bad input (due to native validators), browsers discard its
  22578. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  22579. // control's value is the same empty value twice in a row.
  22580. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  22581. ctrl.$setViewValue(value, event);
  22582. }
  22583. };
  22584. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  22585. // input event on backspace, delete or cut
  22586. if ($sniffer.hasEvent('input')) {
  22587. element.on('input', listener);
  22588. } else {
  22589. var deferListener = function(ev, input, origValue) {
  22590. if (!timeout) {
  22591. timeout = $browser.defer(function() {
  22592. timeout = null;
  22593. if (!input || input.value !== origValue) {
  22594. listener(ev);
  22595. }
  22596. });
  22597. }
  22598. };
  22599. element.on('keydown', /** @this */ function(event) {
  22600. var key = event.keyCode;
  22601. // ignore
  22602. // command modifiers arrows
  22603. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  22604. deferListener(event, this, this.value);
  22605. });
  22606. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  22607. if ($sniffer.hasEvent('paste')) {
  22608. element.on('paste cut', deferListener);
  22609. }
  22610. }
  22611. // if user paste into input using mouse on older browser
  22612. // or form autocomplete on newer browser, we need "change" event to catch it
  22613. element.on('change', listener);
  22614. // Some native input types (date-family) have the ability to change validity without
  22615. // firing any input/change events.
  22616. // For these event types, when native validators are present and the browser supports the type,
  22617. // check for validity changes on various DOM events.
  22618. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  22619. element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
  22620. if (!timeout) {
  22621. var validity = this[VALIDITY_STATE_PROPERTY];
  22622. var origBadInput = validity.badInput;
  22623. var origTypeMismatch = validity.typeMismatch;
  22624. timeout = $browser.defer(function() {
  22625. timeout = null;
  22626. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  22627. listener(ev);
  22628. }
  22629. });
  22630. }
  22631. });
  22632. }
  22633. ctrl.$render = function() {
  22634. // Workaround for Firefox validation #12102.
  22635. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  22636. if (element.val() !== value) {
  22637. element.val(value);
  22638. }
  22639. };
  22640. }
  22641. function weekParser(isoWeek, existingDate) {
  22642. if (isDate(isoWeek)) {
  22643. return isoWeek;
  22644. }
  22645. if (isString(isoWeek)) {
  22646. WEEK_REGEXP.lastIndex = 0;
  22647. var parts = WEEK_REGEXP.exec(isoWeek);
  22648. if (parts) {
  22649. var year = +parts[1],
  22650. week = +parts[2],
  22651. hours = 0,
  22652. minutes = 0,
  22653. seconds = 0,
  22654. milliseconds = 0,
  22655. firstThurs = getFirstThursdayOfYear(year),
  22656. addDays = (week - 1) * 7;
  22657. if (existingDate) {
  22658. hours = existingDate.getHours();
  22659. minutes = existingDate.getMinutes();
  22660. seconds = existingDate.getSeconds();
  22661. milliseconds = existingDate.getMilliseconds();
  22662. }
  22663. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  22664. }
  22665. }
  22666. return NaN;
  22667. }
  22668. function createDateParser(regexp, mapping) {
  22669. return function(iso, date) {
  22670. var parts, map;
  22671. if (isDate(iso)) {
  22672. return iso;
  22673. }
  22674. if (isString(iso)) {
  22675. // When a date is JSON'ified to wraps itself inside of an extra
  22676. // set of double quotes. This makes the date parsing code unable
  22677. // to match the date string and parse it as a date.
  22678. if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
  22679. iso = iso.substring(1, iso.length - 1);
  22680. }
  22681. if (ISO_DATE_REGEXP.test(iso)) {
  22682. return new Date(iso);
  22683. }
  22684. regexp.lastIndex = 0;
  22685. parts = regexp.exec(iso);
  22686. if (parts) {
  22687. parts.shift();
  22688. if (date) {
  22689. map = {
  22690. yyyy: date.getFullYear(),
  22691. MM: date.getMonth() + 1,
  22692. dd: date.getDate(),
  22693. HH: date.getHours(),
  22694. mm: date.getMinutes(),
  22695. ss: date.getSeconds(),
  22696. sss: date.getMilliseconds() / 1000
  22697. };
  22698. } else {
  22699. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  22700. }
  22701. forEach(parts, function(part, index) {
  22702. if (index < mapping.length) {
  22703. map[mapping[index]] = +part;
  22704. }
  22705. });
  22706. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  22707. }
  22708. }
  22709. return NaN;
  22710. };
  22711. }
  22712. function createDateInputType(type, regexp, parseDate, format) {
  22713. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  22714. badInputChecker(scope, element, attr, ctrl);
  22715. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22716. var timezone = ctrl && ctrl.$options.getOption('timezone');
  22717. var previousDate;
  22718. ctrl.$$parserName = type;
  22719. ctrl.$parsers.push(function(value) {
  22720. if (ctrl.$isEmpty(value)) return null;
  22721. if (regexp.test(value)) {
  22722. // Note: We cannot read ctrl.$modelValue, as there might be a different
  22723. // parser/formatter in the processing chain so that the model
  22724. // contains some different data format!
  22725. var parsedDate = parseDate(value, previousDate);
  22726. if (timezone) {
  22727. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  22728. }
  22729. return parsedDate;
  22730. }
  22731. return undefined;
  22732. });
  22733. ctrl.$formatters.push(function(value) {
  22734. if (value && !isDate(value)) {
  22735. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  22736. }
  22737. if (isValidDate(value)) {
  22738. previousDate = value;
  22739. if (previousDate && timezone) {
  22740. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  22741. }
  22742. return $filter('date')(value, format, timezone);
  22743. } else {
  22744. previousDate = null;
  22745. return '';
  22746. }
  22747. });
  22748. if (isDefined(attr.min) || attr.ngMin) {
  22749. var minVal;
  22750. ctrl.$validators.min = function(value) {
  22751. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  22752. };
  22753. attr.$observe('min', function(val) {
  22754. minVal = parseObservedDateValue(val);
  22755. ctrl.$validate();
  22756. });
  22757. }
  22758. if (isDefined(attr.max) || attr.ngMax) {
  22759. var maxVal;
  22760. ctrl.$validators.max = function(value) {
  22761. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  22762. };
  22763. attr.$observe('max', function(val) {
  22764. maxVal = parseObservedDateValue(val);
  22765. ctrl.$validate();
  22766. });
  22767. }
  22768. function isValidDate(value) {
  22769. // Invalid Date: getTime() returns NaN
  22770. return value && !(value.getTime && value.getTime() !== value.getTime());
  22771. }
  22772. function parseObservedDateValue(val) {
  22773. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  22774. }
  22775. };
  22776. }
  22777. function badInputChecker(scope, element, attr, ctrl) {
  22778. var node = element[0];
  22779. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  22780. if (nativeValidation) {
  22781. ctrl.$parsers.push(function(value) {
  22782. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  22783. return validity.badInput || validity.typeMismatch ? undefined : value;
  22784. });
  22785. }
  22786. }
  22787. function numberFormatterParser(ctrl) {
  22788. ctrl.$$parserName = 'number';
  22789. ctrl.$parsers.push(function(value) {
  22790. if (ctrl.$isEmpty(value)) return null;
  22791. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  22792. return undefined;
  22793. });
  22794. ctrl.$formatters.push(function(value) {
  22795. if (!ctrl.$isEmpty(value)) {
  22796. if (!isNumber(value)) {
  22797. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  22798. }
  22799. value = value.toString();
  22800. }
  22801. return value;
  22802. });
  22803. }
  22804. function parseNumberAttrVal(val) {
  22805. if (isDefined(val) && !isNumber(val)) {
  22806. val = parseFloat(val);
  22807. }
  22808. return !isNumberNaN(val) ? val : undefined;
  22809. }
  22810. function isNumberInteger(num) {
  22811. // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
  22812. // (minus the assumption that `num` is a number)
  22813. // eslint-disable-next-line no-bitwise
  22814. return (num | 0) === num;
  22815. }
  22816. function countDecimals(num) {
  22817. var numString = num.toString();
  22818. var decimalSymbolIndex = numString.indexOf('.');
  22819. if (decimalSymbolIndex === -1) {
  22820. if (-1 < num && num < 1) {
  22821. // It may be in the exponential notation format (`1e-X`)
  22822. var match = /e-(\d+)$/.exec(numString);
  22823. if (match) {
  22824. return Number(match[1]);
  22825. }
  22826. }
  22827. return 0;
  22828. }
  22829. return numString.length - decimalSymbolIndex - 1;
  22830. }
  22831. function isValidForStep(viewValue, stepBase, step) {
  22832. // At this point `stepBase` and `step` are expected to be non-NaN values
  22833. // and `viewValue` is expected to be a valid stringified number.
  22834. var value = Number(viewValue);
  22835. var isNonIntegerValue = !isNumberInteger(value);
  22836. var isNonIntegerStepBase = !isNumberInteger(stepBase);
  22837. var isNonIntegerStep = !isNumberInteger(step);
  22838. // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
  22839. // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
  22840. if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) {
  22841. var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0;
  22842. var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0;
  22843. var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0;
  22844. var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals);
  22845. var multiplier = Math.pow(10, decimalCount);
  22846. value = value * multiplier;
  22847. stepBase = stepBase * multiplier;
  22848. step = step * multiplier;
  22849. if (isNonIntegerValue) value = Math.round(value);
  22850. if (isNonIntegerStepBase) stepBase = Math.round(stepBase);
  22851. if (isNonIntegerStep) step = Math.round(step);
  22852. }
  22853. return (value - stepBase) % step === 0;
  22854. }
  22855. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22856. badInputChecker(scope, element, attr, ctrl);
  22857. numberFormatterParser(ctrl);
  22858. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22859. var minVal;
  22860. var maxVal;
  22861. if (isDefined(attr.min) || attr.ngMin) {
  22862. ctrl.$validators.min = function(value) {
  22863. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  22864. };
  22865. attr.$observe('min', function(val) {
  22866. minVal = parseNumberAttrVal(val);
  22867. // TODO(matsko): implement validateLater to reduce number of validations
  22868. ctrl.$validate();
  22869. });
  22870. }
  22871. if (isDefined(attr.max) || attr.ngMax) {
  22872. ctrl.$validators.max = function(value) {
  22873. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  22874. };
  22875. attr.$observe('max', function(val) {
  22876. maxVal = parseNumberAttrVal(val);
  22877. // TODO(matsko): implement validateLater to reduce number of validations
  22878. ctrl.$validate();
  22879. });
  22880. }
  22881. if (isDefined(attr.step) || attr.ngStep) {
  22882. var stepVal;
  22883. ctrl.$validators.step = function(modelValue, viewValue) {
  22884. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  22885. isValidForStep(viewValue, minVal || 0, stepVal);
  22886. };
  22887. attr.$observe('step', function(val) {
  22888. stepVal = parseNumberAttrVal(val);
  22889. // TODO(matsko): implement validateLater to reduce number of validations
  22890. ctrl.$validate();
  22891. });
  22892. }
  22893. }
  22894. function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22895. badInputChecker(scope, element, attr, ctrl);
  22896. numberFormatterParser(ctrl);
  22897. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22898. var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
  22899. minVal = supportsRange ? 0 : undefined,
  22900. maxVal = supportsRange ? 100 : undefined,
  22901. stepVal = supportsRange ? 1 : undefined,
  22902. validity = element[0].validity,
  22903. hasMinAttr = isDefined(attr.min),
  22904. hasMaxAttr = isDefined(attr.max),
  22905. hasStepAttr = isDefined(attr.step);
  22906. var originalRender = ctrl.$render;
  22907. ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
  22908. //Browsers that implement range will set these values automatically, but reading the adjusted values after
  22909. //$render would cause the min / max validators to be applied with the wrong value
  22910. function rangeRender() {
  22911. originalRender();
  22912. ctrl.$setViewValue(element.val());
  22913. } :
  22914. originalRender;
  22915. if (hasMinAttr) {
  22916. ctrl.$validators.min = supportsRange ?
  22917. // Since all browsers set the input to a valid value, we don't need to check validity
  22918. function noopMinValidator() { return true; } :
  22919. // non-support browsers validate the min val
  22920. function minValidator(modelValue, viewValue) {
  22921. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  22922. };
  22923. setInitialValueAndObserver('min', minChange);
  22924. }
  22925. if (hasMaxAttr) {
  22926. ctrl.$validators.max = supportsRange ?
  22927. // Since all browsers set the input to a valid value, we don't need to check validity
  22928. function noopMaxValidator() { return true; } :
  22929. // non-support browsers validate the max val
  22930. function maxValidator(modelValue, viewValue) {
  22931. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  22932. };
  22933. setInitialValueAndObserver('max', maxChange);
  22934. }
  22935. if (hasStepAttr) {
  22936. ctrl.$validators.step = supportsRange ?
  22937. function nativeStepValidator() {
  22938. // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
  22939. // input element value to a valid value). It's possible that other browsers set the stepMismatch
  22940. // validity error instead, so we can at least report an error in that case.
  22941. return !validity.stepMismatch;
  22942. } :
  22943. // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
  22944. function stepValidator(modelValue, viewValue) {
  22945. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  22946. isValidForStep(viewValue, minVal || 0, stepVal);
  22947. };
  22948. setInitialValueAndObserver('step', stepChange);
  22949. }
  22950. function setInitialValueAndObserver(htmlAttrName, changeFn) {
  22951. // interpolated attributes set the attribute value only after a digest, but we need the
  22952. // attribute value when the input is first rendered, so that the browser can adjust the
  22953. // input value based on the min/max value
  22954. element.attr(htmlAttrName, attr[htmlAttrName]);
  22955. attr.$observe(htmlAttrName, changeFn);
  22956. }
  22957. function minChange(val) {
  22958. minVal = parseNumberAttrVal(val);
  22959. // ignore changes before model is initialized
  22960. if (isNumberNaN(ctrl.$modelValue)) {
  22961. return;
  22962. }
  22963. if (supportsRange) {
  22964. var elVal = element.val();
  22965. // IE11 doesn't set the el val correctly if the minVal is greater than the element value
  22966. if (minVal > elVal) {
  22967. elVal = minVal;
  22968. element.val(elVal);
  22969. }
  22970. ctrl.$setViewValue(elVal);
  22971. } else {
  22972. // TODO(matsko): implement validateLater to reduce number of validations
  22973. ctrl.$validate();
  22974. }
  22975. }
  22976. function maxChange(val) {
  22977. maxVal = parseNumberAttrVal(val);
  22978. // ignore changes before model is initialized
  22979. if (isNumberNaN(ctrl.$modelValue)) {
  22980. return;
  22981. }
  22982. if (supportsRange) {
  22983. var elVal = element.val();
  22984. // IE11 doesn't set the el val correctly if the maxVal is less than the element value
  22985. if (maxVal < elVal) {
  22986. element.val(maxVal);
  22987. // IE11 and Chrome don't set the value to the minVal when max < min
  22988. elVal = maxVal < minVal ? minVal : maxVal;
  22989. }
  22990. ctrl.$setViewValue(elVal);
  22991. } else {
  22992. // TODO(matsko): implement validateLater to reduce number of validations
  22993. ctrl.$validate();
  22994. }
  22995. }
  22996. function stepChange(val) {
  22997. stepVal = parseNumberAttrVal(val);
  22998. // ignore changes before model is initialized
  22999. if (isNumberNaN(ctrl.$modelValue)) {
  23000. return;
  23001. }
  23002. // Some browsers don't adjust the input value correctly, but set the stepMismatch error
  23003. if (supportsRange && ctrl.$viewValue !== element.val()) {
  23004. ctrl.$setViewValue(element.val());
  23005. } else {
  23006. // TODO(matsko): implement validateLater to reduce number of validations
  23007. ctrl.$validate();
  23008. }
  23009. }
  23010. }
  23011. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23012. // Note: no badInputChecker here by purpose as `url` is only a validation
  23013. // in browsers, i.e. we can always read out input.value even if it is not valid!
  23014. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23015. stringBasedInputType(ctrl);
  23016. ctrl.$$parserName = 'url';
  23017. ctrl.$validators.url = function(modelValue, viewValue) {
  23018. var value = modelValue || viewValue;
  23019. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  23020. };
  23021. }
  23022. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23023. // Note: no badInputChecker here by purpose as `url` is only a validation
  23024. // in browsers, i.e. we can always read out input.value even if it is not valid!
  23025. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23026. stringBasedInputType(ctrl);
  23027. ctrl.$$parserName = 'email';
  23028. ctrl.$validators.email = function(modelValue, viewValue) {
  23029. var value = modelValue || viewValue;
  23030. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  23031. };
  23032. }
  23033. function radioInputType(scope, element, attr, ctrl) {
  23034. var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
  23035. // make the name unique, if not defined
  23036. if (isUndefined(attr.name)) {
  23037. element.attr('name', nextUid());
  23038. }
  23039. var listener = function(ev) {
  23040. var value;
  23041. if (element[0].checked) {
  23042. value = attr.value;
  23043. if (doTrim) {
  23044. value = trim(value);
  23045. }
  23046. ctrl.$setViewValue(value, ev && ev.type);
  23047. }
  23048. };
  23049. element.on('click', listener);
  23050. ctrl.$render = function() {
  23051. var value = attr.value;
  23052. if (doTrim) {
  23053. value = trim(value);
  23054. }
  23055. element[0].checked = (value === ctrl.$viewValue);
  23056. };
  23057. attr.$observe('value', ctrl.$render);
  23058. }
  23059. function parseConstantExpr($parse, context, name, expression, fallback) {
  23060. var parseFn;
  23061. if (isDefined(expression)) {
  23062. parseFn = $parse(expression);
  23063. if (!parseFn.constant) {
  23064. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  23065. '`{1}`.', name, expression);
  23066. }
  23067. return parseFn(context);
  23068. }
  23069. return fallback;
  23070. }
  23071. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  23072. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  23073. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  23074. var listener = function(ev) {
  23075. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  23076. };
  23077. element.on('click', listener);
  23078. ctrl.$render = function() {
  23079. element[0].checked = ctrl.$viewValue;
  23080. };
  23081. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  23082. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  23083. // it to a boolean.
  23084. ctrl.$isEmpty = function(value) {
  23085. return value === false;
  23086. };
  23087. ctrl.$formatters.push(function(value) {
  23088. return equals(value, trueValue);
  23089. });
  23090. ctrl.$parsers.push(function(value) {
  23091. return value ? trueValue : falseValue;
  23092. });
  23093. }
  23094. /**
  23095. * @ngdoc directive
  23096. * @name textarea
  23097. * @restrict E
  23098. *
  23099. * @description
  23100. * HTML textarea element control with angular data-binding. The data-binding and validation
  23101. * properties of this element are exactly the same as those of the
  23102. * {@link ng.directive:input input element}.
  23103. *
  23104. * @param {string} ngModel Assignable angular expression to data-bind to.
  23105. * @param {string=} name Property name of the form under which the control is published.
  23106. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23107. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23108. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23109. * `required` when you want to data-bind to the `required` attribute.
  23110. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23111. * minlength.
  23112. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23113. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  23114. * length.
  23115. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23116. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  23117. * If the expression evaluates to a RegExp object, then this is used directly.
  23118. * If the expression evaluates to a string, then it will be converted to a RegExp
  23119. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23120. * `new RegExp('^abc$')`.<br />
  23121. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23122. * start at the index of the last search's match, thus not taking the whole input value into
  23123. * account.
  23124. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  23125. * interaction with the input element.
  23126. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  23127. *
  23128. * @knownIssue
  23129. *
  23130. * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
  23131. * insert the placeholder value as the textarea's content. If the placeholder value contains
  23132. * interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update
  23133. * the value of the by-then-removed text node. This doesn't affect the functionality of the
  23134. * textarea, but can be undesirable.
  23135. *
  23136. * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
  23137. * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
  23138. * find more details on `ngAttr` in the
  23139. * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
  23140. * Developer Guide.
  23141. */
  23142. /**
  23143. * @ngdoc directive
  23144. * @name input
  23145. * @restrict E
  23146. *
  23147. * @description
  23148. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  23149. * input state control, and validation.
  23150. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  23151. *
  23152. * <div class="alert alert-warning">
  23153. * **Note:** Not every feature offered is available for all input types.
  23154. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  23155. * </div>
  23156. *
  23157. * @param {string} ngModel Assignable angular expression to data-bind to.
  23158. * @param {string=} name Property name of the form under which the control is published.
  23159. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23160. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  23161. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23162. * minlength.
  23163. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23164. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  23165. * length.
  23166. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23167. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  23168. * If the expression evaluates to a RegExp object, then this is used directly.
  23169. * If the expression evaluates to a string, then it will be converted to a RegExp
  23170. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23171. * `new RegExp('^abc$')`.<br />
  23172. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23173. * start at the index of the last search's match, thus not taking the whole input value into
  23174. * account.
  23175. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  23176. * interaction with the input element.
  23177. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  23178. * This parameter is ignored for input[type=password] controls, which will never trim the
  23179. * input.
  23180. *
  23181. * @example
  23182. <example name="input-directive" module="inputExample">
  23183. <file name="index.html">
  23184. <script>
  23185. angular.module('inputExample', [])
  23186. .controller('ExampleController', ['$scope', function($scope) {
  23187. $scope.user = {name: 'guest', last: 'visitor'};
  23188. }]);
  23189. </script>
  23190. <div ng-controller="ExampleController">
  23191. <form name="myForm">
  23192. <label>
  23193. User name:
  23194. <input type="text" name="userName" ng-model="user.name" required>
  23195. </label>
  23196. <div role="alert">
  23197. <span class="error" ng-show="myForm.userName.$error.required">
  23198. Required!</span>
  23199. </div>
  23200. <label>
  23201. Last name:
  23202. <input type="text" name="lastName" ng-model="user.last"
  23203. ng-minlength="3" ng-maxlength="10">
  23204. </label>
  23205. <div role="alert">
  23206. <span class="error" ng-show="myForm.lastName.$error.minlength">
  23207. Too short!</span>
  23208. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  23209. Too long!</span>
  23210. </div>
  23211. </form>
  23212. <hr>
  23213. <tt>user = {{user}}</tt><br/>
  23214. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  23215. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  23216. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  23217. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  23218. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23219. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23220. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  23221. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  23222. </div>
  23223. </file>
  23224. <file name="protractor.js" type="protractor">
  23225. var user = element(by.exactBinding('user'));
  23226. var userNameValid = element(by.binding('myForm.userName.$valid'));
  23227. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  23228. var lastNameError = element(by.binding('myForm.lastName.$error'));
  23229. var formValid = element(by.binding('myForm.$valid'));
  23230. var userNameInput = element(by.model('user.name'));
  23231. var userLastInput = element(by.model('user.last'));
  23232. it('should initialize to model', function() {
  23233. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  23234. expect(userNameValid.getText()).toContain('true');
  23235. expect(formValid.getText()).toContain('true');
  23236. });
  23237. it('should be invalid if empty when required', function() {
  23238. userNameInput.clear();
  23239. userNameInput.sendKeys('');
  23240. expect(user.getText()).toContain('{"last":"visitor"}');
  23241. expect(userNameValid.getText()).toContain('false');
  23242. expect(formValid.getText()).toContain('false');
  23243. });
  23244. it('should be valid if empty when min length is set', function() {
  23245. userLastInput.clear();
  23246. userLastInput.sendKeys('');
  23247. expect(user.getText()).toContain('{"name":"guest","last":""}');
  23248. expect(lastNameValid.getText()).toContain('true');
  23249. expect(formValid.getText()).toContain('true');
  23250. });
  23251. it('should be invalid if less than required min length', function() {
  23252. userLastInput.clear();
  23253. userLastInput.sendKeys('xx');
  23254. expect(user.getText()).toContain('{"name":"guest"}');
  23255. expect(lastNameValid.getText()).toContain('false');
  23256. expect(lastNameError.getText()).toContain('minlength');
  23257. expect(formValid.getText()).toContain('false');
  23258. });
  23259. it('should be invalid if longer than max length', function() {
  23260. userLastInput.clear();
  23261. userLastInput.sendKeys('some ridiculously long name');
  23262. expect(user.getText()).toContain('{"name":"guest"}');
  23263. expect(lastNameValid.getText()).toContain('false');
  23264. expect(lastNameError.getText()).toContain('maxlength');
  23265. expect(formValid.getText()).toContain('false');
  23266. });
  23267. </file>
  23268. </example>
  23269. */
  23270. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  23271. function($browser, $sniffer, $filter, $parse) {
  23272. return {
  23273. restrict: 'E',
  23274. require: ['?ngModel'],
  23275. link: {
  23276. pre: function(scope, element, attr, ctrls) {
  23277. if (ctrls[0]) {
  23278. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  23279. $browser, $filter, $parse);
  23280. }
  23281. }
  23282. }
  23283. };
  23284. }];
  23285. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  23286. /**
  23287. * @ngdoc directive
  23288. * @name ngValue
  23289. *
  23290. * @description
  23291. * Binds the given expression to the value of the element.
  23292. *
  23293. * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
  23294. * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
  23295. * {@link select `select`} parent element) is set to the bound value. It is especially useful
  23296. * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
  23297. *
  23298. * It can also be used to achieve one-way binding of a given expression to an input element
  23299. * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
  23300. *
  23301. * @element input
  23302. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  23303. * and `value` property of the element.
  23304. *
  23305. * @example
  23306. <example name="ngValue-directive" module="valueExample">
  23307. <file name="index.html">
  23308. <script>
  23309. angular.module('valueExample', [])
  23310. .controller('ExampleController', ['$scope', function($scope) {
  23311. $scope.names = ['pizza', 'unicorns', 'robots'];
  23312. $scope.my = { favorite: 'unicorns' };
  23313. }]);
  23314. </script>
  23315. <form ng-controller="ExampleController">
  23316. <h2>Which is your favorite?</h2>
  23317. <label ng-repeat="name in names" for="{{name}}">
  23318. {{name}}
  23319. <input type="radio"
  23320. ng-model="my.favorite"
  23321. ng-value="name"
  23322. id="{{name}}"
  23323. name="favorite">
  23324. </label>
  23325. <div>You chose {{my.favorite}}</div>
  23326. </form>
  23327. </file>
  23328. <file name="protractor.js" type="protractor">
  23329. var favorite = element(by.binding('my.favorite'));
  23330. it('should initialize to model', function() {
  23331. expect(favorite.getText()).toContain('unicorns');
  23332. });
  23333. it('should bind the values to the inputs', function() {
  23334. element.all(by.model('my.favorite')).get(0).click();
  23335. expect(favorite.getText()).toContain('pizza');
  23336. });
  23337. </file>
  23338. </example>
  23339. */
  23340. var ngValueDirective = function() {
  23341. /**
  23342. * inputs use the value attribute as their default value if the value property is not set.
  23343. * Once the value property has been set (by adding input), it will not react to changes to
  23344. * the value attribute anymore. Setting both attribute and property fixes this behavior, and
  23345. * makes it possible to use ngValue as a sort of one-way bind.
  23346. */
  23347. function updateElementValue(element, attr, value) {
  23348. // Support: IE9 only
  23349. // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`).
  23350. var propValue = isDefined(value) ? value : (msie === 9) ? '' : null;
  23351. element.prop('value', propValue);
  23352. attr.$set('value', value);
  23353. }
  23354. return {
  23355. restrict: 'A',
  23356. priority: 100,
  23357. compile: function(tpl, tplAttr) {
  23358. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  23359. return function ngValueConstantLink(scope, elm, attr) {
  23360. var value = scope.$eval(attr.ngValue);
  23361. updateElementValue(elm, attr, value);
  23362. };
  23363. } else {
  23364. return function ngValueLink(scope, elm, attr) {
  23365. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  23366. updateElementValue(elm, attr, value);
  23367. });
  23368. };
  23369. }
  23370. }
  23371. };
  23372. };
  23373. /**
  23374. * @ngdoc directive
  23375. * @name ngBind
  23376. * @restrict AC
  23377. *
  23378. * @description
  23379. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  23380. * with the value of a given expression, and to update the text content when the value of that
  23381. * expression changes.
  23382. *
  23383. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  23384. * `{{ expression }}` which is similar but less verbose.
  23385. *
  23386. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  23387. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  23388. * element attribute, it makes the bindings invisible to the user while the page is loading.
  23389. *
  23390. * An alternative solution to this problem would be using the
  23391. * {@link ng.directive:ngCloak ngCloak} directive.
  23392. *
  23393. *
  23394. * @element ANY
  23395. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  23396. *
  23397. * @example
  23398. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  23399. <example module="bindExample" name="ng-bind">
  23400. <file name="index.html">
  23401. <script>
  23402. angular.module('bindExample', [])
  23403. .controller('ExampleController', ['$scope', function($scope) {
  23404. $scope.name = 'Whirled';
  23405. }]);
  23406. </script>
  23407. <div ng-controller="ExampleController">
  23408. <label>Enter name: <input type="text" ng-model="name"></label><br>
  23409. Hello <span ng-bind="name"></span>!
  23410. </div>
  23411. </file>
  23412. <file name="protractor.js" type="protractor">
  23413. it('should check ng-bind', function() {
  23414. var nameInput = element(by.model('name'));
  23415. expect(element(by.binding('name')).getText()).toBe('Whirled');
  23416. nameInput.clear();
  23417. nameInput.sendKeys('world');
  23418. expect(element(by.binding('name')).getText()).toBe('world');
  23419. });
  23420. </file>
  23421. </example>
  23422. */
  23423. var ngBindDirective = ['$compile', function($compile) {
  23424. return {
  23425. restrict: 'AC',
  23426. compile: function ngBindCompile(templateElement) {
  23427. $compile.$$addBindingClass(templateElement);
  23428. return function ngBindLink(scope, element, attr) {
  23429. $compile.$$addBindingInfo(element, attr.ngBind);
  23430. element = element[0];
  23431. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  23432. element.textContent = stringify(value);
  23433. });
  23434. };
  23435. }
  23436. };
  23437. }];
  23438. /**
  23439. * @ngdoc directive
  23440. * @name ngBindTemplate
  23441. *
  23442. * @description
  23443. * The `ngBindTemplate` directive specifies that the element
  23444. * text content should be replaced with the interpolation of the template
  23445. * in the `ngBindTemplate` attribute.
  23446. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  23447. * expressions. This directive is needed since some HTML elements
  23448. * (such as TITLE and OPTION) cannot contain SPAN elements.
  23449. *
  23450. * @element ANY
  23451. * @param {string} ngBindTemplate template of form
  23452. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  23453. *
  23454. * @example
  23455. * Try it here: enter text in text box and watch the greeting change.
  23456. <example module="bindExample" name="ng-bind-template">
  23457. <file name="index.html">
  23458. <script>
  23459. angular.module('bindExample', [])
  23460. .controller('ExampleController', ['$scope', function($scope) {
  23461. $scope.salutation = 'Hello';
  23462. $scope.name = 'World';
  23463. }]);
  23464. </script>
  23465. <div ng-controller="ExampleController">
  23466. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  23467. <label>Name: <input type="text" ng-model="name"></label><br>
  23468. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  23469. </div>
  23470. </file>
  23471. <file name="protractor.js" type="protractor">
  23472. it('should check ng-bind', function() {
  23473. var salutationElem = element(by.binding('salutation'));
  23474. var salutationInput = element(by.model('salutation'));
  23475. var nameInput = element(by.model('name'));
  23476. expect(salutationElem.getText()).toBe('Hello World!');
  23477. salutationInput.clear();
  23478. salutationInput.sendKeys('Greetings');
  23479. nameInput.clear();
  23480. nameInput.sendKeys('user');
  23481. expect(salutationElem.getText()).toBe('Greetings user!');
  23482. });
  23483. </file>
  23484. </example>
  23485. */
  23486. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  23487. return {
  23488. compile: function ngBindTemplateCompile(templateElement) {
  23489. $compile.$$addBindingClass(templateElement);
  23490. return function ngBindTemplateLink(scope, element, attr) {
  23491. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  23492. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  23493. element = element[0];
  23494. attr.$observe('ngBindTemplate', function(value) {
  23495. element.textContent = isUndefined(value) ? '' : value;
  23496. });
  23497. };
  23498. }
  23499. };
  23500. }];
  23501. /**
  23502. * @ngdoc directive
  23503. * @name ngBindHtml
  23504. *
  23505. * @description
  23506. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  23507. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  23508. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  23509. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  23510. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  23511. *
  23512. * You may also bypass sanitization for values you know are safe. To do so, bind to
  23513. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  23514. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  23515. *
  23516. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  23517. * will have an exception (instead of an exploit.)
  23518. *
  23519. * @element ANY
  23520. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  23521. *
  23522. * @example
  23523. <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
  23524. <file name="index.html">
  23525. <div ng-controller="ExampleController">
  23526. <p ng-bind-html="myHTML"></p>
  23527. </div>
  23528. </file>
  23529. <file name="script.js">
  23530. angular.module('bindHtmlExample', ['ngSanitize'])
  23531. .controller('ExampleController', ['$scope', function($scope) {
  23532. $scope.myHTML =
  23533. 'I am an <code>HTML</code>string with ' +
  23534. '<a href="#">links!</a> and other <em>stuff</em>';
  23535. }]);
  23536. </file>
  23537. <file name="protractor.js" type="protractor">
  23538. it('should check ng-bind-html', function() {
  23539. expect(element(by.binding('myHTML')).getText()).toBe(
  23540. 'I am an HTMLstring with links! and other stuff');
  23541. });
  23542. </file>
  23543. </example>
  23544. */
  23545. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  23546. return {
  23547. restrict: 'A',
  23548. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  23549. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  23550. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  23551. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  23552. return $sce.valueOf(val);
  23553. });
  23554. $compile.$$addBindingClass(tElement);
  23555. return function ngBindHtmlLink(scope, element, attr) {
  23556. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  23557. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  23558. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  23559. var value = ngBindHtmlGetter(scope);
  23560. element.html($sce.getTrustedHtml(value) || '');
  23561. });
  23562. };
  23563. }
  23564. };
  23565. }];
  23566. /**
  23567. * @ngdoc directive
  23568. * @name ngChange
  23569. *
  23570. * @description
  23571. * Evaluate the given expression when the user changes the input.
  23572. * The expression is evaluated immediately, unlike the JavaScript onchange event
  23573. * which only triggers at the end of a change (usually, when the user leaves the
  23574. * form element or presses the return key).
  23575. *
  23576. * The `ngChange` expression is only evaluated when a change in the input value causes
  23577. * a new value to be committed to the model.
  23578. *
  23579. * It will not be evaluated:
  23580. * * if the value returned from the `$parsers` transformation pipeline has not changed
  23581. * * if the input has continued to be invalid since the model will stay `null`
  23582. * * if the model is changed programmatically and not by a change to the input value
  23583. *
  23584. *
  23585. * Note, this directive requires `ngModel` to be present.
  23586. *
  23587. * @element input
  23588. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  23589. * in input value.
  23590. *
  23591. * @example
  23592. * <example name="ngChange-directive" module="changeExample">
  23593. * <file name="index.html">
  23594. * <script>
  23595. * angular.module('changeExample', [])
  23596. * .controller('ExampleController', ['$scope', function($scope) {
  23597. * $scope.counter = 0;
  23598. * $scope.change = function() {
  23599. * $scope.counter++;
  23600. * };
  23601. * }]);
  23602. * </script>
  23603. * <div ng-controller="ExampleController">
  23604. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  23605. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  23606. * <label for="ng-change-example2">Confirmed</label><br />
  23607. * <tt>debug = {{confirmed}}</tt><br/>
  23608. * <tt>counter = {{counter}}</tt><br/>
  23609. * </div>
  23610. * </file>
  23611. * <file name="protractor.js" type="protractor">
  23612. * var counter = element(by.binding('counter'));
  23613. * var debug = element(by.binding('confirmed'));
  23614. *
  23615. * it('should evaluate the expression if changing from view', function() {
  23616. * expect(counter.getText()).toContain('0');
  23617. *
  23618. * element(by.id('ng-change-example1')).click();
  23619. *
  23620. * expect(counter.getText()).toContain('1');
  23621. * expect(debug.getText()).toContain('true');
  23622. * });
  23623. *
  23624. * it('should not evaluate the expression if changing from model', function() {
  23625. * element(by.id('ng-change-example2')).click();
  23626. * expect(counter.getText()).toContain('0');
  23627. * expect(debug.getText()).toContain('true');
  23628. * });
  23629. * </file>
  23630. * </example>
  23631. */
  23632. var ngChangeDirective = valueFn({
  23633. restrict: 'A',
  23634. require: 'ngModel',
  23635. link: function(scope, element, attr, ctrl) {
  23636. ctrl.$viewChangeListeners.push(function() {
  23637. scope.$eval(attr.ngChange);
  23638. });
  23639. }
  23640. });
  23641. /* exported
  23642. ngClassDirective,
  23643. ngClassEvenDirective,
  23644. ngClassOddDirective
  23645. */
  23646. function classDirective(name, selector) {
  23647. name = 'ngClass' + name;
  23648. var indexWatchExpression;
  23649. return ['$parse', function($parse) {
  23650. return {
  23651. restrict: 'AC',
  23652. link: function(scope, element, attr) {
  23653. var classCounts = element.data('$classCounts');
  23654. var oldModulo = true;
  23655. var oldClassString;
  23656. if (!classCounts) {
  23657. // Use createMap() to prevent class assumptions involving property
  23658. // names in Object.prototype
  23659. classCounts = createMap();
  23660. element.data('$classCounts', classCounts);
  23661. }
  23662. if (name !== 'ngClass') {
  23663. if (!indexWatchExpression) {
  23664. indexWatchExpression = $parse('$index', function moduloTwo($index) {
  23665. // eslint-disable-next-line no-bitwise
  23666. return $index & 1;
  23667. });
  23668. }
  23669. scope.$watch(indexWatchExpression, ngClassIndexWatchAction);
  23670. }
  23671. scope.$watch($parse(attr[name], toClassString), ngClassWatchAction);
  23672. function addClasses(classString) {
  23673. classString = digestClassCounts(split(classString), 1);
  23674. attr.$addClass(classString);
  23675. }
  23676. function removeClasses(classString) {
  23677. classString = digestClassCounts(split(classString), -1);
  23678. attr.$removeClass(classString);
  23679. }
  23680. function updateClasses(oldClassString, newClassString) {
  23681. var oldClassArray = split(oldClassString);
  23682. var newClassArray = split(newClassString);
  23683. var toRemoveArray = arrayDifference(oldClassArray, newClassArray);
  23684. var toAddArray = arrayDifference(newClassArray, oldClassArray);
  23685. var toRemoveString = digestClassCounts(toRemoveArray, -1);
  23686. var toAddString = digestClassCounts(toAddArray, 1);
  23687. attr.$addClass(toAddString);
  23688. attr.$removeClass(toRemoveString);
  23689. }
  23690. function digestClassCounts(classArray, count) {
  23691. var classesToUpdate = [];
  23692. forEach(classArray, function(className) {
  23693. if (count > 0 || classCounts[className]) {
  23694. classCounts[className] = (classCounts[className] || 0) + count;
  23695. if (classCounts[className] === +(count > 0)) {
  23696. classesToUpdate.push(className);
  23697. }
  23698. }
  23699. });
  23700. return classesToUpdate.join(' ');
  23701. }
  23702. function ngClassIndexWatchAction(newModulo) {
  23703. // This watch-action should run before the `ngClassWatchAction()`, thus it
  23704. // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the
  23705. // `ngClassWatchAction()` will update the classes.
  23706. if (newModulo === selector) {
  23707. addClasses(oldClassString);
  23708. } else {
  23709. removeClasses(oldClassString);
  23710. }
  23711. oldModulo = newModulo;
  23712. }
  23713. function ngClassWatchAction(newClassString) {
  23714. // When using a one-time binding the newClassString will return
  23715. // the pre-interceptor value until the one-time is complete
  23716. if (!isString(newClassString)) {
  23717. newClassString = toClassString(newClassString);
  23718. }
  23719. if (oldModulo === selector) {
  23720. updateClasses(oldClassString, newClassString);
  23721. }
  23722. oldClassString = newClassString;
  23723. }
  23724. }
  23725. };
  23726. }];
  23727. // Helpers
  23728. function arrayDifference(tokens1, tokens2) {
  23729. if (!tokens1 || !tokens1.length) return [];
  23730. if (!tokens2 || !tokens2.length) return tokens1;
  23731. var values = [];
  23732. outer:
  23733. for (var i = 0; i < tokens1.length; i++) {
  23734. var token = tokens1[i];
  23735. for (var j = 0; j < tokens2.length; j++) {
  23736. if (token === tokens2[j]) continue outer;
  23737. }
  23738. values.push(token);
  23739. }
  23740. return values;
  23741. }
  23742. function split(classString) {
  23743. return classString && classString.split(' ');
  23744. }
  23745. function toClassString(classValue) {
  23746. var classString = classValue;
  23747. if (isArray(classValue)) {
  23748. classString = classValue.map(toClassString).join(' ');
  23749. } else if (isObject(classValue)) {
  23750. classString = Object.keys(classValue).
  23751. filter(function(key) { return classValue[key]; }).
  23752. join(' ');
  23753. }
  23754. return classString;
  23755. }
  23756. }
  23757. /**
  23758. * @ngdoc directive
  23759. * @name ngClass
  23760. * @restrict AC
  23761. *
  23762. * @description
  23763. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  23764. * an expression that represents all classes to be added.
  23765. *
  23766. * The directive operates in three different ways, depending on which of three types the expression
  23767. * evaluates to:
  23768. *
  23769. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  23770. * names.
  23771. *
  23772. * 2. If the expression evaluates to an object, then for each key-value pair of the
  23773. * object with a truthy value the corresponding key is used as a class name.
  23774. *
  23775. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  23776. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  23777. * to give you more control over what CSS classes appear. See the code below for an example of this.
  23778. *
  23779. *
  23780. * The directive won't add duplicate classes if a particular class was already set.
  23781. *
  23782. * When the expression changes, the previously added classes are removed and only then are the
  23783. * new classes added.
  23784. *
  23785. * @knownIssue
  23786. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  23787. * attribute, when using the `ngClass` directive on the same element.
  23788. * See {@link guide/interpolation#known-issues here} for more info.
  23789. *
  23790. * @animations
  23791. * | Animation | Occurs |
  23792. * |----------------------------------|-------------------------------------|
  23793. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  23794. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  23795. *
  23796. * @element ANY
  23797. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  23798. * of the evaluation can be a string representing space delimited class
  23799. * names, an array, or a map of class names to boolean values. In the case of a map, the
  23800. * names of the properties whose values are truthy will be added as css classes to the
  23801. * element.
  23802. *
  23803. * @example Example that demonstrates basic bindings via ngClass directive.
  23804. <example name="ng-class">
  23805. <file name="index.html">
  23806. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  23807. <label>
  23808. <input type="checkbox" ng-model="deleted">
  23809. deleted (apply "strike" class)
  23810. </label><br>
  23811. <label>
  23812. <input type="checkbox" ng-model="important">
  23813. important (apply "bold" class)
  23814. </label><br>
  23815. <label>
  23816. <input type="checkbox" ng-model="error">
  23817. error (apply "has-error" class)
  23818. </label>
  23819. <hr>
  23820. <p ng-class="style">Using String Syntax</p>
  23821. <input type="text" ng-model="style"
  23822. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  23823. <hr>
  23824. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  23825. <input ng-model="style1"
  23826. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  23827. <input ng-model="style2"
  23828. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  23829. <input ng-model="style3"
  23830. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  23831. <hr>
  23832. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  23833. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  23834. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  23835. </file>
  23836. <file name="style.css">
  23837. .strike {
  23838. text-decoration: line-through;
  23839. }
  23840. .bold {
  23841. font-weight: bold;
  23842. }
  23843. .red {
  23844. color: red;
  23845. }
  23846. .has-error {
  23847. color: red;
  23848. background-color: yellow;
  23849. }
  23850. .orange {
  23851. color: orange;
  23852. }
  23853. </file>
  23854. <file name="protractor.js" type="protractor">
  23855. var ps = element.all(by.css('p'));
  23856. it('should let you toggle the class', function() {
  23857. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  23858. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  23859. element(by.model('important')).click();
  23860. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  23861. element(by.model('error')).click();
  23862. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  23863. });
  23864. it('should let you toggle string example', function() {
  23865. expect(ps.get(1).getAttribute('class')).toBe('');
  23866. element(by.model('style')).clear();
  23867. element(by.model('style')).sendKeys('red');
  23868. expect(ps.get(1).getAttribute('class')).toBe('red');
  23869. });
  23870. it('array example should have 3 classes', function() {
  23871. expect(ps.get(2).getAttribute('class')).toBe('');
  23872. element(by.model('style1')).sendKeys('bold');
  23873. element(by.model('style2')).sendKeys('strike');
  23874. element(by.model('style3')).sendKeys('red');
  23875. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  23876. });
  23877. it('array with map example should have 2 classes', function() {
  23878. expect(ps.last().getAttribute('class')).toBe('');
  23879. element(by.model('style4')).sendKeys('bold');
  23880. element(by.model('warning')).click();
  23881. expect(ps.last().getAttribute('class')).toBe('bold orange');
  23882. });
  23883. </file>
  23884. </example>
  23885. ## Animations
  23886. The example below demonstrates how to perform animations using ngClass.
  23887. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
  23888. <file name="index.html">
  23889. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  23890. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  23891. <br>
  23892. <span class="base-class" ng-class="myVar">Sample Text</span>
  23893. </file>
  23894. <file name="style.css">
  23895. .base-class {
  23896. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23897. }
  23898. .base-class.my-class {
  23899. color: red;
  23900. font-size:3em;
  23901. }
  23902. </file>
  23903. <file name="protractor.js" type="protractor">
  23904. it('should check ng-class', function() {
  23905. expect(element(by.css('.base-class')).getAttribute('class')).not.
  23906. toMatch(/my-class/);
  23907. element(by.id('setbtn')).click();
  23908. expect(element(by.css('.base-class')).getAttribute('class')).
  23909. toMatch(/my-class/);
  23910. element(by.id('clearbtn')).click();
  23911. expect(element(by.css('.base-class')).getAttribute('class')).not.
  23912. toMatch(/my-class/);
  23913. });
  23914. </file>
  23915. </example>
  23916. ## ngClass and pre-existing CSS3 Transitions/Animations
  23917. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  23918. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  23919. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  23920. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  23921. {@link $animate#removeClass $animate.removeClass}.
  23922. */
  23923. var ngClassDirective = classDirective('', true);
  23924. /**
  23925. * @ngdoc directive
  23926. * @name ngClassOdd
  23927. * @restrict AC
  23928. *
  23929. * @description
  23930. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23931. * {@link ng.directive:ngClass ngClass}, except they work in
  23932. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23933. *
  23934. * This directive can be applied only within the scope of an
  23935. * {@link ng.directive:ngRepeat ngRepeat}.
  23936. *
  23937. * @element ANY
  23938. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  23939. * of the evaluation can be a string representing space delimited class names or an array.
  23940. *
  23941. * @example
  23942. <example name="ng-class-odd">
  23943. <file name="index.html">
  23944. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23945. <li ng-repeat="name in names">
  23946. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23947. {{name}}
  23948. </span>
  23949. </li>
  23950. </ol>
  23951. </file>
  23952. <file name="style.css">
  23953. .odd {
  23954. color: red;
  23955. }
  23956. .even {
  23957. color: blue;
  23958. }
  23959. </file>
  23960. <file name="protractor.js" type="protractor">
  23961. it('should check ng-class-odd and ng-class-even', function() {
  23962. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  23963. toMatch(/odd/);
  23964. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  23965. toMatch(/even/);
  23966. });
  23967. </file>
  23968. </example>
  23969. */
  23970. var ngClassOddDirective = classDirective('Odd', 0);
  23971. /**
  23972. * @ngdoc directive
  23973. * @name ngClassEven
  23974. * @restrict AC
  23975. *
  23976. * @description
  23977. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23978. * {@link ng.directive:ngClass ngClass}, except they work in
  23979. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23980. *
  23981. * This directive can be applied only within the scope of an
  23982. * {@link ng.directive:ngRepeat ngRepeat}.
  23983. *
  23984. * @element ANY
  23985. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  23986. * result of the evaluation can be a string representing space delimited class names or an array.
  23987. *
  23988. * @example
  23989. <example name="ng-class-even">
  23990. <file name="index.html">
  23991. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23992. <li ng-repeat="name in names">
  23993. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23994. {{name}} &nbsp; &nbsp; &nbsp;
  23995. </span>
  23996. </li>
  23997. </ol>
  23998. </file>
  23999. <file name="style.css">
  24000. .odd {
  24001. color: red;
  24002. }
  24003. .even {
  24004. color: blue;
  24005. }
  24006. </file>
  24007. <file name="protractor.js" type="protractor">
  24008. it('should check ng-class-odd and ng-class-even', function() {
  24009. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  24010. toMatch(/odd/);
  24011. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  24012. toMatch(/even/);
  24013. });
  24014. </file>
  24015. </example>
  24016. */
  24017. var ngClassEvenDirective = classDirective('Even', 1);
  24018. /**
  24019. * @ngdoc directive
  24020. * @name ngCloak
  24021. * @restrict AC
  24022. *
  24023. * @description
  24024. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  24025. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  24026. * directive to avoid the undesirable flicker effect caused by the html template display.
  24027. *
  24028. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  24029. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  24030. * of the browser view.
  24031. *
  24032. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  24033. * `angular.min.js`.
  24034. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24035. *
  24036. * ```css
  24037. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  24038. * display: none !important;
  24039. * }
  24040. * ```
  24041. *
  24042. * When this css rule is loaded by the browser, all html elements (including their children) that
  24043. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  24044. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  24045. * the compiled element visible.
  24046. *
  24047. * For the best result, the `angular.js` script must be loaded in the head section of the html
  24048. * document; alternatively, the css rule above must be included in the external stylesheet of the
  24049. * application.
  24050. *
  24051. * @element ANY
  24052. *
  24053. * @example
  24054. <example name="ng-cloak">
  24055. <file name="index.html">
  24056. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  24057. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  24058. </file>
  24059. <file name="protractor.js" type="protractor">
  24060. it('should remove the template directive and css class', function() {
  24061. expect($('#template1').getAttribute('ng-cloak')).
  24062. toBeNull();
  24063. expect($('#template2').getAttribute('ng-cloak')).
  24064. toBeNull();
  24065. });
  24066. </file>
  24067. </example>
  24068. *
  24069. */
  24070. var ngCloakDirective = ngDirective({
  24071. compile: function(element, attr) {
  24072. attr.$set('ngCloak', undefined);
  24073. element.removeClass('ng-cloak');
  24074. }
  24075. });
  24076. /**
  24077. * @ngdoc directive
  24078. * @name ngController
  24079. *
  24080. * @description
  24081. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  24082. * supports the principles behind the Model-View-Controller design pattern.
  24083. *
  24084. * MVC components in angular:
  24085. *
  24086. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  24087. * are accessed through bindings.
  24088. * * View — The template (HTML with data bindings) that is rendered into the View.
  24089. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  24090. * logic behind the application to decorate the scope with functions and values
  24091. *
  24092. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  24093. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  24094. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  24095. * and executed twice.
  24096. *
  24097. * @element ANY
  24098. * @scope
  24099. * @priority 500
  24100. * @param {expression} ngController Name of a constructor function registered with the current
  24101. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  24102. * that on the current scope evaluates to a constructor function.
  24103. *
  24104. * The controller instance can be published into a scope property by specifying
  24105. * `ng-controller="as propertyName"`.
  24106. *
  24107. * If the current `$controllerProvider` is configured to use globals (via
  24108. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  24109. * also be the name of a globally accessible constructor function (deprecated, not recommended).
  24110. *
  24111. * @example
  24112. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  24113. * greeting are methods declared on the controller (see source tab). These methods can
  24114. * easily be called from the angular markup. Any changes to the data are automatically reflected
  24115. * in the View without the need for a manual update.
  24116. *
  24117. * Two different declaration styles are included below:
  24118. *
  24119. * * one binds methods and properties directly onto the controller using `this`:
  24120. * `ng-controller="SettingsController1 as settings"`
  24121. * * one injects `$scope` into the controller:
  24122. * `ng-controller="SettingsController2"`
  24123. *
  24124. * The second option is more common in the Angular community, and is generally used in boilerplates
  24125. * and in this guide. However, there are advantages to binding properties directly to the controller
  24126. * and avoiding scope.
  24127. *
  24128. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  24129. * multiple controllers apply to an element.
  24130. * * If you are writing your controllers as classes you have easier access to the properties and
  24131. * methods, which will appear on the scope, from inside the controller code.
  24132. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  24133. * inheritance masking primitives.
  24134. *
  24135. * This example demonstrates the `controller as` syntax.
  24136. *
  24137. * <example name="ngControllerAs" module="controllerAsExample">
  24138. * <file name="index.html">
  24139. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  24140. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  24141. * <button ng-click="settings.greet()">greet</button><br/>
  24142. * Contact:
  24143. * <ul>
  24144. * <li ng-repeat="contact in settings.contacts">
  24145. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  24146. * <option>phone</option>
  24147. * <option>email</option>
  24148. * </select>
  24149. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24150. * <button ng-click="settings.clearContact(contact)">clear</button>
  24151. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  24152. * </li>
  24153. * <li><button ng-click="settings.addContact()">add</button></li>
  24154. * </ul>
  24155. * </div>
  24156. * </file>
  24157. * <file name="app.js">
  24158. * angular.module('controllerAsExample', [])
  24159. * .controller('SettingsController1', SettingsController1);
  24160. *
  24161. * function SettingsController1() {
  24162. * this.name = 'John Smith';
  24163. * this.contacts = [
  24164. * {type: 'phone', value: '408 555 1212'},
  24165. * {type: 'email', value: 'john.smith@example.org'}
  24166. * ];
  24167. * }
  24168. *
  24169. * SettingsController1.prototype.greet = function() {
  24170. * alert(this.name);
  24171. * };
  24172. *
  24173. * SettingsController1.prototype.addContact = function() {
  24174. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  24175. * };
  24176. *
  24177. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  24178. * var index = this.contacts.indexOf(contactToRemove);
  24179. * this.contacts.splice(index, 1);
  24180. * };
  24181. *
  24182. * SettingsController1.prototype.clearContact = function(contact) {
  24183. * contact.type = 'phone';
  24184. * contact.value = '';
  24185. * };
  24186. * </file>
  24187. * <file name="protractor.js" type="protractor">
  24188. * it('should check controller as', function() {
  24189. * var container = element(by.id('ctrl-as-exmpl'));
  24190. * expect(container.element(by.model('settings.name'))
  24191. * .getAttribute('value')).toBe('John Smith');
  24192. *
  24193. * var firstRepeat =
  24194. * container.element(by.repeater('contact in settings.contacts').row(0));
  24195. * var secondRepeat =
  24196. * container.element(by.repeater('contact in settings.contacts').row(1));
  24197. *
  24198. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24199. * .toBe('408 555 1212');
  24200. *
  24201. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24202. * .toBe('john.smith@example.org');
  24203. *
  24204. * firstRepeat.element(by.buttonText('clear')).click();
  24205. *
  24206. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24207. * .toBe('');
  24208. *
  24209. * container.element(by.buttonText('add')).click();
  24210. *
  24211. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  24212. * .element(by.model('contact.value'))
  24213. * .getAttribute('value'))
  24214. * .toBe('yourname@example.org');
  24215. * });
  24216. * </file>
  24217. * </example>
  24218. *
  24219. * This example demonstrates the "attach to `$scope`" style of controller.
  24220. *
  24221. * <example name="ngController" module="controllerExample">
  24222. * <file name="index.html">
  24223. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  24224. * <label>Name: <input type="text" ng-model="name"/></label>
  24225. * <button ng-click="greet()">greet</button><br/>
  24226. * Contact:
  24227. * <ul>
  24228. * <li ng-repeat="contact in contacts">
  24229. * <select ng-model="contact.type" id="select_{{$index}}">
  24230. * <option>phone</option>
  24231. * <option>email</option>
  24232. * </select>
  24233. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24234. * <button ng-click="clearContact(contact)">clear</button>
  24235. * <button ng-click="removeContact(contact)">X</button>
  24236. * </li>
  24237. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  24238. * </ul>
  24239. * </div>
  24240. * </file>
  24241. * <file name="app.js">
  24242. * angular.module('controllerExample', [])
  24243. * .controller('SettingsController2', ['$scope', SettingsController2]);
  24244. *
  24245. * function SettingsController2($scope) {
  24246. * $scope.name = 'John Smith';
  24247. * $scope.contacts = [
  24248. * {type:'phone', value:'408 555 1212'},
  24249. * {type:'email', value:'john.smith@example.org'}
  24250. * ];
  24251. *
  24252. * $scope.greet = function() {
  24253. * alert($scope.name);
  24254. * };
  24255. *
  24256. * $scope.addContact = function() {
  24257. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  24258. * };
  24259. *
  24260. * $scope.removeContact = function(contactToRemove) {
  24261. * var index = $scope.contacts.indexOf(contactToRemove);
  24262. * $scope.contacts.splice(index, 1);
  24263. * };
  24264. *
  24265. * $scope.clearContact = function(contact) {
  24266. * contact.type = 'phone';
  24267. * contact.value = '';
  24268. * };
  24269. * }
  24270. * </file>
  24271. * <file name="protractor.js" type="protractor">
  24272. * it('should check controller', function() {
  24273. * var container = element(by.id('ctrl-exmpl'));
  24274. *
  24275. * expect(container.element(by.model('name'))
  24276. * .getAttribute('value')).toBe('John Smith');
  24277. *
  24278. * var firstRepeat =
  24279. * container.element(by.repeater('contact in contacts').row(0));
  24280. * var secondRepeat =
  24281. * container.element(by.repeater('contact in contacts').row(1));
  24282. *
  24283. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24284. * .toBe('408 555 1212');
  24285. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24286. * .toBe('john.smith@example.org');
  24287. *
  24288. * firstRepeat.element(by.buttonText('clear')).click();
  24289. *
  24290. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24291. * .toBe('');
  24292. *
  24293. * container.element(by.buttonText('add')).click();
  24294. *
  24295. * expect(container.element(by.repeater('contact in contacts').row(2))
  24296. * .element(by.model('contact.value'))
  24297. * .getAttribute('value'))
  24298. * .toBe('yourname@example.org');
  24299. * });
  24300. * </file>
  24301. *</example>
  24302. */
  24303. var ngControllerDirective = [function() {
  24304. return {
  24305. restrict: 'A',
  24306. scope: true,
  24307. controller: '@',
  24308. priority: 500
  24309. };
  24310. }];
  24311. /**
  24312. * @ngdoc directive
  24313. * @name ngCsp
  24314. *
  24315. * @restrict A
  24316. * @element ANY
  24317. * @description
  24318. *
  24319. * Angular has some features that can conflict with certain restrictions that are applied when using
  24320. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  24321. *
  24322. * If you intend to implement CSP with these rules then you must tell Angular not to use these
  24323. * features.
  24324. *
  24325. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  24326. *
  24327. *
  24328. * The following default rules in CSP affect Angular:
  24329. *
  24330. * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
  24331. * code from strings is forbidden. Angular makes use of this in the {@link $parse} service to
  24332. * provide a 30% increase in the speed of evaluating Angular expressions. (This CSP rule can be
  24333. * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
  24334. * weaken the protections offered by CSP.)
  24335. *
  24336. * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
  24337. * This prevents apps from injecting custom styles directly into the document. Angular makes use of
  24338. * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
  24339. * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
  24340. * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
  24341. * it is generally not recommended as it would weaken the protections offered by CSP.)
  24342. *
  24343. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking dynamic code
  24344. * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
  24345. * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
  24346. * CSP error to be logged in the console:
  24347. *
  24348. * ```
  24349. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  24350. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  24351. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  24352. * ```
  24353. *
  24354. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  24355. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  24356. * the `angular.js` file.
  24357. *
  24358. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  24359. *
  24360. * You can specify which of the CSP related Angular features should be deactivated by providing
  24361. * a value for the `ng-csp` attribute. The options are as follows:
  24362. *
  24363. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  24364. *
  24365. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  24366. *
  24367. * You can use these values in the following combinations:
  24368. *
  24369. *
  24370. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  24371. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
  24372. * versions of Angular.
  24373. *
  24374. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  24375. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
  24376. * versions of Angular.
  24377. *
  24378. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can
  24379. * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  24380. *
  24381. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  24382. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  24383. *
  24384. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  24385. * styles nor use eval, which is the same as an empty: ng-csp.
  24386. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  24387. *
  24388. * @example
  24389. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  24390. ```html
  24391. <!doctype html>
  24392. <html ng-app ng-csp>
  24393. ...
  24394. ...
  24395. </html>
  24396. ```
  24397. * @example
  24398. <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
  24399. <example name="example.csp" module="cspExample" ng-csp="true">
  24400. <file name="index.html">
  24401. <div ng-controller="MainController as ctrl">
  24402. <div>
  24403. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  24404. <span id="counter">
  24405. {{ctrl.counter}}
  24406. </span>
  24407. </div>
  24408. <div>
  24409. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  24410. <span id="evilError">
  24411. {{ctrl.evilError}}
  24412. </span>
  24413. </div>
  24414. </div>
  24415. </file>
  24416. <file name="script.js">
  24417. angular.module('cspExample', [])
  24418. .controller('MainController', function MainController() {
  24419. this.counter = 0;
  24420. this.inc = function() {
  24421. this.counter++;
  24422. };
  24423. this.evil = function() {
  24424. try {
  24425. eval('1+2'); // eslint-disable-line no-eval
  24426. } catch (e) {
  24427. this.evilError = e.message;
  24428. }
  24429. };
  24430. });
  24431. </file>
  24432. <file name="protractor.js" type="protractor">
  24433. var util, webdriver;
  24434. var incBtn = element(by.id('inc'));
  24435. var counter = element(by.id('counter'));
  24436. var evilBtn = element(by.id('evil'));
  24437. var evilError = element(by.id('evilError'));
  24438. function getAndClearSevereErrors() {
  24439. return browser.manage().logs().get('browser').then(function(browserLog) {
  24440. return browserLog.filter(function(logEntry) {
  24441. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  24442. });
  24443. });
  24444. }
  24445. function clearErrors() {
  24446. getAndClearSevereErrors();
  24447. }
  24448. function expectNoErrors() {
  24449. getAndClearSevereErrors().then(function(filteredLog) {
  24450. expect(filteredLog.length).toEqual(0);
  24451. if (filteredLog.length) {
  24452. console.log('browser console errors: ' + util.inspect(filteredLog));
  24453. }
  24454. });
  24455. }
  24456. function expectError(regex) {
  24457. getAndClearSevereErrors().then(function(filteredLog) {
  24458. var found = false;
  24459. filteredLog.forEach(function(log) {
  24460. if (log.message.match(regex)) {
  24461. found = true;
  24462. }
  24463. });
  24464. if (!found) {
  24465. throw new Error('expected an error that matches ' + regex);
  24466. }
  24467. });
  24468. }
  24469. beforeEach(function() {
  24470. util = require('util');
  24471. webdriver = require('selenium-webdriver');
  24472. });
  24473. // For now, we only test on Chrome,
  24474. // as Safari does not load the page with Protractor's injected scripts,
  24475. // and Firefox webdriver always disables content security policy (#6358)
  24476. if (browser.params.browser !== 'chrome') {
  24477. return;
  24478. }
  24479. it('should not report errors when the page is loaded', function() {
  24480. // clear errors so we are not dependent on previous tests
  24481. clearErrors();
  24482. // Need to reload the page as the page is already loaded when
  24483. // we come here
  24484. browser.driver.getCurrentUrl().then(function(url) {
  24485. browser.get(url);
  24486. });
  24487. expectNoErrors();
  24488. });
  24489. it('should evaluate expressions', function() {
  24490. expect(counter.getText()).toEqual('0');
  24491. incBtn.click();
  24492. expect(counter.getText()).toEqual('1');
  24493. expectNoErrors();
  24494. });
  24495. it('should throw and report an error when using "eval"', function() {
  24496. evilBtn.click();
  24497. expect(evilError.getText()).toMatch(/Content Security Policy/);
  24498. expectError(/Content Security Policy/);
  24499. });
  24500. </file>
  24501. </example>
  24502. */
  24503. // `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
  24504. // we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
  24505. // fn that looks for the `ng-csp` attribute anywhere in the current doc.
  24506. /**
  24507. * @ngdoc directive
  24508. * @name ngClick
  24509. *
  24510. * @description
  24511. * The ngClick directive allows you to specify custom behavior when
  24512. * an element is clicked.
  24513. *
  24514. * @element ANY
  24515. * @priority 0
  24516. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  24517. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  24518. *
  24519. * @example
  24520. <example name="ng-click">
  24521. <file name="index.html">
  24522. <button ng-click="count = count + 1" ng-init="count=0">
  24523. Increment
  24524. </button>
  24525. <span>
  24526. count: {{count}}
  24527. </span>
  24528. </file>
  24529. <file name="protractor.js" type="protractor">
  24530. it('should check ng-click', function() {
  24531. expect(element(by.binding('count')).getText()).toMatch('0');
  24532. element(by.css('button')).click();
  24533. expect(element(by.binding('count')).getText()).toMatch('1');
  24534. });
  24535. </file>
  24536. </example>
  24537. */
  24538. /*
  24539. * A collection of directives that allows creation of custom event handlers that are defined as
  24540. * angular expressions and are compiled and executed within the current scope.
  24541. */
  24542. var ngEventDirectives = {};
  24543. // For events that might fire synchronously during DOM manipulation
  24544. // we need to execute their event handlers asynchronously using $evalAsync,
  24545. // so that they are not executed in an inconsistent state.
  24546. var forceAsyncEvents = {
  24547. 'blur': true,
  24548. 'focus': true
  24549. };
  24550. forEach(
  24551. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  24552. function(eventName) {
  24553. var directiveName = directiveNormalize('ng-' + eventName);
  24554. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  24555. return {
  24556. restrict: 'A',
  24557. compile: function($element, attr) {
  24558. // NOTE:
  24559. // We expose the powerful `$event` object on the scope that provides access to the Window,
  24560. // etc. This is OK, because expressions are not sandboxed any more (and the expression
  24561. // sandbox was never meant to be a security feature anyway).
  24562. var fn = $parse(attr[directiveName]);
  24563. return function ngEventHandler(scope, element) {
  24564. element.on(eventName, function(event) {
  24565. var callback = function() {
  24566. fn(scope, {$event: event});
  24567. };
  24568. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  24569. scope.$evalAsync(callback);
  24570. } else {
  24571. scope.$apply(callback);
  24572. }
  24573. });
  24574. };
  24575. }
  24576. };
  24577. }];
  24578. }
  24579. );
  24580. /**
  24581. * @ngdoc directive
  24582. * @name ngDblclick
  24583. *
  24584. * @description
  24585. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  24586. *
  24587. * @element ANY
  24588. * @priority 0
  24589. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  24590. * a dblclick. (The Event object is available as `$event`)
  24591. *
  24592. * @example
  24593. <example name="ng-dblclick">
  24594. <file name="index.html">
  24595. <button ng-dblclick="count = count + 1" ng-init="count=0">
  24596. Increment (on double click)
  24597. </button>
  24598. count: {{count}}
  24599. </file>
  24600. </example>
  24601. */
  24602. /**
  24603. * @ngdoc directive
  24604. * @name ngMousedown
  24605. *
  24606. * @description
  24607. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  24608. *
  24609. * @element ANY
  24610. * @priority 0
  24611. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  24612. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  24613. *
  24614. * @example
  24615. <example name="ng-mousedown">
  24616. <file name="index.html">
  24617. <button ng-mousedown="count = count + 1" ng-init="count=0">
  24618. Increment (on mouse down)
  24619. </button>
  24620. count: {{count}}
  24621. </file>
  24622. </example>
  24623. */
  24624. /**
  24625. * @ngdoc directive
  24626. * @name ngMouseup
  24627. *
  24628. * @description
  24629. * Specify custom behavior on mouseup event.
  24630. *
  24631. * @element ANY
  24632. * @priority 0
  24633. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  24634. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  24635. *
  24636. * @example
  24637. <example name="ng-mouseup">
  24638. <file name="index.html">
  24639. <button ng-mouseup="count = count + 1" ng-init="count=0">
  24640. Increment (on mouse up)
  24641. </button>
  24642. count: {{count}}
  24643. </file>
  24644. </example>
  24645. */
  24646. /**
  24647. * @ngdoc directive
  24648. * @name ngMouseover
  24649. *
  24650. * @description
  24651. * Specify custom behavior on mouseover event.
  24652. *
  24653. * @element ANY
  24654. * @priority 0
  24655. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  24656. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  24657. *
  24658. * @example
  24659. <example name="ng-mouseover">
  24660. <file name="index.html">
  24661. <button ng-mouseover="count = count + 1" ng-init="count=0">
  24662. Increment (when mouse is over)
  24663. </button>
  24664. count: {{count}}
  24665. </file>
  24666. </example>
  24667. */
  24668. /**
  24669. * @ngdoc directive
  24670. * @name ngMouseenter
  24671. *
  24672. * @description
  24673. * Specify custom behavior on mouseenter event.
  24674. *
  24675. * @element ANY
  24676. * @priority 0
  24677. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  24678. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  24679. *
  24680. * @example
  24681. <example name="ng-mouseenter">
  24682. <file name="index.html">
  24683. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  24684. Increment (when mouse enters)
  24685. </button>
  24686. count: {{count}}
  24687. </file>
  24688. </example>
  24689. */
  24690. /**
  24691. * @ngdoc directive
  24692. * @name ngMouseleave
  24693. *
  24694. * @description
  24695. * Specify custom behavior on mouseleave event.
  24696. *
  24697. * @element ANY
  24698. * @priority 0
  24699. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  24700. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  24701. *
  24702. * @example
  24703. <example name="ng-mouseleave">
  24704. <file name="index.html">
  24705. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  24706. Increment (when mouse leaves)
  24707. </button>
  24708. count: {{count}}
  24709. </file>
  24710. </example>
  24711. */
  24712. /**
  24713. * @ngdoc directive
  24714. * @name ngMousemove
  24715. *
  24716. * @description
  24717. * Specify custom behavior on mousemove event.
  24718. *
  24719. * @element ANY
  24720. * @priority 0
  24721. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  24722. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  24723. *
  24724. * @example
  24725. <example name="ng-mousemove">
  24726. <file name="index.html">
  24727. <button ng-mousemove="count = count + 1" ng-init="count=0">
  24728. Increment (when mouse moves)
  24729. </button>
  24730. count: {{count}}
  24731. </file>
  24732. </example>
  24733. */
  24734. /**
  24735. * @ngdoc directive
  24736. * @name ngKeydown
  24737. *
  24738. * @description
  24739. * Specify custom behavior on keydown event.
  24740. *
  24741. * @element ANY
  24742. * @priority 0
  24743. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  24744. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  24745. *
  24746. * @example
  24747. <example name="ng-keydown">
  24748. <file name="index.html">
  24749. <input ng-keydown="count = count + 1" ng-init="count=0">
  24750. key down count: {{count}}
  24751. </file>
  24752. </example>
  24753. */
  24754. /**
  24755. * @ngdoc directive
  24756. * @name ngKeyup
  24757. *
  24758. * @description
  24759. * Specify custom behavior on keyup event.
  24760. *
  24761. * @element ANY
  24762. * @priority 0
  24763. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  24764. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  24765. *
  24766. * @example
  24767. <example name="ng-keyup">
  24768. <file name="index.html">
  24769. <p>Typing in the input box below updates the key count</p>
  24770. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  24771. <p>Typing in the input box below updates the keycode</p>
  24772. <input ng-keyup="event=$event">
  24773. <p>event keyCode: {{ event.keyCode }}</p>
  24774. <p>event altKey: {{ event.altKey }}</p>
  24775. </file>
  24776. </example>
  24777. */
  24778. /**
  24779. * @ngdoc directive
  24780. * @name ngKeypress
  24781. *
  24782. * @description
  24783. * Specify custom behavior on keypress event.
  24784. *
  24785. * @element ANY
  24786. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  24787. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  24788. * and can be interrogated for keyCode, altKey, etc.)
  24789. *
  24790. * @example
  24791. <example name="ng-keypress">
  24792. <file name="index.html">
  24793. <input ng-keypress="count = count + 1" ng-init="count=0">
  24794. key press count: {{count}}
  24795. </file>
  24796. </example>
  24797. */
  24798. /**
  24799. * @ngdoc directive
  24800. * @name ngSubmit
  24801. *
  24802. * @description
  24803. * Enables binding angular expressions to onsubmit events.
  24804. *
  24805. * Additionally it prevents the default action (which for form means sending the request to the
  24806. * server and reloading the current page), but only if the form does not contain `action`,
  24807. * `data-action`, or `x-action` attributes.
  24808. *
  24809. * <div class="alert alert-warning">
  24810. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  24811. * `ngSubmit` handlers together. See the
  24812. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  24813. * for a detailed discussion of when `ngSubmit` may be triggered.
  24814. * </div>
  24815. *
  24816. * @element form
  24817. * @priority 0
  24818. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  24819. * ({@link guide/expression#-event- Event object is available as `$event`})
  24820. *
  24821. * @example
  24822. <example module="submitExample" name="ng-submit">
  24823. <file name="index.html">
  24824. <script>
  24825. angular.module('submitExample', [])
  24826. .controller('ExampleController', ['$scope', function($scope) {
  24827. $scope.list = [];
  24828. $scope.text = 'hello';
  24829. $scope.submit = function() {
  24830. if ($scope.text) {
  24831. $scope.list.push(this.text);
  24832. $scope.text = '';
  24833. }
  24834. };
  24835. }]);
  24836. </script>
  24837. <form ng-submit="submit()" ng-controller="ExampleController">
  24838. Enter text and hit enter:
  24839. <input type="text" ng-model="text" name="text" />
  24840. <input type="submit" id="submit" value="Submit" />
  24841. <pre>list={{list}}</pre>
  24842. </form>
  24843. </file>
  24844. <file name="protractor.js" type="protractor">
  24845. it('should check ng-submit', function() {
  24846. expect(element(by.binding('list')).getText()).toBe('list=[]');
  24847. element(by.css('#submit')).click();
  24848. expect(element(by.binding('list')).getText()).toContain('hello');
  24849. expect(element(by.model('text')).getAttribute('value')).toBe('');
  24850. });
  24851. it('should ignore empty strings', function() {
  24852. expect(element(by.binding('list')).getText()).toBe('list=[]');
  24853. element(by.css('#submit')).click();
  24854. element(by.css('#submit')).click();
  24855. expect(element(by.binding('list')).getText()).toContain('hello');
  24856. });
  24857. </file>
  24858. </example>
  24859. */
  24860. /**
  24861. * @ngdoc directive
  24862. * @name ngFocus
  24863. *
  24864. * @description
  24865. * Specify custom behavior on focus event.
  24866. *
  24867. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  24868. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  24869. * during an `$apply` to ensure a consistent state.
  24870. *
  24871. * @element window, input, select, textarea, a
  24872. * @priority 0
  24873. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  24874. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  24875. *
  24876. * @example
  24877. * See {@link ng.directive:ngClick ngClick}
  24878. */
  24879. /**
  24880. * @ngdoc directive
  24881. * @name ngBlur
  24882. *
  24883. * @description
  24884. * Specify custom behavior on blur event.
  24885. *
  24886. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  24887. * an element has lost focus.
  24888. *
  24889. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  24890. * (e.g. removing a focussed input),
  24891. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  24892. * during an `$apply` to ensure a consistent state.
  24893. *
  24894. * @element window, input, select, textarea, a
  24895. * @priority 0
  24896. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  24897. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  24898. *
  24899. * @example
  24900. * See {@link ng.directive:ngClick ngClick}
  24901. */
  24902. /**
  24903. * @ngdoc directive
  24904. * @name ngCopy
  24905. *
  24906. * @description
  24907. * Specify custom behavior on copy event.
  24908. *
  24909. * @element window, input, select, textarea, a
  24910. * @priority 0
  24911. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  24912. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  24913. *
  24914. * @example
  24915. <example name="ng-copy">
  24916. <file name="index.html">
  24917. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  24918. copied: {{copied}}
  24919. </file>
  24920. </example>
  24921. */
  24922. /**
  24923. * @ngdoc directive
  24924. * @name ngCut
  24925. *
  24926. * @description
  24927. * Specify custom behavior on cut event.
  24928. *
  24929. * @element window, input, select, textarea, a
  24930. * @priority 0
  24931. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  24932. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  24933. *
  24934. * @example
  24935. <example name="ng-cut">
  24936. <file name="index.html">
  24937. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  24938. cut: {{cut}}
  24939. </file>
  24940. </example>
  24941. */
  24942. /**
  24943. * @ngdoc directive
  24944. * @name ngPaste
  24945. *
  24946. * @description
  24947. * Specify custom behavior on paste event.
  24948. *
  24949. * @element window, input, select, textarea, a
  24950. * @priority 0
  24951. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  24952. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  24953. *
  24954. * @example
  24955. <example name="ng-paste">
  24956. <file name="index.html">
  24957. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  24958. pasted: {{paste}}
  24959. </file>
  24960. </example>
  24961. */
  24962. /**
  24963. * @ngdoc directive
  24964. * @name ngIf
  24965. * @restrict A
  24966. * @multiElement
  24967. *
  24968. * @description
  24969. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  24970. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  24971. * value then the element is removed from the DOM, otherwise a clone of the
  24972. * element is reinserted into the DOM.
  24973. *
  24974. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  24975. * element in the DOM rather than changing its visibility via the `display` css property. A common
  24976. * case when this difference is significant is when using css selectors that rely on an element's
  24977. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  24978. *
  24979. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  24980. * is created when the element is restored. The scope created within `ngIf` inherits from
  24981. * its parent scope using
  24982. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  24983. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  24984. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  24985. * variable within the child scope will override (hide) the value in the parent scope.
  24986. *
  24987. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  24988. * is if an element's class attribute is directly modified after it's compiled, using something like
  24989. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  24990. * the added class will be lost because the original compiled state is used to regenerate the element.
  24991. *
  24992. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  24993. * and `leave` effects.
  24994. *
  24995. * @animations
  24996. * | Animation | Occurs |
  24997. * |----------------------------------|-------------------------------------|
  24998. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  24999. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  25000. *
  25001. * @element ANY
  25002. * @scope
  25003. * @priority 600
  25004. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  25005. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  25006. * element is added to the DOM tree.
  25007. *
  25008. * @example
  25009. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
  25010. <file name="index.html">
  25011. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  25012. Show when checked:
  25013. <span ng-if="checked" class="animate-if">
  25014. This is removed when the checkbox is unchecked.
  25015. </span>
  25016. </file>
  25017. <file name="animations.css">
  25018. .animate-if {
  25019. background:white;
  25020. border:1px solid black;
  25021. padding:10px;
  25022. }
  25023. .animate-if.ng-enter, .animate-if.ng-leave {
  25024. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25025. }
  25026. .animate-if.ng-enter,
  25027. .animate-if.ng-leave.ng-leave-active {
  25028. opacity:0;
  25029. }
  25030. .animate-if.ng-leave,
  25031. .animate-if.ng-enter.ng-enter-active {
  25032. opacity:1;
  25033. }
  25034. </file>
  25035. </example>
  25036. */
  25037. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  25038. return {
  25039. multiElement: true,
  25040. transclude: 'element',
  25041. priority: 600,
  25042. terminal: true,
  25043. restrict: 'A',
  25044. $$tlb: true,
  25045. link: function($scope, $element, $attr, ctrl, $transclude) {
  25046. var block, childScope, previousElements;
  25047. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  25048. if (value) {
  25049. if (!childScope) {
  25050. $transclude(function(clone, newScope) {
  25051. childScope = newScope;
  25052. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  25053. // Note: We only need the first/last node of the cloned nodes.
  25054. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  25055. // by a directive with templateUrl when its template arrives.
  25056. block = {
  25057. clone: clone
  25058. };
  25059. $animate.enter(clone, $element.parent(), $element);
  25060. });
  25061. }
  25062. } else {
  25063. if (previousElements) {
  25064. previousElements.remove();
  25065. previousElements = null;
  25066. }
  25067. if (childScope) {
  25068. childScope.$destroy();
  25069. childScope = null;
  25070. }
  25071. if (block) {
  25072. previousElements = getBlockNodes(block.clone);
  25073. $animate.leave(previousElements).done(function(response) {
  25074. if (response !== false) previousElements = null;
  25075. });
  25076. block = null;
  25077. }
  25078. }
  25079. });
  25080. }
  25081. };
  25082. }];
  25083. /**
  25084. * @ngdoc directive
  25085. * @name ngInclude
  25086. * @restrict ECA
  25087. *
  25088. * @description
  25089. * Fetches, compiles and includes an external HTML fragment.
  25090. *
  25091. * By default, the template URL is restricted to the same domain and protocol as the
  25092. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  25093. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  25094. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  25095. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  25096. * ng.$sce Strict Contextual Escaping}.
  25097. *
  25098. * In addition, the browser's
  25099. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  25100. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  25101. * policy may further restrict whether the template is successfully loaded.
  25102. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  25103. * access on some browsers.
  25104. *
  25105. * @animations
  25106. * | Animation | Occurs |
  25107. * |----------------------------------|-------------------------------------|
  25108. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  25109. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  25110. *
  25111. * The enter and leave animation occur concurrently.
  25112. *
  25113. * @scope
  25114. * @priority 400
  25115. *
  25116. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  25117. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  25118. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  25119. * <div class="alert alert-warning">
  25120. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  25121. * a function with the name on the window element, which will usually throw a
  25122. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  25123. * different form that {@link guide/directive#normalization matches} `onload`.
  25124. * </div>
  25125. *
  25126. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  25127. * $anchorScroll} to scroll the viewport after the content is loaded.
  25128. *
  25129. * - If the attribute is not set, disable scrolling.
  25130. * - If the attribute is set without value, enable scrolling.
  25131. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  25132. *
  25133. * @example
  25134. <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
  25135. <file name="index.html">
  25136. <div ng-controller="ExampleController">
  25137. <select ng-model="template" ng-options="t.name for t in templates">
  25138. <option value="">(blank)</option>
  25139. </select>
  25140. url of the template: <code>{{template.url}}</code>
  25141. <hr/>
  25142. <div class="slide-animate-container">
  25143. <div class="slide-animate" ng-include="template.url"></div>
  25144. </div>
  25145. </div>
  25146. </file>
  25147. <file name="script.js">
  25148. angular.module('includeExample', ['ngAnimate'])
  25149. .controller('ExampleController', ['$scope', function($scope) {
  25150. $scope.templates =
  25151. [{ name: 'template1.html', url: 'template1.html'},
  25152. { name: 'template2.html', url: 'template2.html'}];
  25153. $scope.template = $scope.templates[0];
  25154. }]);
  25155. </file>
  25156. <file name="template1.html">
  25157. Content of template1.html
  25158. </file>
  25159. <file name="template2.html">
  25160. Content of template2.html
  25161. </file>
  25162. <file name="animations.css">
  25163. .slide-animate-container {
  25164. position:relative;
  25165. background:white;
  25166. border:1px solid black;
  25167. height:40px;
  25168. overflow:hidden;
  25169. }
  25170. .slide-animate {
  25171. padding:10px;
  25172. }
  25173. .slide-animate.ng-enter, .slide-animate.ng-leave {
  25174. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25175. position:absolute;
  25176. top:0;
  25177. left:0;
  25178. right:0;
  25179. bottom:0;
  25180. display:block;
  25181. padding:10px;
  25182. }
  25183. .slide-animate.ng-enter {
  25184. top:-50px;
  25185. }
  25186. .slide-animate.ng-enter.ng-enter-active {
  25187. top:0;
  25188. }
  25189. .slide-animate.ng-leave {
  25190. top:0;
  25191. }
  25192. .slide-animate.ng-leave.ng-leave-active {
  25193. top:50px;
  25194. }
  25195. </file>
  25196. <file name="protractor.js" type="protractor">
  25197. var templateSelect = element(by.model('template'));
  25198. var includeElem = element(by.css('[ng-include]'));
  25199. it('should load template1.html', function() {
  25200. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  25201. });
  25202. it('should load template2.html', function() {
  25203. if (browser.params.browser === 'firefox') {
  25204. // Firefox can't handle using selects
  25205. // See https://github.com/angular/protractor/issues/480
  25206. return;
  25207. }
  25208. templateSelect.click();
  25209. templateSelect.all(by.css('option')).get(2).click();
  25210. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  25211. });
  25212. it('should change to blank', function() {
  25213. if (browser.params.browser === 'firefox') {
  25214. // Firefox can't handle using selects
  25215. return;
  25216. }
  25217. templateSelect.click();
  25218. templateSelect.all(by.css('option')).get(0).click();
  25219. expect(includeElem.isPresent()).toBe(false);
  25220. });
  25221. </file>
  25222. </example>
  25223. */
  25224. /**
  25225. * @ngdoc event
  25226. * @name ngInclude#$includeContentRequested
  25227. * @eventType emit on the scope ngInclude was declared in
  25228. * @description
  25229. * Emitted every time the ngInclude content is requested.
  25230. *
  25231. * @param {Object} angularEvent Synthetic event object.
  25232. * @param {String} src URL of content to load.
  25233. */
  25234. /**
  25235. * @ngdoc event
  25236. * @name ngInclude#$includeContentLoaded
  25237. * @eventType emit on the current ngInclude scope
  25238. * @description
  25239. * Emitted every time the ngInclude content is reloaded.
  25240. *
  25241. * @param {Object} angularEvent Synthetic event object.
  25242. * @param {String} src URL of content to load.
  25243. */
  25244. /**
  25245. * @ngdoc event
  25246. * @name ngInclude#$includeContentError
  25247. * @eventType emit on the scope ngInclude was declared in
  25248. * @description
  25249. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  25250. *
  25251. * @param {Object} angularEvent Synthetic event object.
  25252. * @param {String} src URL of content to load.
  25253. */
  25254. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  25255. function($templateRequest, $anchorScroll, $animate) {
  25256. return {
  25257. restrict: 'ECA',
  25258. priority: 400,
  25259. terminal: true,
  25260. transclude: 'element',
  25261. controller: angular.noop,
  25262. compile: function(element, attr) {
  25263. var srcExp = attr.ngInclude || attr.src,
  25264. onloadExp = attr.onload || '',
  25265. autoScrollExp = attr.autoscroll;
  25266. return function(scope, $element, $attr, ctrl, $transclude) {
  25267. var changeCounter = 0,
  25268. currentScope,
  25269. previousElement,
  25270. currentElement;
  25271. var cleanupLastIncludeContent = function() {
  25272. if (previousElement) {
  25273. previousElement.remove();
  25274. previousElement = null;
  25275. }
  25276. if (currentScope) {
  25277. currentScope.$destroy();
  25278. currentScope = null;
  25279. }
  25280. if (currentElement) {
  25281. $animate.leave(currentElement).done(function(response) {
  25282. if (response !== false) previousElement = null;
  25283. });
  25284. previousElement = currentElement;
  25285. currentElement = null;
  25286. }
  25287. };
  25288. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  25289. var afterAnimation = function(response) {
  25290. if (response !== false && isDefined(autoScrollExp) &&
  25291. (!autoScrollExp || scope.$eval(autoScrollExp))) {
  25292. $anchorScroll();
  25293. }
  25294. };
  25295. var thisChangeId = ++changeCounter;
  25296. if (src) {
  25297. //set the 2nd param to true to ignore the template request error so that the inner
  25298. //contents and scope can be cleaned up.
  25299. $templateRequest(src, true).then(function(response) {
  25300. if (scope.$$destroyed) return;
  25301. if (thisChangeId !== changeCounter) return;
  25302. var newScope = scope.$new();
  25303. ctrl.template = response;
  25304. // Note: This will also link all children of ng-include that were contained in the original
  25305. // html. If that content contains controllers, ... they could pollute/change the scope.
  25306. // However, using ng-include on an element with additional content does not make sense...
  25307. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  25308. // function is called before linking the content, which would apply child
  25309. // directives to non existing elements.
  25310. var clone = $transclude(newScope, function(clone) {
  25311. cleanupLastIncludeContent();
  25312. $animate.enter(clone, null, $element).done(afterAnimation);
  25313. });
  25314. currentScope = newScope;
  25315. currentElement = clone;
  25316. currentScope.$emit('$includeContentLoaded', src);
  25317. scope.$eval(onloadExp);
  25318. }, function() {
  25319. if (scope.$$destroyed) return;
  25320. if (thisChangeId === changeCounter) {
  25321. cleanupLastIncludeContent();
  25322. scope.$emit('$includeContentError', src);
  25323. }
  25324. });
  25325. scope.$emit('$includeContentRequested', src);
  25326. } else {
  25327. cleanupLastIncludeContent();
  25328. ctrl.template = null;
  25329. }
  25330. });
  25331. };
  25332. }
  25333. };
  25334. }];
  25335. // This directive is called during the $transclude call of the first `ngInclude` directive.
  25336. // It will replace and compile the content of the element with the loaded template.
  25337. // We need this directive so that the element content is already filled when
  25338. // the link function of another directive on the same element as ngInclude
  25339. // is called.
  25340. var ngIncludeFillContentDirective = ['$compile',
  25341. function($compile) {
  25342. return {
  25343. restrict: 'ECA',
  25344. priority: -400,
  25345. require: 'ngInclude',
  25346. link: function(scope, $element, $attr, ctrl) {
  25347. if (toString.call($element[0]).match(/SVG/)) {
  25348. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  25349. // support innerHTML, so detect this here and try to generate the contents
  25350. // specially.
  25351. $element.empty();
  25352. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  25353. function namespaceAdaptedClone(clone) {
  25354. $element.append(clone);
  25355. }, {futureParentElement: $element});
  25356. return;
  25357. }
  25358. $element.html(ctrl.template);
  25359. $compile($element.contents())(scope);
  25360. }
  25361. };
  25362. }];
  25363. /**
  25364. * @ngdoc directive
  25365. * @name ngInit
  25366. * @restrict AC
  25367. *
  25368. * @description
  25369. * The `ngInit` directive allows you to evaluate an expression in the
  25370. * current scope.
  25371. *
  25372. * <div class="alert alert-danger">
  25373. * This directive can be abused to add unnecessary amounts of logic into your templates.
  25374. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  25375. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  25376. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  25377. * rather than `ngInit` to initialize values on a scope.
  25378. * </div>
  25379. *
  25380. * <div class="alert alert-warning">
  25381. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  25382. * sure you have parentheses to ensure correct operator precedence:
  25383. * <pre class="prettyprint">
  25384. * `<div ng-init="test1 = ($index | toString)"></div>`
  25385. * </pre>
  25386. * </div>
  25387. *
  25388. * @priority 450
  25389. *
  25390. * @element ANY
  25391. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  25392. *
  25393. * @example
  25394. <example module="initExample" name="ng-init">
  25395. <file name="index.html">
  25396. <script>
  25397. angular.module('initExample', [])
  25398. .controller('ExampleController', ['$scope', function($scope) {
  25399. $scope.list = [['a', 'b'], ['c', 'd']];
  25400. }]);
  25401. </script>
  25402. <div ng-controller="ExampleController">
  25403. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  25404. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  25405. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  25406. </div>
  25407. </div>
  25408. </div>
  25409. </file>
  25410. <file name="protractor.js" type="protractor">
  25411. it('should alias index positions', function() {
  25412. var elements = element.all(by.css('.example-init'));
  25413. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  25414. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  25415. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  25416. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  25417. });
  25418. </file>
  25419. </example>
  25420. */
  25421. var ngInitDirective = ngDirective({
  25422. priority: 450,
  25423. compile: function() {
  25424. return {
  25425. pre: function(scope, element, attrs) {
  25426. scope.$eval(attrs.ngInit);
  25427. }
  25428. };
  25429. }
  25430. });
  25431. /**
  25432. * @ngdoc directive
  25433. * @name ngList
  25434. *
  25435. * @description
  25436. * Text input that converts between a delimited string and an array of strings. The default
  25437. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  25438. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  25439. *
  25440. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  25441. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  25442. * list item is respected. This implies that the user of the directive is responsible for
  25443. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  25444. * tab or newline character.
  25445. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  25446. * when joining the list items back together) and whitespace around each list item is stripped
  25447. * before it is added to the model.
  25448. *
  25449. * ### Example with Validation
  25450. *
  25451. * <example name="ngList-directive" module="listExample">
  25452. * <file name="app.js">
  25453. * angular.module('listExample', [])
  25454. * .controller('ExampleController', ['$scope', function($scope) {
  25455. * $scope.names = ['morpheus', 'neo', 'trinity'];
  25456. * }]);
  25457. * </file>
  25458. * <file name="index.html">
  25459. * <form name="myForm" ng-controller="ExampleController">
  25460. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  25461. * <span role="alert">
  25462. * <span class="error" ng-show="myForm.namesInput.$error.required">
  25463. * Required!</span>
  25464. * </span>
  25465. * <br>
  25466. * <tt>names = {{names}}</tt><br/>
  25467. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  25468. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  25469. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  25470. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  25471. * </form>
  25472. * </file>
  25473. * <file name="protractor.js" type="protractor">
  25474. * var listInput = element(by.model('names'));
  25475. * var names = element(by.exactBinding('names'));
  25476. * var valid = element(by.binding('myForm.namesInput.$valid'));
  25477. * var error = element(by.css('span.error'));
  25478. *
  25479. * it('should initialize to model', function() {
  25480. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  25481. * expect(valid.getText()).toContain('true');
  25482. * expect(error.getCssValue('display')).toBe('none');
  25483. * });
  25484. *
  25485. * it('should be invalid if empty', function() {
  25486. * listInput.clear();
  25487. * listInput.sendKeys('');
  25488. *
  25489. * expect(names.getText()).toContain('');
  25490. * expect(valid.getText()).toContain('false');
  25491. * expect(error.getCssValue('display')).not.toBe('none');
  25492. * });
  25493. * </file>
  25494. * </example>
  25495. *
  25496. * ### Example - splitting on newline
  25497. * <example name="ngList-directive-newlines">
  25498. * <file name="index.html">
  25499. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  25500. * <pre>{{ list | json }}</pre>
  25501. * </file>
  25502. * <file name="protractor.js" type="protractor">
  25503. * it("should split the text by newlines", function() {
  25504. * var listInput = element(by.model('list'));
  25505. * var output = element(by.binding('list | json'));
  25506. * listInput.sendKeys('abc\ndef\nghi');
  25507. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  25508. * });
  25509. * </file>
  25510. * </example>
  25511. *
  25512. * @element input
  25513. * @param {string=} ngList optional delimiter that should be used to split the value.
  25514. */
  25515. var ngListDirective = function() {
  25516. return {
  25517. restrict: 'A',
  25518. priority: 100,
  25519. require: 'ngModel',
  25520. link: function(scope, element, attr, ctrl) {
  25521. var ngList = attr.ngList || ', ';
  25522. var trimValues = attr.ngTrim !== 'false';
  25523. var separator = trimValues ? trim(ngList) : ngList;
  25524. var parse = function(viewValue) {
  25525. // If the viewValue is invalid (say required but empty) it will be `undefined`
  25526. if (isUndefined(viewValue)) return;
  25527. var list = [];
  25528. if (viewValue) {
  25529. forEach(viewValue.split(separator), function(value) {
  25530. if (value) list.push(trimValues ? trim(value) : value);
  25531. });
  25532. }
  25533. return list;
  25534. };
  25535. ctrl.$parsers.push(parse);
  25536. ctrl.$formatters.push(function(value) {
  25537. if (isArray(value)) {
  25538. return value.join(ngList);
  25539. }
  25540. return undefined;
  25541. });
  25542. // Override the standard $isEmpty because an empty array means the input is empty.
  25543. ctrl.$isEmpty = function(value) {
  25544. return !value || !value.length;
  25545. };
  25546. }
  25547. };
  25548. };
  25549. /* global VALID_CLASS: true,
  25550. INVALID_CLASS: true,
  25551. PRISTINE_CLASS: true,
  25552. DIRTY_CLASS: true,
  25553. UNTOUCHED_CLASS: true,
  25554. TOUCHED_CLASS: true,
  25555. PENDING_CLASS: true,
  25556. addSetValidityMethod: true,
  25557. setupValidity: true,
  25558. defaultModelOptions: false
  25559. */
  25560. var VALID_CLASS = 'ng-valid',
  25561. INVALID_CLASS = 'ng-invalid',
  25562. PRISTINE_CLASS = 'ng-pristine',
  25563. DIRTY_CLASS = 'ng-dirty',
  25564. UNTOUCHED_CLASS = 'ng-untouched',
  25565. TOUCHED_CLASS = 'ng-touched',
  25566. EMPTY_CLASS = 'ng-empty',
  25567. NOT_EMPTY_CLASS = 'ng-not-empty';
  25568. var ngModelMinErr = minErr('ngModel');
  25569. /**
  25570. * @ngdoc type
  25571. * @name ngModel.NgModelController
  25572. *
  25573. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  25574. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  25575. * is set.
  25576. *
  25577. * @property {*} $modelValue The value in the model that the control is bound to.
  25578. *
  25579. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  25580. * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue
  25581. `$viewValue`} from the DOM, usually via user input.
  25582. See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation.
  25583. Note that the `$parsers` are not called when the bound ngModel expression changes programmatically.
  25584. The functions are called in array order, each passing
  25585. its return value through to the next. The last return value is forwarded to the
  25586. {@link ngModel.NgModelController#$validators `$validators`} collection.
  25587. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  25588. `$viewValue`}.
  25589. Returning `undefined` from a parser means a parse error occurred. In that case,
  25590. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  25591. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  25592. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  25593. This simple example shows a parser that would convert text input value to lowercase:
  25594. * ```js
  25595. * function parse(value) {
  25596. * if (value) {
  25597. * return value.toLowerCase();
  25598. * }
  25599. * }
  25600. * ngModelController.$parsers.push(parse);
  25601. * ```
  25602. *
  25603. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  25604. the bound ngModel expression changes programmatically. The `$formatters` are not called when the
  25605. value of the control is changed by user interaction.
  25606. Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue
  25607. `$modelValue`} for display in the control.
  25608. The functions are called in reverse array order, each passing the value through to the
  25609. next. The last return value is used as the actual DOM value.
  25610. This simple example shows a formatter that would convert the model value to uppercase:
  25611. * ```js
  25612. * function format(value) {
  25613. * if (value) {
  25614. * return value.toUpperCase();
  25615. * }
  25616. * }
  25617. * ngModel.$formatters.push(format);
  25618. * ```
  25619. *
  25620. * @property {Object.<string, function>} $validators A collection of validators that are applied
  25621. * whenever the model value changes. The key value within the object refers to the name of the
  25622. * validator while the function refers to the validation operation. The validation operation is
  25623. * provided with the model value as an argument and must return a true or false value depending
  25624. * on the response of that validation.
  25625. *
  25626. * ```js
  25627. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  25628. * var value = modelValue || viewValue;
  25629. * return /[0-9]+/.test(value) &&
  25630. * /[a-z]+/.test(value) &&
  25631. * /[A-Z]+/.test(value) &&
  25632. * /\W+/.test(value);
  25633. * };
  25634. * ```
  25635. *
  25636. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  25637. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  25638. * is expected to return a promise when it is run during the model validation process. Once the promise
  25639. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  25640. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  25641. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  25642. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  25643. * will only run once all synchronous validators have passed.
  25644. *
  25645. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  25646. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  25647. *
  25648. * ```js
  25649. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  25650. * var value = modelValue || viewValue;
  25651. *
  25652. * // Lookup user by username
  25653. * return $http.get('/api/users/' + value).
  25654. * then(function resolved() {
  25655. * //username exists, this means validation fails
  25656. * return $q.reject('exists');
  25657. * }, function rejected() {
  25658. * //username does not exist, therefore this validation passes
  25659. * return true;
  25660. * });
  25661. * };
  25662. * ```
  25663. *
  25664. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  25665. * view value has changed. It is called with no arguments, and its return value is ignored.
  25666. * This can be used in place of additional $watches against the model value.
  25667. *
  25668. * @property {Object} $error An object hash with all failing validator ids as keys.
  25669. * @property {Object} $pending An object hash with all pending validator ids as keys.
  25670. *
  25671. * @property {boolean} $untouched True if control has not lost focus yet.
  25672. * @property {boolean} $touched True if control has lost focus.
  25673. * @property {boolean} $pristine True if user has not interacted with the control yet.
  25674. * @property {boolean} $dirty True if user has already interacted with the control.
  25675. * @property {boolean} $valid True if there is no error.
  25676. * @property {boolean} $invalid True if at least one error on the control.
  25677. * @property {string} $name The name attribute of the control.
  25678. *
  25679. * @description
  25680. *
  25681. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  25682. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  25683. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  25684. * listening to DOM events.
  25685. * Such DOM related logic should be provided by other directives which make use of
  25686. * `NgModelController` for data-binding to control elements.
  25687. * Angular provides this DOM logic for most {@link input `input`} elements.
  25688. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  25689. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  25690. *
  25691. * @example
  25692. * ### Custom Control Example
  25693. * This example shows how to use `NgModelController` with a custom control to achieve
  25694. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  25695. * collaborate together to achieve the desired result.
  25696. *
  25697. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  25698. * contents be edited in place by the user.
  25699. *
  25700. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  25701. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  25702. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  25703. * that content using the `$sce` service.
  25704. *
  25705. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  25706. <file name="style.css">
  25707. [contenteditable] {
  25708. border: 1px solid black;
  25709. background-color: white;
  25710. min-height: 20px;
  25711. }
  25712. .ng-invalid {
  25713. border: 1px solid red;
  25714. }
  25715. </file>
  25716. <file name="script.js">
  25717. angular.module('customControl', ['ngSanitize']).
  25718. directive('contenteditable', ['$sce', function($sce) {
  25719. return {
  25720. restrict: 'A', // only activate on element attribute
  25721. require: '?ngModel', // get a hold of NgModelController
  25722. link: function(scope, element, attrs, ngModel) {
  25723. if (!ngModel) return; // do nothing if no ng-model
  25724. // Specify how UI should be updated
  25725. ngModel.$render = function() {
  25726. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  25727. };
  25728. // Listen for change events to enable binding
  25729. element.on('blur keyup change', function() {
  25730. scope.$evalAsync(read);
  25731. });
  25732. read(); // initialize
  25733. // Write data to the model
  25734. function read() {
  25735. var html = element.html();
  25736. // When we clear the content editable the browser leaves a <br> behind
  25737. // If strip-br attribute is provided then we strip this out
  25738. if (attrs.stripBr && html === '<br>') {
  25739. html = '';
  25740. }
  25741. ngModel.$setViewValue(html);
  25742. }
  25743. }
  25744. };
  25745. }]);
  25746. </file>
  25747. <file name="index.html">
  25748. <form name="myForm">
  25749. <div contenteditable
  25750. name="myWidget" ng-model="userContent"
  25751. strip-br="true"
  25752. required>Change me!</div>
  25753. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  25754. <hr>
  25755. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  25756. </form>
  25757. </file>
  25758. <file name="protractor.js" type="protractor">
  25759. it('should data-bind and become invalid', function() {
  25760. if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
  25761. // SafariDriver can't handle contenteditable
  25762. // and Firefox driver can't clear contenteditables very well
  25763. return;
  25764. }
  25765. var contentEditable = element(by.css('[contenteditable]'));
  25766. var content = 'Change me!';
  25767. expect(contentEditable.getText()).toEqual(content);
  25768. contentEditable.clear();
  25769. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  25770. expect(contentEditable.getText()).toEqual('');
  25771. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  25772. });
  25773. </file>
  25774. * </example>
  25775. *
  25776. *
  25777. */
  25778. NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];
  25779. function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {
  25780. this.$viewValue = Number.NaN;
  25781. this.$modelValue = Number.NaN;
  25782. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  25783. this.$validators = {};
  25784. this.$asyncValidators = {};
  25785. this.$parsers = [];
  25786. this.$formatters = [];
  25787. this.$viewChangeListeners = [];
  25788. this.$untouched = true;
  25789. this.$touched = false;
  25790. this.$pristine = true;
  25791. this.$dirty = false;
  25792. this.$valid = true;
  25793. this.$invalid = false;
  25794. this.$error = {}; // keep invalid keys here
  25795. this.$$success = {}; // keep valid keys here
  25796. this.$pending = undefined; // keep pending keys here
  25797. this.$name = $interpolate($attr.name || '', false)($scope);
  25798. this.$$parentForm = nullFormCtrl;
  25799. this.$options = defaultModelOptions;
  25800. this.$$parsedNgModel = $parse($attr.ngModel);
  25801. this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;
  25802. this.$$ngModelGet = this.$$parsedNgModel;
  25803. this.$$ngModelSet = this.$$parsedNgModelAssign;
  25804. this.$$pendingDebounce = null;
  25805. this.$$parserValid = undefined;
  25806. this.$$currentValidationRunId = 0;
  25807. // https://github.com/angular/angular.js/issues/15833
  25808. // Prevent `$$scope` from being iterated over by `copy` when NgModelController is deep watched
  25809. Object.defineProperty(this, '$$scope', {value: $scope});
  25810. this.$$attr = $attr;
  25811. this.$$element = $element;
  25812. this.$$animate = $animate;
  25813. this.$$timeout = $timeout;
  25814. this.$$parse = $parse;
  25815. this.$$q = $q;
  25816. this.$$exceptionHandler = $exceptionHandler;
  25817. setupValidity(this);
  25818. setupModelWatcher(this);
  25819. }
  25820. NgModelController.prototype = {
  25821. $$initGetterSetters: function() {
  25822. if (this.$options.getOption('getterSetter')) {
  25823. var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),
  25824. invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');
  25825. this.$$ngModelGet = function($scope) {
  25826. var modelValue = this.$$parsedNgModel($scope);
  25827. if (isFunction(modelValue)) {
  25828. modelValue = invokeModelGetter($scope);
  25829. }
  25830. return modelValue;
  25831. };
  25832. this.$$ngModelSet = function($scope, newValue) {
  25833. if (isFunction(this.$$parsedNgModel($scope))) {
  25834. invokeModelSetter($scope, {$$$p: newValue});
  25835. } else {
  25836. this.$$parsedNgModelAssign($scope, newValue);
  25837. }
  25838. };
  25839. } else if (!this.$$parsedNgModel.assign) {
  25840. throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
  25841. this.$$attr.ngModel, startingTag(this.$$element));
  25842. }
  25843. },
  25844. /**
  25845. * @ngdoc method
  25846. * @name ngModel.NgModelController#$render
  25847. *
  25848. * @description
  25849. * Called when the view needs to be updated. It is expected that the user of the ng-model
  25850. * directive will implement this method.
  25851. *
  25852. * The `$render()` method is invoked in the following situations:
  25853. *
  25854. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  25855. * committed value then `$render()` is called to update the input control.
  25856. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  25857. * the `$viewValue` are different from last time.
  25858. *
  25859. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  25860. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  25861. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  25862. * invoked if you only change a property on the objects.
  25863. */
  25864. $render: noop,
  25865. /**
  25866. * @ngdoc method
  25867. * @name ngModel.NgModelController#$isEmpty
  25868. *
  25869. * @description
  25870. * This is called when we need to determine if the value of an input is empty.
  25871. *
  25872. * For instance, the required directive does this to work out if the input has data or not.
  25873. *
  25874. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  25875. *
  25876. * You can override this for input directives whose concept of being empty is different from the
  25877. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  25878. * implies empty.
  25879. *
  25880. * @param {*} value The value of the input to check for emptiness.
  25881. * @returns {boolean} True if `value` is "empty".
  25882. */
  25883. $isEmpty: function(value) {
  25884. // eslint-disable-next-line no-self-compare
  25885. return isUndefined(value) || value === '' || value === null || value !== value;
  25886. },
  25887. $$updateEmptyClasses: function(value) {
  25888. if (this.$isEmpty(value)) {
  25889. this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);
  25890. this.$$animate.addClass(this.$$element, EMPTY_CLASS);
  25891. } else {
  25892. this.$$animate.removeClass(this.$$element, EMPTY_CLASS);
  25893. this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);
  25894. }
  25895. },
  25896. /**
  25897. * @ngdoc method
  25898. * @name ngModel.NgModelController#$setPristine
  25899. *
  25900. * @description
  25901. * Sets the control to its pristine state.
  25902. *
  25903. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  25904. * state (`ng-pristine` class). A model is considered to be pristine when the control
  25905. * has not been changed from when first compiled.
  25906. */
  25907. $setPristine: function() {
  25908. this.$dirty = false;
  25909. this.$pristine = true;
  25910. this.$$animate.removeClass(this.$$element, DIRTY_CLASS);
  25911. this.$$animate.addClass(this.$$element, PRISTINE_CLASS);
  25912. },
  25913. /**
  25914. * @ngdoc method
  25915. * @name ngModel.NgModelController#$setDirty
  25916. *
  25917. * @description
  25918. * Sets the control to its dirty state.
  25919. *
  25920. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  25921. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  25922. * from when first compiled.
  25923. */
  25924. $setDirty: function() {
  25925. this.$dirty = true;
  25926. this.$pristine = false;
  25927. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  25928. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  25929. this.$$parentForm.$setDirty();
  25930. },
  25931. /**
  25932. * @ngdoc method
  25933. * @name ngModel.NgModelController#$setUntouched
  25934. *
  25935. * @description
  25936. * Sets the control to its untouched state.
  25937. *
  25938. * This method can be called to remove the `ng-touched` class and set the control to its
  25939. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  25940. * by default, however this function can be used to restore that state if the model has
  25941. * already been touched by the user.
  25942. */
  25943. $setUntouched: function() {
  25944. this.$touched = false;
  25945. this.$untouched = true;
  25946. this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  25947. },
  25948. /**
  25949. * @ngdoc method
  25950. * @name ngModel.NgModelController#$setTouched
  25951. *
  25952. * @description
  25953. * Sets the control to its touched state.
  25954. *
  25955. * This method can be called to remove the `ng-untouched` class and set the control to its
  25956. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  25957. * first focused the control element and then shifted focus away from the control (blur event).
  25958. */
  25959. $setTouched: function() {
  25960. this.$touched = true;
  25961. this.$untouched = false;
  25962. this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  25963. },
  25964. /**
  25965. * @ngdoc method
  25966. * @name ngModel.NgModelController#$rollbackViewValue
  25967. *
  25968. * @description
  25969. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  25970. * which may be caused by a pending debounced event or because the input is waiting for some
  25971. * future event.
  25972. *
  25973. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  25974. * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
  25975. * sync with the ngModel's `$modelValue`.
  25976. *
  25977. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  25978. * and reset the input to the last committed view value.
  25979. *
  25980. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  25981. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  25982. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  25983. *
  25984. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  25985. * input which may have such events pending. This is important in order to make sure that the
  25986. * input field will be updated with the new model value and any pending operations are cancelled.
  25987. *
  25988. * <example name="ng-model-cancel-update" module="cancel-update-example">
  25989. * <file name="app.js">
  25990. * angular.module('cancel-update-example', [])
  25991. *
  25992. * .controller('CancelUpdateController', ['$scope', function($scope) {
  25993. * $scope.model = {value1: '', value2: ''};
  25994. *
  25995. * $scope.setEmpty = function(e, value, rollback) {
  25996. * if (e.keyCode === 27) {
  25997. * e.preventDefault();
  25998. * if (rollback) {
  25999. * $scope.myForm[value].$rollbackViewValue();
  26000. * }
  26001. * $scope.model[value] = '';
  26002. * }
  26003. * };
  26004. * }]);
  26005. * </file>
  26006. * <file name="index.html">
  26007. * <div ng-controller="CancelUpdateController">
  26008. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  26009. * empty them. Follow these steps and observe the difference:</p>
  26010. * <ol>
  26011. * <li>Type something in the input. You will see that the model is not yet updated</li>
  26012. * <li>Press the Escape key.
  26013. * <ol>
  26014. * <li> In the first example, nothing happens, because the model is already '', and no
  26015. * update is detected. If you blur the input, the model will be set to the current view.
  26016. * </li>
  26017. * <li> In the second example, the pending update is cancelled, and the input is set back
  26018. * to the last committed view value (''). Blurring the input does nothing.
  26019. * </li>
  26020. * </ol>
  26021. * </li>
  26022. * </ol>
  26023. *
  26024. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  26025. * <div>
  26026. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  26027. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  26028. * ng-keydown="setEmpty($event, 'value1')">
  26029. * value1: "{{ model.value1 }}"
  26030. * </div>
  26031. *
  26032. * <div>
  26033. * <p id="inputDescription2">With $rollbackViewValue():</p>
  26034. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  26035. * ng-keydown="setEmpty($event, 'value2', true)">
  26036. * value2: "{{ model.value2 }}"
  26037. * </div>
  26038. * </form>
  26039. * </div>
  26040. * </file>
  26041. <file name="style.css">
  26042. div {
  26043. display: table-cell;
  26044. }
  26045. div:nth-child(1) {
  26046. padding-right: 30px;
  26047. }
  26048. </file>
  26049. * </example>
  26050. */
  26051. $rollbackViewValue: function() {
  26052. this.$$timeout.cancel(this.$$pendingDebounce);
  26053. this.$viewValue = this.$$lastCommittedViewValue;
  26054. this.$render();
  26055. },
  26056. /**
  26057. * @ngdoc method
  26058. * @name ngModel.NgModelController#$validate
  26059. *
  26060. * @description
  26061. * Runs each of the registered validators (first synchronous validators and then
  26062. * asynchronous validators).
  26063. * If the validity changes to invalid, the model will be set to `undefined`,
  26064. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  26065. * If the validity changes to valid, it will set the model to the last available valid
  26066. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  26067. */
  26068. $validate: function() {
  26069. // ignore $validate before model is initialized
  26070. if (isNumberNaN(this.$modelValue)) {
  26071. return;
  26072. }
  26073. var viewValue = this.$$lastCommittedViewValue;
  26074. // Note: we use the $$rawModelValue as $modelValue might have been
  26075. // set to undefined during a view -> model update that found validation
  26076. // errors. We can't parse the view here, since that could change
  26077. // the model although neither viewValue nor the model on the scope changed
  26078. var modelValue = this.$$rawModelValue;
  26079. var prevValid = this.$valid;
  26080. var prevModelValue = this.$modelValue;
  26081. var allowInvalid = this.$options.getOption('allowInvalid');
  26082. var that = this;
  26083. this.$$runValidators(modelValue, viewValue, function(allValid) {
  26084. // If there was no change in validity, don't update the model
  26085. // This prevents changing an invalid modelValue to undefined
  26086. if (!allowInvalid && prevValid !== allValid) {
  26087. // Note: Don't check this.$valid here, as we could have
  26088. // external validators (e.g. calculated on the server),
  26089. // that just call $setValidity and need the model value
  26090. // to calculate their validity.
  26091. that.$modelValue = allValid ? modelValue : undefined;
  26092. if (that.$modelValue !== prevModelValue) {
  26093. that.$$writeModelToScope();
  26094. }
  26095. }
  26096. });
  26097. },
  26098. $$runValidators: function(modelValue, viewValue, doneCallback) {
  26099. this.$$currentValidationRunId++;
  26100. var localValidationRunId = this.$$currentValidationRunId;
  26101. var that = this;
  26102. // check parser error
  26103. if (!processParseErrors()) {
  26104. validationDone(false);
  26105. return;
  26106. }
  26107. if (!processSyncValidators()) {
  26108. validationDone(false);
  26109. return;
  26110. }
  26111. processAsyncValidators();
  26112. function processParseErrors() {
  26113. var errorKey = that.$$parserName || 'parse';
  26114. if (isUndefined(that.$$parserValid)) {
  26115. setValidity(errorKey, null);
  26116. } else {
  26117. if (!that.$$parserValid) {
  26118. forEach(that.$validators, function(v, name) {
  26119. setValidity(name, null);
  26120. });
  26121. forEach(that.$asyncValidators, function(v, name) {
  26122. setValidity(name, null);
  26123. });
  26124. }
  26125. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  26126. setValidity(errorKey, that.$$parserValid);
  26127. return that.$$parserValid;
  26128. }
  26129. return true;
  26130. }
  26131. function processSyncValidators() {
  26132. var syncValidatorsValid = true;
  26133. forEach(that.$validators, function(validator, name) {
  26134. var result = Boolean(validator(modelValue, viewValue));
  26135. syncValidatorsValid = syncValidatorsValid && result;
  26136. setValidity(name, result);
  26137. });
  26138. if (!syncValidatorsValid) {
  26139. forEach(that.$asyncValidators, function(v, name) {
  26140. setValidity(name, null);
  26141. });
  26142. return false;
  26143. }
  26144. return true;
  26145. }
  26146. function processAsyncValidators() {
  26147. var validatorPromises = [];
  26148. var allValid = true;
  26149. forEach(that.$asyncValidators, function(validator, name) {
  26150. var promise = validator(modelValue, viewValue);
  26151. if (!isPromiseLike(promise)) {
  26152. throw ngModelMinErr('nopromise',
  26153. 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
  26154. }
  26155. setValidity(name, undefined);
  26156. validatorPromises.push(promise.then(function() {
  26157. setValidity(name, true);
  26158. }, function() {
  26159. allValid = false;
  26160. setValidity(name, false);
  26161. }));
  26162. });
  26163. if (!validatorPromises.length) {
  26164. validationDone(true);
  26165. } else {
  26166. that.$$q.all(validatorPromises).then(function() {
  26167. validationDone(allValid);
  26168. }, noop);
  26169. }
  26170. }
  26171. function setValidity(name, isValid) {
  26172. if (localValidationRunId === that.$$currentValidationRunId) {
  26173. that.$setValidity(name, isValid);
  26174. }
  26175. }
  26176. function validationDone(allValid) {
  26177. if (localValidationRunId === that.$$currentValidationRunId) {
  26178. doneCallback(allValid);
  26179. }
  26180. }
  26181. },
  26182. /**
  26183. * @ngdoc method
  26184. * @name ngModel.NgModelController#$commitViewValue
  26185. *
  26186. * @description
  26187. * Commit a pending update to the `$modelValue`.
  26188. *
  26189. * Updates may be pending by a debounced event or because the input is waiting for a some future
  26190. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  26191. * usually handles calling this in response to input events.
  26192. */
  26193. $commitViewValue: function() {
  26194. var viewValue = this.$viewValue;
  26195. this.$$timeout.cancel(this.$$pendingDebounce);
  26196. // If the view value has not changed then we should just exit, except in the case where there is
  26197. // a native validator on the element. In this case the validation state may have changed even though
  26198. // the viewValue has stayed empty.
  26199. if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {
  26200. return;
  26201. }
  26202. this.$$updateEmptyClasses(viewValue);
  26203. this.$$lastCommittedViewValue = viewValue;
  26204. // change to dirty
  26205. if (this.$pristine) {
  26206. this.$setDirty();
  26207. }
  26208. this.$$parseAndValidate();
  26209. },
  26210. $$parseAndValidate: function() {
  26211. var viewValue = this.$$lastCommittedViewValue;
  26212. var modelValue = viewValue;
  26213. var that = this;
  26214. this.$$parserValid = isUndefined(modelValue) ? undefined : true;
  26215. if (this.$$parserValid) {
  26216. for (var i = 0; i < this.$parsers.length; i++) {
  26217. modelValue = this.$parsers[i](modelValue);
  26218. if (isUndefined(modelValue)) {
  26219. this.$$parserValid = false;
  26220. break;
  26221. }
  26222. }
  26223. }
  26224. if (isNumberNaN(this.$modelValue)) {
  26225. // this.$modelValue has not been touched yet...
  26226. this.$modelValue = this.$$ngModelGet(this.$$scope);
  26227. }
  26228. var prevModelValue = this.$modelValue;
  26229. var allowInvalid = this.$options.getOption('allowInvalid');
  26230. this.$$rawModelValue = modelValue;
  26231. if (allowInvalid) {
  26232. this.$modelValue = modelValue;
  26233. writeToModelIfNeeded();
  26234. }
  26235. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  26236. // This can happen if e.g. $setViewValue is called from inside a parser
  26237. this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {
  26238. if (!allowInvalid) {
  26239. // Note: Don't check this.$valid here, as we could have
  26240. // external validators (e.g. calculated on the server),
  26241. // that just call $setValidity and need the model value
  26242. // to calculate their validity.
  26243. that.$modelValue = allValid ? modelValue : undefined;
  26244. writeToModelIfNeeded();
  26245. }
  26246. });
  26247. function writeToModelIfNeeded() {
  26248. if (that.$modelValue !== prevModelValue) {
  26249. that.$$writeModelToScope();
  26250. }
  26251. }
  26252. },
  26253. $$writeModelToScope: function() {
  26254. this.$$ngModelSet(this.$$scope, this.$modelValue);
  26255. forEach(this.$viewChangeListeners, function(listener) {
  26256. try {
  26257. listener();
  26258. } catch (e) {
  26259. // eslint-disable-next-line no-invalid-this
  26260. this.$$exceptionHandler(e);
  26261. }
  26262. }, this);
  26263. },
  26264. /**
  26265. * @ngdoc method
  26266. * @name ngModel.NgModelController#$setViewValue
  26267. *
  26268. * @description
  26269. * Update the view value.
  26270. *
  26271. * This method should be called when a control wants to change the view value; typically,
  26272. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  26273. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  26274. * calls it when an option is selected.
  26275. *
  26276. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  26277. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  26278. * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and
  26279. * `$asyncValidators` are called and the value is applied to `$modelValue`.
  26280. * Finally, the value is set to the **expression** specified in the `ng-model` attribute and
  26281. * all the registered change listeners, in the `$viewChangeListeners` list are called.
  26282. *
  26283. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  26284. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  26285. * `updateOn` events is triggered on the DOM element.
  26286. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  26287. * directive is used with a custom debounce for this particular event.
  26288. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  26289. * is specified, once the timer runs out.
  26290. *
  26291. * When used with standard inputs, the view value will always be a string (which is in some cases
  26292. * parsed into another type, such as a `Date` object for `input[date]`.)
  26293. * However, custom controls might also pass objects to this method. In this case, we should make
  26294. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  26295. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  26296. * the property of the object then ngModel will not realize that the object has changed and
  26297. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  26298. * not change properties of the copy once it has been passed to `$setViewValue`.
  26299. * Otherwise you may cause the model value on the scope to change incorrectly.
  26300. *
  26301. * <div class="alert alert-info">
  26302. * In any case, the value passed to the method should always reflect the current value
  26303. * of the control. For example, if you are calling `$setViewValue` for an input element,
  26304. * you should pass the input DOM value. Otherwise, the control and the scope model become
  26305. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  26306. * the control's DOM value in any way. If we want to change the control's DOM value
  26307. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  26308. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  26309. * to update the DOM, and finally call `$validate` on it.
  26310. * </div>
  26311. *
  26312. * @param {*} value value from the view.
  26313. * @param {string} trigger Event that triggered the update.
  26314. */
  26315. $setViewValue: function(value, trigger) {
  26316. this.$viewValue = value;
  26317. if (this.$options.getOption('updateOnDefault')) {
  26318. this.$$debounceViewValueCommit(trigger);
  26319. }
  26320. },
  26321. $$debounceViewValueCommit: function(trigger) {
  26322. var debounceDelay = this.$options.getOption('debounce');
  26323. if (isNumber(debounceDelay[trigger])) {
  26324. debounceDelay = debounceDelay[trigger];
  26325. } else if (isNumber(debounceDelay['default'])) {
  26326. debounceDelay = debounceDelay['default'];
  26327. }
  26328. this.$$timeout.cancel(this.$$pendingDebounce);
  26329. var that = this;
  26330. if (debounceDelay > 0) { // this fails if debounceDelay is an object
  26331. this.$$pendingDebounce = this.$$timeout(function() {
  26332. that.$commitViewValue();
  26333. }, debounceDelay);
  26334. } else if (this.$$scope.$root.$$phase) {
  26335. this.$commitViewValue();
  26336. } else {
  26337. this.$$scope.$apply(function() {
  26338. that.$commitViewValue();
  26339. });
  26340. }
  26341. },
  26342. /**
  26343. * @ngdoc method
  26344. *
  26345. * @name ngModel.NgModelController#$overrideModelOptions
  26346. *
  26347. * @description
  26348. *
  26349. * Override the current model options settings programmatically.
  26350. *
  26351. * The previous `ModelOptions` value will not be modified. Instead, a
  26352. * new `ModelOptions` object will inherit from the previous one overriding
  26353. * or inheriting settings that are defined in the given parameter.
  26354. *
  26355. * See {@link ngModelOptions} for information about what options can be specified
  26356. * and how model option inheritance works.
  26357. *
  26358. * @param {Object} options a hash of settings to override the previous options
  26359. *
  26360. */
  26361. $overrideModelOptions: function(options) {
  26362. this.$options = this.$options.createChild(options);
  26363. }
  26364. };
  26365. function setupModelWatcher(ctrl) {
  26366. // model -> value
  26367. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  26368. // 1. scope value is 'a'
  26369. // 2. user enters 'b'
  26370. // 3. ng-change kicks in and reverts scope value to 'a'
  26371. // -> scope value did not change since the last digest as
  26372. // ng-change executes in apply phase
  26373. // 4. view should be changed back to 'a'
  26374. ctrl.$$scope.$watch(function ngModelWatch(scope) {
  26375. var modelValue = ctrl.$$ngModelGet(scope);
  26376. // if scope model value and ngModel value are out of sync
  26377. // TODO(perf): why not move this to the action fn?
  26378. if (modelValue !== ctrl.$modelValue &&
  26379. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  26380. // eslint-disable-next-line no-self-compare
  26381. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  26382. ) {
  26383. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  26384. ctrl.$$parserValid = undefined;
  26385. var formatters = ctrl.$formatters,
  26386. idx = formatters.length;
  26387. var viewValue = modelValue;
  26388. while (idx--) {
  26389. viewValue = formatters[idx](viewValue);
  26390. }
  26391. if (ctrl.$viewValue !== viewValue) {
  26392. ctrl.$$updateEmptyClasses(viewValue);
  26393. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  26394. ctrl.$render();
  26395. // It is possible that model and view value have been updated during render
  26396. ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);
  26397. }
  26398. }
  26399. return modelValue;
  26400. });
  26401. }
  26402. /**
  26403. * @ngdoc method
  26404. * @name ngModel.NgModelController#$setValidity
  26405. *
  26406. * @description
  26407. * Change the validity state, and notify the form.
  26408. *
  26409. * This method can be called within $parsers/$formatters or a custom validation implementation.
  26410. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  26411. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  26412. *
  26413. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  26414. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  26415. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  26416. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  26417. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  26418. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  26419. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  26420. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  26421. * Skipped is used by Angular when validators do not run because of parse errors and
  26422. * when `$asyncValidators` do not run because any of the `$validators` failed.
  26423. */
  26424. addSetValidityMethod({
  26425. clazz: NgModelController,
  26426. set: function(object, property) {
  26427. object[property] = true;
  26428. },
  26429. unset: function(object, property) {
  26430. delete object[property];
  26431. }
  26432. });
  26433. /**
  26434. * @ngdoc directive
  26435. * @name ngModel
  26436. *
  26437. * @element input
  26438. * @priority 1
  26439. *
  26440. * @description
  26441. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  26442. * property on the scope using {@link ngModel.NgModelController NgModelController},
  26443. * which is created and exposed by this directive.
  26444. *
  26445. * `ngModel` is responsible for:
  26446. *
  26447. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  26448. * require.
  26449. * - Providing validation behavior (i.e. required, number, email, url).
  26450. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  26451. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  26452. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  26453. * - Registering the control with its parent {@link ng.directive:form form}.
  26454. *
  26455. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  26456. * current scope. If the property doesn't already exist on this scope, it will be created
  26457. * implicitly and added to the scope.
  26458. *
  26459. * For best practices on using `ngModel`, see:
  26460. *
  26461. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  26462. *
  26463. * For basic examples, how to use `ngModel`, see:
  26464. *
  26465. * - {@link ng.directive:input input}
  26466. * - {@link input[text] text}
  26467. * - {@link input[checkbox] checkbox}
  26468. * - {@link input[radio] radio}
  26469. * - {@link input[number] number}
  26470. * - {@link input[email] email}
  26471. * - {@link input[url] url}
  26472. * - {@link input[date] date}
  26473. * - {@link input[datetime-local] datetime-local}
  26474. * - {@link input[time] time}
  26475. * - {@link input[month] month}
  26476. * - {@link input[week] week}
  26477. * - {@link ng.directive:select select}
  26478. * - {@link ng.directive:textarea textarea}
  26479. *
  26480. * # Complex Models (objects or collections)
  26481. *
  26482. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  26483. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  26484. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  26485. *
  26486. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  26487. *
  26488. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  26489. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  26490. * if the select is given the `multiple` attribute.
  26491. *
  26492. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  26493. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  26494. * not trigger a re-rendering of the model.
  26495. *
  26496. * # CSS classes
  26497. * The following CSS classes are added and removed on the associated input/select/textarea element
  26498. * depending on the validity of the model.
  26499. *
  26500. * - `ng-valid`: the model is valid
  26501. * - `ng-invalid`: the model is invalid
  26502. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  26503. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  26504. * - `ng-pristine`: the control hasn't been interacted with yet
  26505. * - `ng-dirty`: the control has been interacted with
  26506. * - `ng-touched`: the control has been blurred
  26507. * - `ng-untouched`: the control hasn't been blurred
  26508. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  26509. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  26510. * by the {@link ngModel.NgModelController#$isEmpty} method
  26511. * - `ng-not-empty`: the view contains a non-empty value
  26512. *
  26513. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  26514. *
  26515. * ## Animation Hooks
  26516. *
  26517. * Animations within models are triggered when any of the associated CSS classes are added and removed
  26518. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  26519. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  26520. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  26521. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  26522. *
  26523. * The following example shows a simple way to utilize CSS transitions to style an input element
  26524. * that has been rendered as invalid after it has been validated:
  26525. *
  26526. * <pre>
  26527. * //be sure to include ngAnimate as a module to hook into more
  26528. * //advanced animations
  26529. * .my-input {
  26530. * transition:0.5s linear all;
  26531. * background: white;
  26532. * }
  26533. * .my-input.ng-invalid {
  26534. * background: red;
  26535. * color:white;
  26536. * }
  26537. * </pre>
  26538. *
  26539. * @example
  26540. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
  26541. <file name="index.html">
  26542. <script>
  26543. angular.module('inputExample', [])
  26544. .controller('ExampleController', ['$scope', function($scope) {
  26545. $scope.val = '1';
  26546. }]);
  26547. </script>
  26548. <style>
  26549. .my-input {
  26550. transition:all linear 0.5s;
  26551. background: transparent;
  26552. }
  26553. .my-input.ng-invalid {
  26554. color:white;
  26555. background: red;
  26556. }
  26557. </style>
  26558. <p id="inputDescription">
  26559. Update input to see transitions when valid/invalid.
  26560. Integer is a valid value.
  26561. </p>
  26562. <form name="testForm" ng-controller="ExampleController">
  26563. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  26564. aria-describedby="inputDescription" />
  26565. </form>
  26566. </file>
  26567. * </example>
  26568. *
  26569. * ## Binding to a getter/setter
  26570. *
  26571. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  26572. * function that returns a representation of the model when called with zero arguments, and sets
  26573. * the internal state of a model when called with an argument. It's sometimes useful to use this
  26574. * for models that have an internal representation that's different from what the model exposes
  26575. * to the view.
  26576. *
  26577. * <div class="alert alert-success">
  26578. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  26579. * frequently than other parts of your code.
  26580. * </div>
  26581. *
  26582. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  26583. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  26584. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  26585. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  26586. *
  26587. * The following example shows how to use `ngModel` with a getter/setter:
  26588. *
  26589. * @example
  26590. * <example name="ngModel-getter-setter" module="getterSetterExample">
  26591. <file name="index.html">
  26592. <div ng-controller="ExampleController">
  26593. <form name="userForm">
  26594. <label>Name:
  26595. <input type="text" name="userName"
  26596. ng-model="user.name"
  26597. ng-model-options="{ getterSetter: true }" />
  26598. </label>
  26599. </form>
  26600. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26601. </div>
  26602. </file>
  26603. <file name="app.js">
  26604. angular.module('getterSetterExample', [])
  26605. .controller('ExampleController', ['$scope', function($scope) {
  26606. var _name = 'Brian';
  26607. $scope.user = {
  26608. name: function(newName) {
  26609. // Note that newName can be undefined for two reasons:
  26610. // 1. Because it is called as a getter and thus called with no arguments
  26611. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  26612. // input is invalid
  26613. return arguments.length ? (_name = newName) : _name;
  26614. }
  26615. };
  26616. }]);
  26617. </file>
  26618. * </example>
  26619. */
  26620. var ngModelDirective = ['$rootScope', function($rootScope) {
  26621. return {
  26622. restrict: 'A',
  26623. require: ['ngModel', '^?form', '^?ngModelOptions'],
  26624. controller: NgModelController,
  26625. // Prelink needs to run before any input directive
  26626. // so that we can set the NgModelOptions in NgModelController
  26627. // before anyone else uses it.
  26628. priority: 1,
  26629. compile: function ngModelCompile(element) {
  26630. // Setup initial state of the control
  26631. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  26632. return {
  26633. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  26634. var modelCtrl = ctrls[0],
  26635. formCtrl = ctrls[1] || modelCtrl.$$parentForm,
  26636. optionsCtrl = ctrls[2];
  26637. if (optionsCtrl) {
  26638. modelCtrl.$options = optionsCtrl.$options;
  26639. }
  26640. modelCtrl.$$initGetterSetters();
  26641. // notify others, especially parent forms
  26642. formCtrl.$addControl(modelCtrl);
  26643. attr.$observe('name', function(newValue) {
  26644. if (modelCtrl.$name !== newValue) {
  26645. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  26646. }
  26647. });
  26648. scope.$on('$destroy', function() {
  26649. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  26650. });
  26651. },
  26652. post: function ngModelPostLink(scope, element, attr, ctrls) {
  26653. var modelCtrl = ctrls[0];
  26654. if (modelCtrl.$options.getOption('updateOn')) {
  26655. element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {
  26656. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  26657. });
  26658. }
  26659. function setTouched() {
  26660. modelCtrl.$setTouched();
  26661. }
  26662. element.on('blur', function() {
  26663. if (modelCtrl.$touched) return;
  26664. if ($rootScope.$$phase) {
  26665. scope.$evalAsync(setTouched);
  26666. } else {
  26667. scope.$apply(setTouched);
  26668. }
  26669. });
  26670. }
  26671. };
  26672. }
  26673. };
  26674. }];
  26675. /* exported defaultModelOptions */
  26676. var defaultModelOptions;
  26677. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  26678. /**
  26679. * @ngdoc type
  26680. * @name ModelOptions
  26681. * @description
  26682. * A container for the options set by the {@link ngModelOptions} directive
  26683. */
  26684. function ModelOptions(options) {
  26685. this.$$options = options;
  26686. }
  26687. ModelOptions.prototype = {
  26688. /**
  26689. * @ngdoc method
  26690. * @name ModelOptions#getOption
  26691. * @param {string} name the name of the option to retrieve
  26692. * @returns {*} the value of the option
  26693. * @description
  26694. * Returns the value of the given option
  26695. */
  26696. getOption: function(name) {
  26697. return this.$$options[name];
  26698. },
  26699. /**
  26700. * @ngdoc method
  26701. * @name ModelOptions#createChild
  26702. * @param {Object} options a hash of options for the new child that will override the parent's options
  26703. * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
  26704. */
  26705. createChild: function(options) {
  26706. var inheritAll = false;
  26707. // make a shallow copy
  26708. options = extend({}, options);
  26709. // Inherit options from the parent if specified by the value `"$inherit"`
  26710. forEach(options, /* @this */ function(option, key) {
  26711. if (option === '$inherit') {
  26712. if (key === '*') {
  26713. inheritAll = true;
  26714. } else {
  26715. options[key] = this.$$options[key];
  26716. // `updateOn` is special so we must also inherit the `updateOnDefault` option
  26717. if (key === 'updateOn') {
  26718. options.updateOnDefault = this.$$options.updateOnDefault;
  26719. }
  26720. }
  26721. } else {
  26722. if (key === 'updateOn') {
  26723. // If the `updateOn` property contains the `default` event then we have to remove
  26724. // it from the event list and set the `updateOnDefault` flag.
  26725. options.updateOnDefault = false;
  26726. options[key] = trim(option.replace(DEFAULT_REGEXP, function() {
  26727. options.updateOnDefault = true;
  26728. return ' ';
  26729. }));
  26730. }
  26731. }
  26732. }, this);
  26733. if (inheritAll) {
  26734. // We have a property of the form: `"*": "$inherit"`
  26735. delete options['*'];
  26736. defaults(options, this.$$options);
  26737. }
  26738. // Finally add in any missing defaults
  26739. defaults(options, defaultModelOptions.$$options);
  26740. return new ModelOptions(options);
  26741. }
  26742. };
  26743. defaultModelOptions = new ModelOptions({
  26744. updateOn: '',
  26745. updateOnDefault: true,
  26746. debounce: 0,
  26747. getterSetter: false,
  26748. allowInvalid: false,
  26749. timezone: null
  26750. });
  26751. /**
  26752. * @ngdoc directive
  26753. * @name ngModelOptions
  26754. *
  26755. * @description
  26756. * This directive allows you to modify the behaviour of {@link ngModel} directives within your
  26757. * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}
  26758. * directives will use the options of their nearest `ngModelOptions` ancestor.
  26759. *
  26760. * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as
  26761. * an Angular expression. This expression should evaluate to an object, whose properties contain
  26762. * the settings. For example: `<div "ng-model-options"="{ debounce: 100 }"`.
  26763. *
  26764. * ## Inheriting Options
  26765. *
  26766. * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions`
  26767. * directive by giving it the value of `"$inherit"`.
  26768. * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the
  26769. * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings
  26770. * will be used.
  26771. *
  26772. * For example given the following fragment of HTML
  26773. *
  26774. *
  26775. * ```html
  26776. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  26777. * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }">
  26778. * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" />
  26779. * </form>
  26780. * </div>
  26781. * ```
  26782. *
  26783. * the `input` element will have the following settings
  26784. *
  26785. * ```js
  26786. * { allowInvalid: true, updateOn: 'default', debounce: 0 }
  26787. * ```
  26788. *
  26789. * Notice that the `debounce` setting was not inherited and used the default value instead.
  26790. *
  26791. * You can specify that all undefined settings are automatically inherited from an ancestor by
  26792. * including a property with key of `"*"` and value of `"$inherit"`.
  26793. *
  26794. * For example given the following fragment of HTML
  26795. *
  26796. *
  26797. * ```html
  26798. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  26799. * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }">
  26800. * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" />
  26801. * </form>
  26802. * </div>
  26803. * ```
  26804. *
  26805. * the `input` element will have the following settings
  26806. *
  26807. * ```js
  26808. * { allowInvalid: true, updateOn: 'default', debounce: 200 }
  26809. * ```
  26810. *
  26811. * Notice that the `debounce` setting now inherits the value from the outer `<div>` element.
  26812. *
  26813. * If you are creating a reusable component then you should be careful when using `"*": "$inherit"`
  26814. * since you may inadvertently inherit a setting in the future that changes the behavior of your component.
  26815. *
  26816. *
  26817. * ## Triggering and debouncing model updates
  26818. *
  26819. * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
  26820. * trigger a model update and/or a debouncing delay so that the actual update only takes place when
  26821. * a timer expires; this timer will be reset after another change takes place.
  26822. *
  26823. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  26824. * be different from the value in the actual model. This means that if you update the model you
  26825. * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in
  26826. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  26827. *
  26828. * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}
  26829. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  26830. * important because `form` controllers are published to the related scope under the name in their
  26831. * `name` attribute.
  26832. *
  26833. * Any pending changes will take place immediately when an enclosing form is submitted via the
  26834. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  26835. * to have access to the updated model.
  26836. *
  26837. * The following example shows how to override immediate updates. Changes on the inputs within the
  26838. * form will update the model only when the control loses focus (blur event). If `escape` key is
  26839. * pressed while the input field is focused, the value is reset to the value in the current model.
  26840. *
  26841. * <example name="ngModelOptions-directive-blur" module="optionsExample">
  26842. * <file name="index.html">
  26843. * <div ng-controller="ExampleController">
  26844. * <form name="userForm">
  26845. * <label>
  26846. * Name:
  26847. * <input type="text" name="userName"
  26848. * ng-model="user.name"
  26849. * ng-model-options="{ updateOn: 'blur' }"
  26850. * ng-keyup="cancel($event)" />
  26851. * </label><br />
  26852. * <label>
  26853. * Other data:
  26854. * <input type="text" ng-model="user.data" />
  26855. * </label><br />
  26856. * </form>
  26857. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  26858. * </div>
  26859. * </file>
  26860. * <file name="app.js">
  26861. * angular.module('optionsExample', [])
  26862. * .controller('ExampleController', ['$scope', function($scope) {
  26863. * $scope.user = { name: 'say', data: '' };
  26864. *
  26865. * $scope.cancel = function(e) {
  26866. * if (e.keyCode === 27) {
  26867. * $scope.userForm.userName.$rollbackViewValue();
  26868. * }
  26869. * };
  26870. * }]);
  26871. * </file>
  26872. * <file name="protractor.js" type="protractor">
  26873. * var model = element(by.binding('user.name'));
  26874. * var input = element(by.model('user.name'));
  26875. * var other = element(by.model('user.data'));
  26876. *
  26877. * it('should allow custom events', function() {
  26878. * input.sendKeys(' hello');
  26879. * input.click();
  26880. * expect(model.getText()).toEqual('say');
  26881. * other.click();
  26882. * expect(model.getText()).toEqual('say hello');
  26883. * });
  26884. *
  26885. * it('should $rollbackViewValue when model changes', function() {
  26886. * input.sendKeys(' hello');
  26887. * expect(input.getAttribute('value')).toEqual('say hello');
  26888. * input.sendKeys(protractor.Key.ESCAPE);
  26889. * expect(input.getAttribute('value')).toEqual('say');
  26890. * other.click();
  26891. * expect(model.getText()).toEqual('say');
  26892. * });
  26893. * </file>
  26894. * </example>
  26895. *
  26896. * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
  26897. * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  26898. *
  26899. * <example name="ngModelOptions-directive-debounce" module="optionsExample">
  26900. * <file name="index.html">
  26901. * <div ng-controller="ExampleController">
  26902. * <form name="userForm">
  26903. * Name:
  26904. * <input type="text" name="userName"
  26905. * ng-model="user.name"
  26906. * ng-model-options="{ debounce: 1000 }" />
  26907. * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  26908. * </form>
  26909. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  26910. * </div>
  26911. * </file>
  26912. * <file name="app.js">
  26913. * angular.module('optionsExample', [])
  26914. * .controller('ExampleController', ['$scope', function($scope) {
  26915. * $scope.user = { name: 'say' };
  26916. * }]);
  26917. * </file>
  26918. * </example>
  26919. *
  26920. * ## Model updates and validation
  26921. *
  26922. * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
  26923. * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
  26924. * the model will still be updated even if the value is invalid.
  26925. *
  26926. *
  26927. * ## Connecting to the scope
  26928. *
  26929. * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
  26930. * on the scope refers to a "getter/setter" function rather than the value itself.
  26931. *
  26932. * The following example shows how to bind to getter/setters:
  26933. *
  26934. * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  26935. * <file name="index.html">
  26936. * <div ng-controller="ExampleController">
  26937. * <form name="userForm">
  26938. * <label>
  26939. * Name:
  26940. * <input type="text" name="userName"
  26941. * ng-model="user.name"
  26942. * ng-model-options="{ getterSetter: true }" />
  26943. * </label>
  26944. * </form>
  26945. * <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26946. * </div>
  26947. * </file>
  26948. * <file name="app.js">
  26949. * angular.module('getterSetterExample', [])
  26950. * .controller('ExampleController', ['$scope', function($scope) {
  26951. * var _name = 'Brian';
  26952. * $scope.user = {
  26953. * name: function(newName) {
  26954. * return angular.isDefined(newName) ? (_name = newName) : _name;
  26955. * }
  26956. * };
  26957. * }]);
  26958. * </file>
  26959. * </example>
  26960. *
  26961. *
  26962. * ## Specifying timezones
  26963. *
  26964. * You can specify the timezone that date/time input directives expect by providing its name in the
  26965. * `timezone` property.
  26966. *
  26967. * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and
  26968. * and its descendents. Valid keys are:
  26969. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  26970. * events using an space delimited list. There is a special event called `default` that
  26971. * matches the default events belonging to the control.
  26972. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  26973. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  26974. * custom value for each event. For example:
  26975. * ```
  26976. * ng-model-options="{
  26977. * updateOn: 'default blur',
  26978. * debounce: { 'default': 500, 'blur': 0 }
  26979. * }"
  26980. * ```
  26981. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  26982. * not validate correctly instead of the default behavior of setting the model to undefined.
  26983. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  26984. * `ngModel` as getters/setters.
  26985. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  26986. * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
  26987. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  26988. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  26989. * If not specified, the timezone of the browser will be used.
  26990. *
  26991. */
  26992. var ngModelOptionsDirective = function() {
  26993. NgModelOptionsController.$inject = ['$attrs', '$scope'];
  26994. function NgModelOptionsController($attrs, $scope) {
  26995. this.$$attrs = $attrs;
  26996. this.$$scope = $scope;
  26997. }
  26998. NgModelOptionsController.prototype = {
  26999. $onInit: function() {
  27000. var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;
  27001. var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);
  27002. this.$options = parentOptions.createChild(modelOptionsDefinition);
  27003. }
  27004. };
  27005. return {
  27006. restrict: 'A',
  27007. // ngModelOptions needs to run before ngModel and input directives
  27008. priority: 10,
  27009. require: {parentCtrl: '?^^ngModelOptions'},
  27010. bindToController: true,
  27011. controller: NgModelOptionsController
  27012. };
  27013. };
  27014. // shallow copy over values from `src` that are not already specified on `dst`
  27015. function defaults(dst, src) {
  27016. forEach(src, function(value, key) {
  27017. if (!isDefined(dst[key])) {
  27018. dst[key] = value;
  27019. }
  27020. });
  27021. }
  27022. /**
  27023. * @ngdoc directive
  27024. * @name ngNonBindable
  27025. * @restrict AC
  27026. * @priority 1000
  27027. *
  27028. * @description
  27029. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  27030. * DOM element. This is useful if the element contains what appears to be Angular directives and
  27031. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  27032. * displays snippets of code, for instance.
  27033. *
  27034. * @element ANY
  27035. *
  27036. * @example
  27037. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  27038. * but the one wrapped in `ngNonBindable` is left alone.
  27039. *
  27040. * @example
  27041. <example name="ng-non-bindable">
  27042. <file name="index.html">
  27043. <div>Normal: {{1 + 2}}</div>
  27044. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  27045. </file>
  27046. <file name="protractor.js" type="protractor">
  27047. it('should check ng-non-bindable', function() {
  27048. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  27049. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  27050. });
  27051. </file>
  27052. </example>
  27053. */
  27054. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  27055. /* exported ngOptionsDirective */
  27056. /* global jqLiteRemove */
  27057. var ngOptionsMinErr = minErr('ngOptions');
  27058. /**
  27059. * @ngdoc directive
  27060. * @name ngOptions
  27061. * @restrict A
  27062. *
  27063. * @description
  27064. *
  27065. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  27066. * elements for the `<select>` element using the array or object obtained by evaluating the
  27067. * `ngOptions` comprehension expression.
  27068. *
  27069. * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
  27070. * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
  27071. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  27072. * comprehension expression
  27073. * - reduced memory consumption by not creating a new scope for each repeated instance
  27074. * - increased render speed by creating the options in a documentFragment instead of individually
  27075. *
  27076. * When an item in the `<select>` menu is selected, the array element or object property
  27077. * represented by the selected option will be bound to the model identified by the `ngModel`
  27078. * directive.
  27079. *
  27080. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  27081. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  27082. * option. See example below for demonstration.
  27083. *
  27084. * ## Complex Models (objects or collections)
  27085. *
  27086. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  27087. * binding the select to a model that is an object or a collection.
  27088. *
  27089. * One issue occurs if you want to preselect an option. For example, if you set
  27090. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  27091. * because the objects are not identical. So by default, you should always reference the item in your collection
  27092. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  27093. *
  27094. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  27095. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  27096. * collection items have an id property, you would `track by item.id`.
  27097. *
  27098. * A different issue with objects or collections is that ngModel won't detect if an object property or
  27099. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  27100. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  27101. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  27102. * has not changed identity, but only a property on the object or an item in the collection changes.
  27103. *
  27104. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  27105. * if the model is an array). This means that changing a property deeper than the first level inside the
  27106. * object/collection will not trigger a re-rendering.
  27107. *
  27108. * ## `select` **`as`**
  27109. *
  27110. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  27111. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  27112. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  27113. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  27114. *
  27115. *
  27116. * ### `select` **`as`** and **`track by`**
  27117. *
  27118. * <div class="alert alert-warning">
  27119. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  27120. * </div>
  27121. *
  27122. * Given this array of items on the $scope:
  27123. *
  27124. * ```js
  27125. * $scope.items = [{
  27126. * id: 1,
  27127. * label: 'aLabel',
  27128. * subItem: { name: 'aSubItem' }
  27129. * }, {
  27130. * id: 2,
  27131. * label: 'bLabel',
  27132. * subItem: { name: 'bSubItem' }
  27133. * }];
  27134. * ```
  27135. *
  27136. * This will work:
  27137. *
  27138. * ```html
  27139. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  27140. * ```
  27141. * ```js
  27142. * $scope.selected = $scope.items[0];
  27143. * ```
  27144. *
  27145. * but this will not work:
  27146. *
  27147. * ```html
  27148. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  27149. * ```
  27150. * ```js
  27151. * $scope.selected = $scope.items[0].subItem;
  27152. * ```
  27153. *
  27154. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  27155. * `items` array. Because the selected option has been set programmatically in the controller, the
  27156. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  27157. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  27158. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  27159. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  27160. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  27161. *
  27162. *
  27163. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  27164. * @param {comprehension_expression} ngOptions in one of the following forms:
  27165. *
  27166. * * for array data sources:
  27167. * * `label` **`for`** `value` **`in`** `array`
  27168. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  27169. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  27170. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  27171. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  27172. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  27173. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  27174. * (for including a filter with `track by`)
  27175. * * for object data sources:
  27176. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  27177. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  27178. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  27179. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  27180. * * `select` **`as`** `label` **`group by`** `group`
  27181. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  27182. * * `select` **`as`** `label` **`disable when`** `disable`
  27183. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  27184. *
  27185. * Where:
  27186. *
  27187. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  27188. * * `value`: local variable which will refer to each item in the `array` or each property value
  27189. * of `object` during iteration.
  27190. * * `key`: local variable which will refer to a property name in `object` during iteration.
  27191. * * `label`: The result of this expression will be the label for `<option>` element. The
  27192. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  27193. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  27194. * element. If not specified, `select` expression will default to `value`.
  27195. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  27196. * DOM element.
  27197. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  27198. * element. Return `true` to disable.
  27199. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  27200. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  27201. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  27202. * even when the options are recreated (e.g. reloaded from the server).
  27203. * @param {string=} name Property name of the form under which the control is published.
  27204. * @param {string=} required The control is considered valid only if value is entered.
  27205. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  27206. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  27207. * `required` when you want to data-bind to the `required` attribute.
  27208. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  27209. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  27210. *
  27211. * @example
  27212. <example module="selectExample" name="select">
  27213. <file name="index.html">
  27214. <script>
  27215. angular.module('selectExample', [])
  27216. .controller('ExampleController', ['$scope', function($scope) {
  27217. $scope.colors = [
  27218. {name:'black', shade:'dark'},
  27219. {name:'white', shade:'light', notAnOption: true},
  27220. {name:'red', shade:'dark'},
  27221. {name:'blue', shade:'dark', notAnOption: true},
  27222. {name:'yellow', shade:'light', notAnOption: false}
  27223. ];
  27224. $scope.myColor = $scope.colors[2]; // red
  27225. }]);
  27226. </script>
  27227. <div ng-controller="ExampleController">
  27228. <ul>
  27229. <li ng-repeat="color in colors">
  27230. <label>Name: <input ng-model="color.name"></label>
  27231. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  27232. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  27233. </li>
  27234. <li>
  27235. <button ng-click="colors.push({})">add</button>
  27236. </li>
  27237. </ul>
  27238. <hr/>
  27239. <label>Color (null not allowed):
  27240. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  27241. </label><br/>
  27242. <label>Color (null allowed):
  27243. <span class="nullable">
  27244. <select ng-model="myColor" ng-options="color.name for color in colors">
  27245. <option value="">-- choose color --</option>
  27246. </select>
  27247. </span></label><br/>
  27248. <label>Color grouped by shade:
  27249. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  27250. </select>
  27251. </label><br/>
  27252. <label>Color grouped by shade, with some disabled:
  27253. <select ng-model="myColor"
  27254. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  27255. </select>
  27256. </label><br/>
  27257. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  27258. <br/>
  27259. <hr/>
  27260. Currently selected: {{ {selected_color:myColor} }}
  27261. <div style="border:solid 1px black; height:20px"
  27262. ng-style="{'background-color':myColor.name}">
  27263. </div>
  27264. </div>
  27265. </file>
  27266. <file name="protractor.js" type="protractor">
  27267. it('should check ng-options', function() {
  27268. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  27269. element.all(by.model('myColor')).first().click();
  27270. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  27271. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  27272. element(by.css('.nullable select[ng-model="myColor"]')).click();
  27273. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  27274. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  27275. });
  27276. </file>
  27277. </example>
  27278. */
  27279. /* eslint-disable max-len */
  27280. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
  27281. 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]+?))?$/;
  27282. // 1: value expression (valueFn)
  27283. // 2: label expression (displayFn)
  27284. // 3: group by expression (groupByFn)
  27285. // 4: disable when expression (disableWhenFn)
  27286. // 5: array item variable name
  27287. // 6: object item key variable name
  27288. // 7: object item value variable name
  27289. // 8: collection expression
  27290. // 9: track by expression
  27291. /* eslint-enable */
  27292. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  27293. function parseOptionsExpression(optionsExp, selectElement, scope) {
  27294. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  27295. if (!(match)) {
  27296. throw ngOptionsMinErr('iexp',
  27297. 'Expected expression in form of ' +
  27298. '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
  27299. ' but got \'{0}\'. Element: {1}',
  27300. optionsExp, startingTag(selectElement));
  27301. }
  27302. // Extract the parts from the ngOptions expression
  27303. // The variable name for the value of the item in the collection
  27304. var valueName = match[5] || match[7];
  27305. // The variable name for the key of the item in the collection
  27306. var keyName = match[6];
  27307. // An expression that generates the viewValue for an option if there is a label expression
  27308. var selectAs = / as /.test(match[0]) && match[1];
  27309. // An expression that is used to track the id of each object in the options collection
  27310. var trackBy = match[9];
  27311. // An expression that generates the viewValue for an option if there is no label expression
  27312. var valueFn = $parse(match[2] ? match[1] : valueName);
  27313. var selectAsFn = selectAs && $parse(selectAs);
  27314. var viewValueFn = selectAsFn || valueFn;
  27315. var trackByFn = trackBy && $parse(trackBy);
  27316. // Get the value by which we are going to track the option
  27317. // if we have a trackFn then use that (passing scope and locals)
  27318. // otherwise just hash the given viewValue
  27319. var getTrackByValueFn = trackBy ?
  27320. function(value, locals) { return trackByFn(scope, locals); } :
  27321. function getHashOfValue(value) { return hashKey(value); };
  27322. var getTrackByValue = function(value, key) {
  27323. return getTrackByValueFn(value, getLocals(value, key));
  27324. };
  27325. var displayFn = $parse(match[2] || match[1]);
  27326. var groupByFn = $parse(match[3] || '');
  27327. var disableWhenFn = $parse(match[4] || '');
  27328. var valuesFn = $parse(match[8]);
  27329. var locals = {};
  27330. var getLocals = keyName ? function(value, key) {
  27331. locals[keyName] = key;
  27332. locals[valueName] = value;
  27333. return locals;
  27334. } : function(value) {
  27335. locals[valueName] = value;
  27336. return locals;
  27337. };
  27338. function Option(selectValue, viewValue, label, group, disabled) {
  27339. this.selectValue = selectValue;
  27340. this.viewValue = viewValue;
  27341. this.label = label;
  27342. this.group = group;
  27343. this.disabled = disabled;
  27344. }
  27345. function getOptionValuesKeys(optionValues) {
  27346. var optionValuesKeys;
  27347. if (!keyName && isArrayLike(optionValues)) {
  27348. optionValuesKeys = optionValues;
  27349. } else {
  27350. // if object, extract keys, in enumeration order, unsorted
  27351. optionValuesKeys = [];
  27352. for (var itemKey in optionValues) {
  27353. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  27354. optionValuesKeys.push(itemKey);
  27355. }
  27356. }
  27357. }
  27358. return optionValuesKeys;
  27359. }
  27360. return {
  27361. trackBy: trackBy,
  27362. getTrackByValue: getTrackByValue,
  27363. getWatchables: $parse(valuesFn, function(optionValues) {
  27364. // Create a collection of things that we would like to watch (watchedArray)
  27365. // so that they can all be watched using a single $watchCollection
  27366. // that only runs the handler once if anything changes
  27367. var watchedArray = [];
  27368. optionValues = optionValues || [];
  27369. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27370. var optionValuesLength = optionValuesKeys.length;
  27371. for (var index = 0; index < optionValuesLength; index++) {
  27372. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27373. var value = optionValues[key];
  27374. var locals = getLocals(value, key);
  27375. var selectValue = getTrackByValueFn(value, locals);
  27376. watchedArray.push(selectValue);
  27377. // Only need to watch the displayFn if there is a specific label expression
  27378. if (match[2] || match[1]) {
  27379. var label = displayFn(scope, locals);
  27380. watchedArray.push(label);
  27381. }
  27382. // Only need to watch the disableWhenFn if there is a specific disable expression
  27383. if (match[4]) {
  27384. var disableWhen = disableWhenFn(scope, locals);
  27385. watchedArray.push(disableWhen);
  27386. }
  27387. }
  27388. return watchedArray;
  27389. }),
  27390. getOptions: function() {
  27391. var optionItems = [];
  27392. var selectValueMap = {};
  27393. // The option values were already computed in the `getWatchables` fn,
  27394. // which must have been called to trigger `getOptions`
  27395. var optionValues = valuesFn(scope) || [];
  27396. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27397. var optionValuesLength = optionValuesKeys.length;
  27398. for (var index = 0; index < optionValuesLength; index++) {
  27399. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27400. var value = optionValues[key];
  27401. var locals = getLocals(value, key);
  27402. var viewValue = viewValueFn(scope, locals);
  27403. var selectValue = getTrackByValueFn(viewValue, locals);
  27404. var label = displayFn(scope, locals);
  27405. var group = groupByFn(scope, locals);
  27406. var disabled = disableWhenFn(scope, locals);
  27407. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  27408. optionItems.push(optionItem);
  27409. selectValueMap[selectValue] = optionItem;
  27410. }
  27411. return {
  27412. items: optionItems,
  27413. selectValueMap: selectValueMap,
  27414. getOptionFromViewValue: function(value) {
  27415. return selectValueMap[getTrackByValue(value)];
  27416. },
  27417. getViewValueFromOption: function(option) {
  27418. // If the viewValue could be an object that may be mutated by the application,
  27419. // we need to make a copy and not return the reference to the value on the option.
  27420. return trackBy ? copy(option.viewValue) : option.viewValue;
  27421. }
  27422. };
  27423. }
  27424. };
  27425. }
  27426. // we can't just jqLite('<option>') since jqLite is not smart enough
  27427. // to create it in <select> and IE barfs otherwise.
  27428. var optionTemplate = window.document.createElement('option'),
  27429. optGroupTemplate = window.document.createElement('optgroup');
  27430. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  27431. var selectCtrl = ctrls[0];
  27432. var ngModelCtrl = ctrls[1];
  27433. var multiple = attr.multiple;
  27434. // The emptyOption allows the application developer to provide their own custom "empty"
  27435. // option when the viewValue does not match any of the option values.
  27436. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  27437. if (children[i].value === '') {
  27438. selectCtrl.hasEmptyOption = true;
  27439. selectCtrl.emptyOption = children.eq(i);
  27440. break;
  27441. }
  27442. }
  27443. var providedEmptyOption = !!selectCtrl.emptyOption;
  27444. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  27445. unknownOption.val('?');
  27446. var options;
  27447. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  27448. // This stores the newly created options before they are appended to the select.
  27449. // Since the contents are removed from the fragment when it is appended,
  27450. // we only need to create it once.
  27451. var listFragment = $document[0].createDocumentFragment();
  27452. // Overwrite the implementation. ngOptions doesn't use hashes
  27453. selectCtrl.generateUnknownOptionValue = function(val) {
  27454. return '?';
  27455. };
  27456. // Update the controller methods for multiple selectable options
  27457. if (!multiple) {
  27458. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  27459. var selectedOption = options.selectValueMap[selectElement.val()];
  27460. var option = options.getOptionFromViewValue(value);
  27461. // Make sure to remove the selected attribute from the previously selected option
  27462. // Otherwise, screen readers might get confused
  27463. if (selectedOption) selectedOption.element.removeAttribute('selected');
  27464. if (option) {
  27465. // Don't update the option when it is already selected.
  27466. // For example, the browser will select the first option by default. In that case,
  27467. // most properties are set automatically - except the `selected` attribute, which we
  27468. // set always
  27469. if (selectElement[0].value !== option.selectValue) {
  27470. selectCtrl.removeUnknownOption();
  27471. selectCtrl.unselectEmptyOption();
  27472. selectElement[0].value = option.selectValue;
  27473. option.element.selected = true;
  27474. }
  27475. option.element.setAttribute('selected', 'selected');
  27476. } else {
  27477. if (providedEmptyOption) {
  27478. selectCtrl.selectEmptyOption();
  27479. } else if (selectCtrl.unknownOption.parent().length) {
  27480. selectCtrl.updateUnknownOption(value);
  27481. } else {
  27482. selectCtrl.renderUnknownOption(value);
  27483. }
  27484. }
  27485. };
  27486. selectCtrl.readValue = function readNgOptionsValue() {
  27487. var selectedOption = options.selectValueMap[selectElement.val()];
  27488. if (selectedOption && !selectedOption.disabled) {
  27489. selectCtrl.unselectEmptyOption();
  27490. selectCtrl.removeUnknownOption();
  27491. return options.getViewValueFromOption(selectedOption);
  27492. }
  27493. return null;
  27494. };
  27495. // If we are using `track by` then we must watch the tracked value on the model
  27496. // since ngModel only watches for object identity change
  27497. // FIXME: When a user selects an option, this watch will fire needlessly
  27498. if (ngOptions.trackBy) {
  27499. scope.$watch(
  27500. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  27501. function() { ngModelCtrl.$render(); }
  27502. );
  27503. }
  27504. } else {
  27505. selectCtrl.writeValue = function writeNgOptionsMultiple(values) {
  27506. // Only set `<option>.selected` if necessary, in order to prevent some browsers from
  27507. // scrolling to `<option>` elements that are outside the `<select>` element's viewport.
  27508. var selectedOptions = values && values.map(getAndUpdateSelectedOption) || [];
  27509. options.items.forEach(function(option) {
  27510. if (option.element.selected && !includes(selectedOptions, option)) {
  27511. option.element.selected = false;
  27512. }
  27513. });
  27514. };
  27515. selectCtrl.readValue = function readNgOptionsMultiple() {
  27516. var selectedValues = selectElement.val() || [],
  27517. selections = [];
  27518. forEach(selectedValues, function(value) {
  27519. var option = options.selectValueMap[value];
  27520. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  27521. });
  27522. return selections;
  27523. };
  27524. // If we are using `track by` then we must watch these tracked values on the model
  27525. // since ngModel only watches for object identity change
  27526. if (ngOptions.trackBy) {
  27527. scope.$watchCollection(function() {
  27528. if (isArray(ngModelCtrl.$viewValue)) {
  27529. return ngModelCtrl.$viewValue.map(function(value) {
  27530. return ngOptions.getTrackByValue(value);
  27531. });
  27532. }
  27533. }, function() {
  27534. ngModelCtrl.$render();
  27535. });
  27536. }
  27537. }
  27538. if (providedEmptyOption) {
  27539. // we need to remove it before calling selectElement.empty() because otherwise IE will
  27540. // remove the label from the element. wtf?
  27541. selectCtrl.emptyOption.remove();
  27542. // compile the element since there might be bindings in it
  27543. $compile(selectCtrl.emptyOption)(scope);
  27544. if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
  27545. // This means the empty option has currently no actual DOM node, probably because
  27546. // it has been modified by a transclusion directive.
  27547. selectCtrl.hasEmptyOption = false;
  27548. // Redefine the registerOption function, which will catch
  27549. // options that are added by ngIf etc. (rendering of the node is async because of
  27550. // lazy transclusion)
  27551. selectCtrl.registerOption = function(optionScope, optionEl) {
  27552. if (optionEl.val() === '') {
  27553. selectCtrl.hasEmptyOption = true;
  27554. selectCtrl.emptyOption = optionEl;
  27555. selectCtrl.emptyOption.removeClass('ng-scope');
  27556. // This ensures the new empty option is selected if previously no option was selected
  27557. ngModelCtrl.$render();
  27558. optionEl.on('$destroy', function() {
  27559. selectCtrl.hasEmptyOption = false;
  27560. selectCtrl.emptyOption = undefined;
  27561. });
  27562. }
  27563. };
  27564. } else {
  27565. // remove the class, which is added automatically because we recompile the element and it
  27566. // becomes the compilation root
  27567. selectCtrl.emptyOption.removeClass('ng-scope');
  27568. }
  27569. }
  27570. selectElement.empty();
  27571. // We need to do this here to ensure that the options object is defined
  27572. // when we first hit it in writeNgOptionsValue
  27573. updateOptions();
  27574. // We will re-render the option elements if the option values or labels change
  27575. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  27576. // ------------------------------------------------------------------ //
  27577. function addOptionElement(option, parent) {
  27578. var optionElement = optionTemplate.cloneNode(false);
  27579. parent.appendChild(optionElement);
  27580. updateOptionElement(option, optionElement);
  27581. }
  27582. function getAndUpdateSelectedOption(viewValue) {
  27583. var option = options.getOptionFromViewValue(viewValue);
  27584. var element = option && option.element;
  27585. if (element && !element.selected) element.selected = true;
  27586. return option;
  27587. }
  27588. function updateOptionElement(option, element) {
  27589. option.element = element;
  27590. element.disabled = option.disabled;
  27591. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  27592. // selects in certain circumstances when multiple selects are next to each other and display
  27593. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  27594. // See https://github.com/angular/angular.js/issues/11314 for more info.
  27595. // This is unfortunately untestable with unit / e2e tests
  27596. if (option.label !== element.label) {
  27597. element.label = option.label;
  27598. element.textContent = option.label;
  27599. }
  27600. element.value = option.selectValue;
  27601. }
  27602. function updateOptions() {
  27603. var previousValue = options && selectCtrl.readValue();
  27604. // We must remove all current options, but cannot simply set innerHTML = null
  27605. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  27606. // must preserve.
  27607. // Instead, iterate over the current option elements and remove them or their optgroup
  27608. // parents
  27609. if (options) {
  27610. for (var i = options.items.length - 1; i >= 0; i--) {
  27611. var option = options.items[i];
  27612. if (isDefined(option.group)) {
  27613. jqLiteRemove(option.element.parentNode);
  27614. } else {
  27615. jqLiteRemove(option.element);
  27616. }
  27617. }
  27618. }
  27619. options = ngOptions.getOptions();
  27620. var groupElementMap = {};
  27621. // Ensure that the empty option is always there if it was explicitly provided
  27622. if (providedEmptyOption) {
  27623. selectElement.prepend(selectCtrl.emptyOption);
  27624. }
  27625. options.items.forEach(function addOption(option) {
  27626. var groupElement;
  27627. if (isDefined(option.group)) {
  27628. // This option is to live in a group
  27629. // See if we have already created this group
  27630. groupElement = groupElementMap[option.group];
  27631. if (!groupElement) {
  27632. groupElement = optGroupTemplate.cloneNode(false);
  27633. listFragment.appendChild(groupElement);
  27634. // Update the label on the group element
  27635. // "null" is special cased because of Safari
  27636. groupElement.label = option.group === null ? 'null' : option.group;
  27637. // Store it for use later
  27638. groupElementMap[option.group] = groupElement;
  27639. }
  27640. addOptionElement(option, groupElement);
  27641. } else {
  27642. // This option is not in a group
  27643. addOptionElement(option, listFragment);
  27644. }
  27645. });
  27646. selectElement[0].appendChild(listFragment);
  27647. ngModelCtrl.$render();
  27648. // Check to see if the value has changed due to the update to the options
  27649. if (!ngModelCtrl.$isEmpty(previousValue)) {
  27650. var nextValue = selectCtrl.readValue();
  27651. var isNotPrimitive = ngOptions.trackBy || multiple;
  27652. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  27653. ngModelCtrl.$setViewValue(nextValue);
  27654. ngModelCtrl.$render();
  27655. }
  27656. }
  27657. }
  27658. }
  27659. return {
  27660. restrict: 'A',
  27661. terminal: true,
  27662. require: ['select', 'ngModel'],
  27663. link: {
  27664. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  27665. // Deactivate the SelectController.register method to prevent
  27666. // option directives from accidentally registering themselves
  27667. // (and unwanted $destroy handlers etc.)
  27668. ctrls[0].registerOption = noop;
  27669. },
  27670. post: ngOptionsPostLink
  27671. }
  27672. };
  27673. }];
  27674. /**
  27675. * @ngdoc directive
  27676. * @name ngPluralize
  27677. * @restrict EA
  27678. *
  27679. * @description
  27680. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  27681. * These rules are bundled with angular.js, but can be overridden
  27682. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  27683. * by specifying the mappings between
  27684. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27685. * and the strings to be displayed.
  27686. *
  27687. * # Plural categories and explicit number rules
  27688. * There are two
  27689. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27690. * in Angular's default en-US locale: "one" and "other".
  27691. *
  27692. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  27693. * any number that is not 1), an explicit number rule can only match one number. For example, the
  27694. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  27695. * and explicit number rules throughout the rest of this documentation.
  27696. *
  27697. * # Configuring ngPluralize
  27698. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  27699. * You can also provide an optional attribute, `offset`.
  27700. *
  27701. * The value of the `count` attribute can be either a string or an {@link guide/expression
  27702. * Angular expression}; these are evaluated on the current scope for its bound value.
  27703. *
  27704. * The `when` attribute specifies the mappings between plural categories and the actual
  27705. * string to be displayed. The value of the attribute should be a JSON object.
  27706. *
  27707. * The following example shows how to configure ngPluralize:
  27708. *
  27709. * ```html
  27710. * <ng-pluralize count="personCount"
  27711. when="{'0': 'Nobody is viewing.',
  27712. * 'one': '1 person is viewing.',
  27713. * 'other': '{} people are viewing.'}">
  27714. * </ng-pluralize>
  27715. *```
  27716. *
  27717. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  27718. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  27719. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  27720. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  27721. * show "a dozen people are viewing".
  27722. *
  27723. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  27724. * into pluralized strings. In the previous example, Angular will replace `{}` with
  27725. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  27726. * for <span ng-non-bindable>{{numberExpression}}</span>.
  27727. *
  27728. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  27729. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  27730. *
  27731. * # Configuring ngPluralize with offset
  27732. * The `offset` attribute allows further customization of pluralized text, which can result in
  27733. * a better user experience. For example, instead of the message "4 people are viewing this document",
  27734. * you might display "John, Kate and 2 others are viewing this document".
  27735. * The offset attribute allows you to offset a number by any desired value.
  27736. * Let's take a look at an example:
  27737. *
  27738. * ```html
  27739. * <ng-pluralize count="personCount" offset=2
  27740. * when="{'0': 'Nobody is viewing.',
  27741. * '1': '{{person1}} is viewing.',
  27742. * '2': '{{person1}} and {{person2}} are viewing.',
  27743. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  27744. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  27745. * </ng-pluralize>
  27746. * ```
  27747. *
  27748. * Notice that we are still using two plural categories(one, other), but we added
  27749. * three explicit number rules 0, 1 and 2.
  27750. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  27751. * When three people view the document, no explicit number rule is found, so
  27752. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  27753. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  27754. * is shown.
  27755. *
  27756. * Note that when you specify offsets, you must provide explicit number rules for
  27757. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  27758. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  27759. * plural categories "one" and "other".
  27760. *
  27761. * @param {string|expression} count The variable to be bound to.
  27762. * @param {string} when The mapping between plural category to its corresponding strings.
  27763. * @param {number=} offset Offset to deduct from the total number.
  27764. *
  27765. * @example
  27766. <example module="pluralizeExample" name="ng-pluralize">
  27767. <file name="index.html">
  27768. <script>
  27769. angular.module('pluralizeExample', [])
  27770. .controller('ExampleController', ['$scope', function($scope) {
  27771. $scope.person1 = 'Igor';
  27772. $scope.person2 = 'Misko';
  27773. $scope.personCount = 1;
  27774. }]);
  27775. </script>
  27776. <div ng-controller="ExampleController">
  27777. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  27778. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  27779. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  27780. <!--- Example with simple pluralization rules for en locale --->
  27781. Without Offset:
  27782. <ng-pluralize count="personCount"
  27783. when="{'0': 'Nobody is viewing.',
  27784. 'one': '1 person is viewing.',
  27785. 'other': '{} people are viewing.'}">
  27786. </ng-pluralize><br>
  27787. <!--- Example with offset --->
  27788. With Offset(2):
  27789. <ng-pluralize count="personCount" offset=2
  27790. when="{'0': 'Nobody is viewing.',
  27791. '1': '{{person1}} is viewing.',
  27792. '2': '{{person1}} and {{person2}} are viewing.',
  27793. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  27794. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  27795. </ng-pluralize>
  27796. </div>
  27797. </file>
  27798. <file name="protractor.js" type="protractor">
  27799. it('should show correct pluralized string', function() {
  27800. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  27801. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  27802. var countInput = element(by.model('personCount'));
  27803. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  27804. expect(withOffset.getText()).toEqual('Igor is viewing.');
  27805. countInput.clear();
  27806. countInput.sendKeys('0');
  27807. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  27808. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  27809. countInput.clear();
  27810. countInput.sendKeys('2');
  27811. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  27812. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  27813. countInput.clear();
  27814. countInput.sendKeys('3');
  27815. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  27816. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  27817. countInput.clear();
  27818. countInput.sendKeys('4');
  27819. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  27820. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  27821. });
  27822. it('should show data-bound names', function() {
  27823. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  27824. var personCount = element(by.model('personCount'));
  27825. var person1 = element(by.model('person1'));
  27826. var person2 = element(by.model('person2'));
  27827. personCount.clear();
  27828. personCount.sendKeys('4');
  27829. person1.clear();
  27830. person1.sendKeys('Di');
  27831. person2.clear();
  27832. person2.sendKeys('Vojta');
  27833. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  27834. });
  27835. </file>
  27836. </example>
  27837. */
  27838. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  27839. var BRACE = /{}/g,
  27840. IS_WHEN = /^when(Minus)?(.+)$/;
  27841. return {
  27842. link: function(scope, element, attr) {
  27843. var numberExp = attr.count,
  27844. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  27845. offset = attr.offset || 0,
  27846. whens = scope.$eval(whenExp) || {},
  27847. whensExpFns = {},
  27848. startSymbol = $interpolate.startSymbol(),
  27849. endSymbol = $interpolate.endSymbol(),
  27850. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  27851. watchRemover = angular.noop,
  27852. lastCount;
  27853. forEach(attr, function(expression, attributeName) {
  27854. var tmpMatch = IS_WHEN.exec(attributeName);
  27855. if (tmpMatch) {
  27856. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  27857. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  27858. }
  27859. });
  27860. forEach(whens, function(expression, key) {
  27861. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  27862. });
  27863. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  27864. var count = parseFloat(newVal);
  27865. var countIsNaN = isNumberNaN(count);
  27866. if (!countIsNaN && !(count in whens)) {
  27867. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  27868. // Otherwise, check it against pluralization rules in $locale service.
  27869. count = $locale.pluralCat(count - offset);
  27870. }
  27871. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  27872. // In JS `NaN !== NaN`, so we have to explicitly check.
  27873. if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
  27874. watchRemover();
  27875. var whenExpFn = whensExpFns[count];
  27876. if (isUndefined(whenExpFn)) {
  27877. if (newVal != null) {
  27878. $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
  27879. }
  27880. watchRemover = noop;
  27881. updateElementText();
  27882. } else {
  27883. watchRemover = scope.$watch(whenExpFn, updateElementText);
  27884. }
  27885. lastCount = count;
  27886. }
  27887. });
  27888. function updateElementText(newText) {
  27889. element.text(newText || '');
  27890. }
  27891. }
  27892. };
  27893. }];
  27894. /* exported ngRepeatDirective */
  27895. /**
  27896. * @ngdoc directive
  27897. * @name ngRepeat
  27898. * @multiElement
  27899. * @restrict A
  27900. *
  27901. * @description
  27902. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  27903. * instance gets its own scope, where the given loop variable is set to the current collection item,
  27904. * and `$index` is set to the item index or key.
  27905. *
  27906. * Special properties are exposed on the local scope of each template instance, including:
  27907. *
  27908. * | Variable | Type | Details |
  27909. * |-----------|-----------------|-----------------------------------------------------------------------------|
  27910. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  27911. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  27912. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  27913. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  27914. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  27915. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  27916. *
  27917. * <div class="alert alert-info">
  27918. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  27919. * This may be useful when, for instance, nesting ngRepeats.
  27920. * </div>
  27921. *
  27922. *
  27923. * # Iterating over object properties
  27924. *
  27925. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  27926. * syntax:
  27927. *
  27928. * ```js
  27929. * <div ng-repeat="(key, value) in myObj"> ... </div>
  27930. * ```
  27931. *
  27932. * However, there are a few limitations compared to array iteration:
  27933. *
  27934. * - The JavaScript specification does not define the order of keys
  27935. * returned for an object, so Angular relies on the order returned by the browser
  27936. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  27937. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  27938. * and reinstated. See the
  27939. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  27940. *
  27941. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  27942. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  27943. *
  27944. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  27945. * objects, and will throw an error if used with one.
  27946. *
  27947. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  27948. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  27949. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  27950. * or implement a `$watch` on the object yourself.
  27951. *
  27952. *
  27953. * # Tracking and Duplicates
  27954. *
  27955. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  27956. * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
  27957. *
  27958. * * When an item is added, a new instance of the template is added to the DOM.
  27959. * * When an item is removed, its template instance is removed from the DOM.
  27960. * * When items are reordered, their respective templates are reordered in the DOM.
  27961. *
  27962. * To minimize creation of DOM elements, `ngRepeat` uses a function
  27963. * to "keep track" of all items in the collection and their corresponding DOM elements.
  27964. * For example, if an item is added to the collection, `ngRepeat` will know that all other items
  27965. * already have DOM elements, and will not re-render them.
  27966. *
  27967. * The default tracking function (which tracks items by their identity) does not allow
  27968. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  27969. * to maintain a one-to-one mapping between collection items and DOM elements.
  27970. *
  27971. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  27972. * with your own using the `track by` expression.
  27973. *
  27974. * For example, you may track items by the index of each item in the collection, using the
  27975. * special scope property `$index`:
  27976. * ```html
  27977. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  27978. * {{n}}
  27979. * </div>
  27980. * ```
  27981. *
  27982. * You may also use arbitrary expressions in `track by`, including references to custom functions
  27983. * on the scope:
  27984. * ```html
  27985. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  27986. * {{n}}
  27987. * </div>
  27988. * ```
  27989. *
  27990. * <div class="alert alert-success">
  27991. * If you are working with objects that have a unique identifier property, you should track
  27992. * by this identifier instead of the object instance. Should you reload your data later, `ngRepeat`
  27993. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  27994. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  27995. * this significantly improves rendering performance. If you don't have a unique identifier,
  27996. * `track by $index` can also provide a performance boost.
  27997. * </div>
  27998. *
  27999. * ```html
  28000. * <div ng-repeat="model in collection track by model.id">
  28001. * {{model.name}}
  28002. * </div>
  28003. * ```
  28004. *
  28005. * <br />
  28006. * <div class="alert alert-warning">
  28007. * Avoid using `track by $index` when the repeated template contains
  28008. * {@link guide/expression#one-time-binding one-time bindings}. In such cases, the `nth` DOM
  28009. * element will always be matched with the `nth` item of the array, so the bindings on that element
  28010. * will not be updated even when the corresponding item changes, essentially causing the view to get
  28011. * out-of-sync with the underlying data.
  28012. * </div>
  28013. *
  28014. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  28015. * `$id` function, which tracks items by their identity:
  28016. * ```html
  28017. * <div ng-repeat="obj in collection track by $id(obj)">
  28018. * {{obj.prop}}
  28019. * </div>
  28020. * ```
  28021. *
  28022. * <br />
  28023. * <div class="alert alert-warning">
  28024. * **Note:** `track by` must always be the last expression:
  28025. * </div>
  28026. * ```
  28027. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  28028. * {{model.name}}
  28029. * </div>
  28030. * ```
  28031. *
  28032. *
  28033. * # Special repeat start and end points
  28034. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  28035. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  28036. * 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)
  28037. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  28038. *
  28039. * The example below makes use of this feature:
  28040. * ```html
  28041. * <header ng-repeat-start="item in items">
  28042. * Header {{ item }}
  28043. * </header>
  28044. * <div class="body">
  28045. * Body {{ item }}
  28046. * </div>
  28047. * <footer ng-repeat-end>
  28048. * Footer {{ item }}
  28049. * </footer>
  28050. * ```
  28051. *
  28052. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  28053. * ```html
  28054. * <header>
  28055. * Header A
  28056. * </header>
  28057. * <div class="body">
  28058. * Body A
  28059. * </div>
  28060. * <footer>
  28061. * Footer A
  28062. * </footer>
  28063. * <header>
  28064. * Header B
  28065. * </header>
  28066. * <div class="body">
  28067. * Body B
  28068. * </div>
  28069. * <footer>
  28070. * Footer B
  28071. * </footer>
  28072. * ```
  28073. *
  28074. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  28075. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  28076. *
  28077. * @animations
  28078. * | Animation | Occurs |
  28079. * |----------------------------------|-------------------------------------|
  28080. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  28081. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  28082. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  28083. *
  28084. * See the example below for defining CSS animations with ngRepeat.
  28085. *
  28086. * @element ANY
  28087. * @scope
  28088. * @priority 1000
  28089. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  28090. * formats are currently supported:
  28091. *
  28092. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  28093. * is a scope expression giving the collection to enumerate.
  28094. *
  28095. * For example: `album in artist.albums`.
  28096. *
  28097. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  28098. * and `expression` is the scope expression giving the collection to enumerate.
  28099. *
  28100. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  28101. *
  28102. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  28103. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  28104. * is specified, ng-repeat associates elements by identity. It is an error to have
  28105. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  28106. * mapped to the same DOM element, which is not possible.)
  28107. *
  28108. * Note that the tracking expression must come last, after any filters, and the alias expression.
  28109. *
  28110. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  28111. * will be associated by item identity in the array.
  28112. *
  28113. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  28114. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  28115. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  28116. * element in the same way in the DOM.
  28117. *
  28118. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  28119. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  28120. * property is same.
  28121. *
  28122. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  28123. * to items in conjunction with a tracking expression.
  28124. *
  28125. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  28126. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  28127. * when a filter is active on the repeater, but the filtered result set is empty.
  28128. *
  28129. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  28130. * the items have been processed through the filter.
  28131. *
  28132. * 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
  28133. * (and not as operator, inside an expression).
  28134. *
  28135. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  28136. *
  28137. * @example
  28138. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  28139. * results by name or by age. New (entering) and removed (leaving) items are animated.
  28140. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true" name="ng-repeat">
  28141. <file name="index.html">
  28142. <div ng-controller="repeatController">
  28143. I have {{friends.length}} friends. They are:
  28144. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  28145. <ul class="example-animate-container">
  28146. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  28147. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  28148. </li>
  28149. <li class="animate-repeat" ng-if="results.length === 0">
  28150. <strong>No results found...</strong>
  28151. </li>
  28152. </ul>
  28153. </div>
  28154. </file>
  28155. <file name="script.js">
  28156. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  28157. $scope.friends = [
  28158. {name:'John', age:25, gender:'boy'},
  28159. {name:'Jessie', age:30, gender:'girl'},
  28160. {name:'Johanna', age:28, gender:'girl'},
  28161. {name:'Joy', age:15, gender:'girl'},
  28162. {name:'Mary', age:28, gender:'girl'},
  28163. {name:'Peter', age:95, gender:'boy'},
  28164. {name:'Sebastian', age:50, gender:'boy'},
  28165. {name:'Erika', age:27, gender:'girl'},
  28166. {name:'Patrick', age:40, gender:'boy'},
  28167. {name:'Samantha', age:60, gender:'girl'}
  28168. ];
  28169. });
  28170. </file>
  28171. <file name="animations.css">
  28172. .example-animate-container {
  28173. background:white;
  28174. border:1px solid black;
  28175. list-style:none;
  28176. margin:0;
  28177. padding:0 10px;
  28178. }
  28179. .animate-repeat {
  28180. line-height:30px;
  28181. list-style:none;
  28182. box-sizing:border-box;
  28183. }
  28184. .animate-repeat.ng-move,
  28185. .animate-repeat.ng-enter,
  28186. .animate-repeat.ng-leave {
  28187. transition:all linear 0.5s;
  28188. }
  28189. .animate-repeat.ng-leave.ng-leave-active,
  28190. .animate-repeat.ng-move,
  28191. .animate-repeat.ng-enter {
  28192. opacity:0;
  28193. max-height:0;
  28194. }
  28195. .animate-repeat.ng-leave,
  28196. .animate-repeat.ng-move.ng-move-active,
  28197. .animate-repeat.ng-enter.ng-enter-active {
  28198. opacity:1;
  28199. max-height:30px;
  28200. }
  28201. </file>
  28202. <file name="protractor.js" type="protractor">
  28203. var friends = element.all(by.repeater('friend in friends'));
  28204. it('should render initial data set', function() {
  28205. expect(friends.count()).toBe(10);
  28206. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  28207. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  28208. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  28209. expect(element(by.binding('friends.length')).getText())
  28210. .toMatch("I have 10 friends. They are:");
  28211. });
  28212. it('should update repeater when filter predicate changes', function() {
  28213. expect(friends.count()).toBe(10);
  28214. element(by.model('q')).sendKeys('ma');
  28215. expect(friends.count()).toBe(2);
  28216. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  28217. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  28218. });
  28219. </file>
  28220. </example>
  28221. */
  28222. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  28223. var NG_REMOVED = '$$NG_REMOVED';
  28224. var ngRepeatMinErr = minErr('ngRepeat');
  28225. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  28226. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  28227. scope[valueIdentifier] = value;
  28228. if (keyIdentifier) scope[keyIdentifier] = key;
  28229. scope.$index = index;
  28230. scope.$first = (index === 0);
  28231. scope.$last = (index === (arrayLength - 1));
  28232. scope.$middle = !(scope.$first || scope.$last);
  28233. // eslint-disable-next-line no-bitwise
  28234. scope.$odd = !(scope.$even = (index & 1) === 0);
  28235. };
  28236. var getBlockStart = function(block) {
  28237. return block.clone[0];
  28238. };
  28239. var getBlockEnd = function(block) {
  28240. return block.clone[block.clone.length - 1];
  28241. };
  28242. return {
  28243. restrict: 'A',
  28244. multiElement: true,
  28245. transclude: 'element',
  28246. priority: 1000,
  28247. terminal: true,
  28248. $$tlb: true,
  28249. compile: function ngRepeatCompile($element, $attr) {
  28250. var expression = $attr.ngRepeat;
  28251. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  28252. 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*$/);
  28253. if (!match) {
  28254. throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
  28255. expression);
  28256. }
  28257. var lhs = match[1];
  28258. var rhs = match[2];
  28259. var aliasAs = match[3];
  28260. var trackByExp = match[4];
  28261. match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
  28262. if (!match) {
  28263. throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
  28264. lhs);
  28265. }
  28266. var valueIdentifier = match[3] || match[1];
  28267. var keyIdentifier = match[2];
  28268. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  28269. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  28270. throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
  28271. aliasAs);
  28272. }
  28273. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  28274. var hashFnLocals = {$id: hashKey};
  28275. if (trackByExp) {
  28276. trackByExpGetter = $parse(trackByExp);
  28277. } else {
  28278. trackByIdArrayFn = function(key, value) {
  28279. return hashKey(value);
  28280. };
  28281. trackByIdObjFn = function(key) {
  28282. return key;
  28283. };
  28284. }
  28285. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  28286. if (trackByExpGetter) {
  28287. trackByIdExpFn = function(key, value, index) {
  28288. // assign key, value, and $index to the locals so that they can be used in hash functions
  28289. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  28290. hashFnLocals[valueIdentifier] = value;
  28291. hashFnLocals.$index = index;
  28292. return trackByExpGetter($scope, hashFnLocals);
  28293. };
  28294. }
  28295. // Store a list of elements from previous run. This is a hash where key is the item from the
  28296. // iterator, and the value is objects with following properties.
  28297. // - scope: bound scope
  28298. // - element: previous element.
  28299. // - index: position
  28300. //
  28301. // We are using no-proto object so that we don't need to guard against inherited props via
  28302. // hasOwnProperty.
  28303. var lastBlockMap = createMap();
  28304. //watch props
  28305. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  28306. var index, length,
  28307. previousNode = $element[0], // node that cloned nodes should be inserted after
  28308. // initialized to the comment node anchor
  28309. nextNode,
  28310. // Same as lastBlockMap but it has the current state. It will become the
  28311. // lastBlockMap on the next iteration.
  28312. nextBlockMap = createMap(),
  28313. collectionLength,
  28314. key, value, // key/value of iteration
  28315. trackById,
  28316. trackByIdFn,
  28317. collectionKeys,
  28318. block, // last object information {scope, element, id}
  28319. nextBlockOrder,
  28320. elementsToRemove;
  28321. if (aliasAs) {
  28322. $scope[aliasAs] = collection;
  28323. }
  28324. if (isArrayLike(collection)) {
  28325. collectionKeys = collection;
  28326. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  28327. } else {
  28328. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  28329. // if object, extract keys, in enumeration order, unsorted
  28330. collectionKeys = [];
  28331. for (var itemKey in collection) {
  28332. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  28333. collectionKeys.push(itemKey);
  28334. }
  28335. }
  28336. }
  28337. collectionLength = collectionKeys.length;
  28338. nextBlockOrder = new Array(collectionLength);
  28339. // locate existing items
  28340. for (index = 0; index < collectionLength; index++) {
  28341. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28342. value = collection[key];
  28343. trackById = trackByIdFn(key, value, index);
  28344. if (lastBlockMap[trackById]) {
  28345. // found previously seen block
  28346. block = lastBlockMap[trackById];
  28347. delete lastBlockMap[trackById];
  28348. nextBlockMap[trackById] = block;
  28349. nextBlockOrder[index] = block;
  28350. } else if (nextBlockMap[trackById]) {
  28351. // if collision detected. restore lastBlockMap and throw an error
  28352. forEach(nextBlockOrder, function(block) {
  28353. if (block && block.scope) lastBlockMap[block.id] = block;
  28354. });
  28355. throw ngRepeatMinErr('dupes',
  28356. 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
  28357. expression, trackById, value);
  28358. } else {
  28359. // new never before seen block
  28360. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  28361. nextBlockMap[trackById] = true;
  28362. }
  28363. }
  28364. // remove leftover items
  28365. for (var blockKey in lastBlockMap) {
  28366. block = lastBlockMap[blockKey];
  28367. elementsToRemove = getBlockNodes(block.clone);
  28368. $animate.leave(elementsToRemove);
  28369. if (elementsToRemove[0].parentNode) {
  28370. // if the element was not removed yet because of pending animation, mark it as deleted
  28371. // so that we can ignore it later
  28372. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  28373. elementsToRemove[index][NG_REMOVED] = true;
  28374. }
  28375. }
  28376. block.scope.$destroy();
  28377. }
  28378. // we are not using forEach for perf reasons (trying to avoid #call)
  28379. for (index = 0; index < collectionLength; index++) {
  28380. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28381. value = collection[key];
  28382. block = nextBlockOrder[index];
  28383. if (block.scope) {
  28384. // if we have already seen this object, then we need to reuse the
  28385. // associated scope/element
  28386. nextNode = previousNode;
  28387. // skip nodes that are already pending removal via leave animation
  28388. do {
  28389. nextNode = nextNode.nextSibling;
  28390. } while (nextNode && nextNode[NG_REMOVED]);
  28391. if (getBlockStart(block) !== nextNode) {
  28392. // existing item which got moved
  28393. $animate.move(getBlockNodes(block.clone), null, previousNode);
  28394. }
  28395. previousNode = getBlockEnd(block);
  28396. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28397. } else {
  28398. // new item which we don't know about
  28399. $transclude(function ngRepeatTransclude(clone, scope) {
  28400. block.scope = scope;
  28401. // http://jsperf.com/clone-vs-createcomment
  28402. var endNode = ngRepeatEndComment.cloneNode(false);
  28403. clone[clone.length++] = endNode;
  28404. $animate.enter(clone, null, previousNode);
  28405. previousNode = endNode;
  28406. // Note: We only need the first/last node of the cloned nodes.
  28407. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  28408. // by a directive with templateUrl when its template arrives.
  28409. block.clone = clone;
  28410. nextBlockMap[block.id] = block;
  28411. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28412. });
  28413. }
  28414. }
  28415. lastBlockMap = nextBlockMap;
  28416. });
  28417. };
  28418. }
  28419. };
  28420. }];
  28421. var NG_HIDE_CLASS = 'ng-hide';
  28422. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  28423. /**
  28424. * @ngdoc directive
  28425. * @name ngShow
  28426. * @multiElement
  28427. *
  28428. * @description
  28429. * The `ngShow` directive shows or hides the given HTML element based on the expression provided to
  28430. * the `ngShow` attribute.
  28431. *
  28432. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  28433. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  28434. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  28435. * {@link ng.directive:ngCsp ngCsp}).
  28436. *
  28437. * ```html
  28438. * <!-- when $scope.myValue is truthy (element is visible) -->
  28439. * <div ng-show="myValue"></div>
  28440. *
  28441. * <!-- when $scope.myValue is falsy (element is hidden) -->
  28442. * <div ng-show="myValue" class="ng-hide"></div>
  28443. * ```
  28444. *
  28445. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added
  28446. * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide`
  28447. * CSS class is removed from the element causing the element not to appear hidden.
  28448. *
  28449. * ## Why is `!important` used?
  28450. *
  28451. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  28452. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  28453. * simple as changing the display style on a HTML list item would make hidden elements appear
  28454. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  28455. *
  28456. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  28457. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  28458. * developer chooses to override the styling to change how to hide an element then it is just a
  28459. * matter of using `!important` in their own CSS code.
  28460. *
  28461. * ### Overriding `.ng-hide`
  28462. *
  28463. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  28464. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  28465. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  28466. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  28467. *
  28468. * ```css
  28469. * .ng-hide:not(.ng-hide-animate) {
  28470. * /&#42; These are just alternative ways of hiding an element &#42;/
  28471. * display: block!important;
  28472. * position: absolute;
  28473. * top: -9999px;
  28474. * left: -9999px;
  28475. * }
  28476. * ```
  28477. *
  28478. * By default you don't need to override anything in CSS and the animations will work around the
  28479. * display style.
  28480. *
  28481. * ## A note about animations with `ngShow`
  28482. *
  28483. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  28484. * directive expression is true and false. This system works like the animation system present with
  28485. * `ngClass` except that you must also include the `!important` flag to override the display
  28486. * property so that the elements are not actually hidden during the animation.
  28487. *
  28488. * ```css
  28489. * /&#42; A working example can be found at the bottom of this page. &#42;/
  28490. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28491. * transition: all 0.5s linear;
  28492. * }
  28493. *
  28494. * .my-element.ng-hide-add { ... }
  28495. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28496. * .my-element.ng-hide-remove { ... }
  28497. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28498. * ```
  28499. *
  28500. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  28501. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  28502. *
  28503. * @animations
  28504. * | Animation | Occurs |
  28505. * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
  28506. * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden. |
  28507. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. |
  28508. *
  28509. * @element ANY
  28510. * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the
  28511. * element is shown/hidden respectively.
  28512. *
  28513. * @example
  28514. * A simple example, animating the element's opacity:
  28515. *
  28516. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple">
  28517. <file name="index.html">
  28518. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  28519. <div class="check-element animate-show-hide" ng-show="checked">
  28520. I show up when your checkbox is checked.
  28521. </div>
  28522. </file>
  28523. <file name="animations.css">
  28524. .animate-show-hide.ng-hide {
  28525. opacity: 0;
  28526. }
  28527. .animate-show-hide.ng-hide-add,
  28528. .animate-show-hide.ng-hide-remove {
  28529. transition: all linear 0.5s;
  28530. }
  28531. .check-element {
  28532. border: 1px solid black;
  28533. opacity: 1;
  28534. padding: 10px;
  28535. }
  28536. </file>
  28537. <file name="protractor.js" type="protractor">
  28538. it('should check ngShow', function() {
  28539. var checkbox = element(by.model('checked'));
  28540. var checkElem = element(by.css('.check-element'));
  28541. expect(checkElem.isDisplayed()).toBe(false);
  28542. checkbox.click();
  28543. expect(checkElem.isDisplayed()).toBe(true);
  28544. });
  28545. </file>
  28546. </example>
  28547. *
  28548. * <hr />
  28549. * @example
  28550. * A more complex example, featuring different show/hide animations:
  28551. *
  28552. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex">
  28553. <file name="index.html">
  28554. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  28555. <div class="check-element funky-show-hide" ng-show="checked">
  28556. I show up when your checkbox is checked.
  28557. </div>
  28558. </file>
  28559. <file name="animations.css">
  28560. body {
  28561. overflow: hidden;
  28562. perspective: 1000px;
  28563. }
  28564. .funky-show-hide.ng-hide-add {
  28565. transform: rotateZ(0);
  28566. transform-origin: right;
  28567. transition: all 0.5s ease-in-out;
  28568. }
  28569. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  28570. transform: rotateZ(-135deg);
  28571. }
  28572. .funky-show-hide.ng-hide-remove {
  28573. transform: rotateY(90deg);
  28574. transform-origin: left;
  28575. transition: all 0.5s ease;
  28576. }
  28577. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  28578. transform: rotateY(0);
  28579. }
  28580. .check-element {
  28581. border: 1px solid black;
  28582. opacity: 1;
  28583. padding: 10px;
  28584. }
  28585. </file>
  28586. <file name="protractor.js" type="protractor">
  28587. it('should check ngShow', function() {
  28588. var checkbox = element(by.model('checked'));
  28589. var checkElem = element(by.css('.check-element'));
  28590. expect(checkElem.isDisplayed()).toBe(false);
  28591. checkbox.click();
  28592. expect(checkElem.isDisplayed()).toBe(true);
  28593. });
  28594. </file>
  28595. </example>
  28596. */
  28597. var ngShowDirective = ['$animate', function($animate) {
  28598. return {
  28599. restrict: 'A',
  28600. multiElement: true,
  28601. link: function(scope, element, attr) {
  28602. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  28603. // we're adding a temporary, animation-specific class for ng-hide since this way
  28604. // we can control when the element is actually displayed on screen without having
  28605. // to have a global/greedy CSS selector that breaks when other animations are run.
  28606. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  28607. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  28608. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28609. });
  28610. });
  28611. }
  28612. };
  28613. }];
  28614. /**
  28615. * @ngdoc directive
  28616. * @name ngHide
  28617. * @multiElement
  28618. *
  28619. * @description
  28620. * The `ngHide` directive shows or hides the given HTML element based on the expression provided to
  28621. * the `ngHide` attribute.
  28622. *
  28623. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  28624. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  28625. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  28626. * {@link ng.directive:ngCsp ngCsp}).
  28627. *
  28628. * ```html
  28629. * <!-- when $scope.myValue is truthy (element is hidden) -->
  28630. * <div ng-hide="myValue" class="ng-hide"></div>
  28631. *
  28632. * <!-- when $scope.myValue is falsy (element is visible) -->
  28633. * <div ng-hide="myValue"></div>
  28634. * ```
  28635. *
  28636. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added
  28637. * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide`
  28638. * CSS class is removed from the element causing the element not to appear hidden.
  28639. *
  28640. * ## Why is `!important` used?
  28641. *
  28642. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  28643. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  28644. * simple as changing the display style on a HTML list item would make hidden elements appear
  28645. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  28646. *
  28647. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  28648. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  28649. * developer chooses to override the styling to change how to hide an element then it is just a
  28650. * matter of using `!important` in their own CSS code.
  28651. *
  28652. * ### Overriding `.ng-hide`
  28653. *
  28654. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  28655. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  28656. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  28657. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  28658. *
  28659. * ```css
  28660. * .ng-hide:not(.ng-hide-animate) {
  28661. * /&#42; These are just alternative ways of hiding an element &#42;/
  28662. * display: block!important;
  28663. * position: absolute;
  28664. * top: -9999px;
  28665. * left: -9999px;
  28666. * }
  28667. * ```
  28668. *
  28669. * By default you don't need to override in CSS anything and the animations will work around the
  28670. * display style.
  28671. *
  28672. * ## A note about animations with `ngHide`
  28673. *
  28674. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  28675. * directive expression is true and false. This system works like the animation system present with
  28676. * `ngClass` except that you must also include the `!important` flag to override the display
  28677. * property so that the elements are not actually hidden during the animation.
  28678. *
  28679. * ```css
  28680. * /&#42; A working example can be found at the bottom of this page. &#42;/
  28681. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28682. * transition: all 0.5s linear;
  28683. * }
  28684. *
  28685. * .my-element.ng-hide-add { ... }
  28686. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28687. * .my-element.ng-hide-remove { ... }
  28688. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28689. * ```
  28690. *
  28691. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  28692. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  28693. *
  28694. * @animations
  28695. * | Animation | Occurs |
  28696. * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------|
  28697. * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. |
  28698. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. |
  28699. *
  28700. *
  28701. * @element ANY
  28702. * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the
  28703. * element is hidden/shown respectively.
  28704. *
  28705. * @example
  28706. * A simple example, animating the element's opacity:
  28707. *
  28708. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple">
  28709. <file name="index.html">
  28710. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  28711. <div class="check-element animate-show-hide" ng-hide="checked">
  28712. I hide when your checkbox is checked.
  28713. </div>
  28714. </file>
  28715. <file name="animations.css">
  28716. .animate-show-hide.ng-hide {
  28717. opacity: 0;
  28718. }
  28719. .animate-show-hide.ng-hide-add,
  28720. .animate-show-hide.ng-hide-remove {
  28721. transition: all linear 0.5s;
  28722. }
  28723. .check-element {
  28724. border: 1px solid black;
  28725. opacity: 1;
  28726. padding: 10px;
  28727. }
  28728. </file>
  28729. <file name="protractor.js" type="protractor">
  28730. it('should check ngHide', function() {
  28731. var checkbox = element(by.model('checked'));
  28732. var checkElem = element(by.css('.check-element'));
  28733. expect(checkElem.isDisplayed()).toBe(true);
  28734. checkbox.click();
  28735. expect(checkElem.isDisplayed()).toBe(false);
  28736. });
  28737. </file>
  28738. </example>
  28739. *
  28740. * <hr />
  28741. * @example
  28742. * A more complex example, featuring different show/hide animations:
  28743. *
  28744. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex">
  28745. <file name="index.html">
  28746. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  28747. <div class="check-element funky-show-hide" ng-hide="checked">
  28748. I hide when your checkbox is checked.
  28749. </div>
  28750. </file>
  28751. <file name="animations.css">
  28752. body {
  28753. overflow: hidden;
  28754. perspective: 1000px;
  28755. }
  28756. .funky-show-hide.ng-hide-add {
  28757. transform: rotateZ(0);
  28758. transform-origin: right;
  28759. transition: all 0.5s ease-in-out;
  28760. }
  28761. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  28762. transform: rotateZ(-135deg);
  28763. }
  28764. .funky-show-hide.ng-hide-remove {
  28765. transform: rotateY(90deg);
  28766. transform-origin: left;
  28767. transition: all 0.5s ease;
  28768. }
  28769. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  28770. transform: rotateY(0);
  28771. }
  28772. .check-element {
  28773. border: 1px solid black;
  28774. opacity: 1;
  28775. padding: 10px;
  28776. }
  28777. </file>
  28778. <file name="protractor.js" type="protractor">
  28779. it('should check ngHide', function() {
  28780. var checkbox = element(by.model('checked'));
  28781. var checkElem = element(by.css('.check-element'));
  28782. expect(checkElem.isDisplayed()).toBe(true);
  28783. checkbox.click();
  28784. expect(checkElem.isDisplayed()).toBe(false);
  28785. });
  28786. </file>
  28787. </example>
  28788. */
  28789. var ngHideDirective = ['$animate', function($animate) {
  28790. return {
  28791. restrict: 'A',
  28792. multiElement: true,
  28793. link: function(scope, element, attr) {
  28794. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  28795. // The comment inside of the ngShowDirective explains why we add and
  28796. // remove a temporary class for the show/hide animation
  28797. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  28798. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28799. });
  28800. });
  28801. }
  28802. };
  28803. }];
  28804. /**
  28805. * @ngdoc directive
  28806. * @name ngStyle
  28807. * @restrict AC
  28808. *
  28809. * @description
  28810. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  28811. *
  28812. * @knownIssue
  28813. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  28814. * attribute, when using the `ngStyle` directive on the same element.
  28815. * See {@link guide/interpolation#known-issues here} for more info.
  28816. *
  28817. * @element ANY
  28818. * @param {expression} ngStyle
  28819. *
  28820. * {@link guide/expression Expression} which evals to an
  28821. * object whose keys are CSS style names and values are corresponding values for those CSS
  28822. * keys.
  28823. *
  28824. * Since some CSS style names are not valid keys for an object, they must be quoted.
  28825. * See the 'background-color' style in the example below.
  28826. *
  28827. * @example
  28828. <example name="ng-style">
  28829. <file name="index.html">
  28830. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  28831. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  28832. <input type="button" value="clear" ng-click="myStyle={}">
  28833. <br/>
  28834. <span ng-style="myStyle">Sample Text</span>
  28835. <pre>myStyle={{myStyle}}</pre>
  28836. </file>
  28837. <file name="style.css">
  28838. span {
  28839. color: black;
  28840. }
  28841. </file>
  28842. <file name="protractor.js" type="protractor">
  28843. var colorSpan = element(by.css('span'));
  28844. it('should check ng-style', function() {
  28845. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  28846. element(by.css('input[value=\'set color\']')).click();
  28847. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  28848. element(by.css('input[value=clear]')).click();
  28849. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  28850. });
  28851. </file>
  28852. </example>
  28853. */
  28854. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  28855. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  28856. if (oldStyles && (newStyles !== oldStyles)) {
  28857. forEach(oldStyles, function(val, style) { element.css(style, '');});
  28858. }
  28859. if (newStyles) element.css(newStyles);
  28860. }, true);
  28861. });
  28862. /**
  28863. * @ngdoc directive
  28864. * @name ngSwitch
  28865. * @restrict EA
  28866. *
  28867. * @description
  28868. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  28869. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  28870. * as specified in the template.
  28871. *
  28872. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  28873. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  28874. * matches the value obtained from the evaluated expression. In other words, you define a container element
  28875. * (where you place the directive), place an expression on the **`on="..."` attribute**
  28876. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  28877. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  28878. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  28879. * attribute is displayed.
  28880. *
  28881. * <div class="alert alert-info">
  28882. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  28883. * as literal string values to match against.
  28884. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  28885. * value of the expression `$scope.someVal`.
  28886. * </div>
  28887. * @animations
  28888. * | Animation | Occurs |
  28889. * |----------------------------------|-------------------------------------|
  28890. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  28891. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  28892. *
  28893. * @usage
  28894. *
  28895. * ```
  28896. * <ANY ng-switch="expression">
  28897. * <ANY ng-switch-when="matchValue1">...</ANY>
  28898. * <ANY ng-switch-when="matchValue2">...</ANY>
  28899. * <ANY ng-switch-default>...</ANY>
  28900. * </ANY>
  28901. * ```
  28902. *
  28903. *
  28904. * @scope
  28905. * @priority 1200
  28906. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  28907. * On child elements add:
  28908. *
  28909. * * `ngSwitchWhen`: the case statement to match against. If match then this
  28910. * case will be displayed. If the same match appears multiple times, all the
  28911. * elements will be displayed. It is possible to associate multiple values to
  28912. * the same `ngSwitchWhen` by defining the optional attribute
  28913. * `ngSwitchWhenSeparator`. The separator will be used to split the value of
  28914. * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
  28915. * if any of the `ngSwitch` evaluates to any of these tokens.
  28916. * * `ngSwitchDefault`: the default case when no other case match. If there
  28917. * are multiple default cases, all of them will be displayed when no other
  28918. * case match.
  28919. *
  28920. *
  28921. * @example
  28922. <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
  28923. <file name="index.html">
  28924. <div ng-controller="ExampleController">
  28925. <select ng-model="selection" ng-options="item for item in items">
  28926. </select>
  28927. <code>selection={{selection}}</code>
  28928. <hr/>
  28929. <div class="animate-switch-container"
  28930. ng-switch on="selection">
  28931. <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
  28932. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  28933. <div class="animate-switch" ng-switch-default>default</div>
  28934. </div>
  28935. </div>
  28936. </file>
  28937. <file name="script.js">
  28938. angular.module('switchExample', ['ngAnimate'])
  28939. .controller('ExampleController', ['$scope', function($scope) {
  28940. $scope.items = ['settings', 'home', 'options', 'other'];
  28941. $scope.selection = $scope.items[0];
  28942. }]);
  28943. </file>
  28944. <file name="animations.css">
  28945. .animate-switch-container {
  28946. position:relative;
  28947. background:white;
  28948. border:1px solid black;
  28949. height:40px;
  28950. overflow:hidden;
  28951. }
  28952. .animate-switch {
  28953. padding:10px;
  28954. }
  28955. .animate-switch.ng-animate {
  28956. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  28957. position:absolute;
  28958. top:0;
  28959. left:0;
  28960. right:0;
  28961. bottom:0;
  28962. }
  28963. .animate-switch.ng-leave.ng-leave-active,
  28964. .animate-switch.ng-enter {
  28965. top:-50px;
  28966. }
  28967. .animate-switch.ng-leave,
  28968. .animate-switch.ng-enter.ng-enter-active {
  28969. top:0;
  28970. }
  28971. </file>
  28972. <file name="protractor.js" type="protractor">
  28973. var switchElem = element(by.css('[ng-switch]'));
  28974. var select = element(by.model('selection'));
  28975. it('should start in settings', function() {
  28976. expect(switchElem.getText()).toMatch(/Settings Div/);
  28977. });
  28978. it('should change to home', function() {
  28979. select.all(by.css('option')).get(1).click();
  28980. expect(switchElem.getText()).toMatch(/Home Span/);
  28981. });
  28982. it('should change to settings via "options"', function() {
  28983. select.all(by.css('option')).get(2).click();
  28984. expect(switchElem.getText()).toMatch(/Settings Div/);
  28985. });
  28986. it('should select default', function() {
  28987. select.all(by.css('option')).get(3).click();
  28988. expect(switchElem.getText()).toMatch(/default/);
  28989. });
  28990. </file>
  28991. </example>
  28992. */
  28993. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  28994. return {
  28995. require: 'ngSwitch',
  28996. // asks for $scope to fool the BC controller module
  28997. controller: ['$scope', function NgSwitchController() {
  28998. this.cases = {};
  28999. }],
  29000. link: function(scope, element, attr, ngSwitchController) {
  29001. var watchExpr = attr.ngSwitch || attr.on,
  29002. selectedTranscludes = [],
  29003. selectedElements = [],
  29004. previousLeaveAnimations = [],
  29005. selectedScopes = [];
  29006. var spliceFactory = function(array, index) {
  29007. return function(response) {
  29008. if (response !== false) array.splice(index, 1);
  29009. };
  29010. };
  29011. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  29012. var i, ii;
  29013. // Start with the last, in case the array is modified during the loop
  29014. while (previousLeaveAnimations.length) {
  29015. $animate.cancel(previousLeaveAnimations.pop());
  29016. }
  29017. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  29018. var selected = getBlockNodes(selectedElements[i].clone);
  29019. selectedScopes[i].$destroy();
  29020. var runner = previousLeaveAnimations[i] = $animate.leave(selected);
  29021. runner.done(spliceFactory(previousLeaveAnimations, i));
  29022. }
  29023. selectedElements.length = 0;
  29024. selectedScopes.length = 0;
  29025. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  29026. forEach(selectedTranscludes, function(selectedTransclude) {
  29027. selectedTransclude.transclude(function(caseElement, selectedScope) {
  29028. selectedScopes.push(selectedScope);
  29029. var anchor = selectedTransclude.element;
  29030. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  29031. var block = { clone: caseElement };
  29032. selectedElements.push(block);
  29033. $animate.enter(caseElement, anchor.parent(), anchor);
  29034. });
  29035. });
  29036. }
  29037. });
  29038. }
  29039. };
  29040. }];
  29041. var ngSwitchWhenDirective = ngDirective({
  29042. transclude: 'element',
  29043. priority: 1200,
  29044. require: '^ngSwitch',
  29045. multiElement: true,
  29046. link: function(scope, element, attrs, ctrl, $transclude) {
  29047. var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
  29048. // Filter duplicate cases
  29049. function(element, index, array) { return array[index - 1] !== element; }
  29050. );
  29051. forEach(cases, function(whenCase) {
  29052. ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
  29053. ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
  29054. });
  29055. }
  29056. });
  29057. var ngSwitchDefaultDirective = ngDirective({
  29058. transclude: 'element',
  29059. priority: 1200,
  29060. require: '^ngSwitch',
  29061. multiElement: true,
  29062. link: function(scope, element, attr, ctrl, $transclude) {
  29063. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  29064. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  29065. }
  29066. });
  29067. /**
  29068. * @ngdoc directive
  29069. * @name ngTransclude
  29070. * @restrict EAC
  29071. *
  29072. * @description
  29073. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  29074. *
  29075. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  29076. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  29077. *
  29078. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  29079. * content of this element will be removed before the transcluded content is inserted.
  29080. * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback
  29081. * content in the case that no transcluded content is provided.
  29082. *
  29083. * @element ANY
  29084. *
  29085. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  29086. * or its value is the same as the name of the attribute then the default slot is used.
  29087. *
  29088. * @example
  29089. * ### Basic transclusion
  29090. * This example demonstrates basic transclusion of content into a component directive.
  29091. * <example name="simpleTranscludeExample" module="transcludeExample">
  29092. * <file name="index.html">
  29093. * <script>
  29094. * angular.module('transcludeExample', [])
  29095. * .directive('pane', function(){
  29096. * return {
  29097. * restrict: 'E',
  29098. * transclude: true,
  29099. * scope: { title:'@' },
  29100. * template: '<div style="border: 1px solid black;">' +
  29101. * '<div style="background-color: gray">{{title}}</div>' +
  29102. * '<ng-transclude></ng-transclude>' +
  29103. * '</div>'
  29104. * };
  29105. * })
  29106. * .controller('ExampleController', ['$scope', function($scope) {
  29107. * $scope.title = 'Lorem Ipsum';
  29108. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29109. * }]);
  29110. * </script>
  29111. * <div ng-controller="ExampleController">
  29112. * <input ng-model="title" aria-label="title"> <br/>
  29113. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  29114. * <pane title="{{title}}"><span>{{text}}</span></pane>
  29115. * </div>
  29116. * </file>
  29117. * <file name="protractor.js" type="protractor">
  29118. * it('should have transcluded', function() {
  29119. * var titleElement = element(by.model('title'));
  29120. * titleElement.clear();
  29121. * titleElement.sendKeys('TITLE');
  29122. * var textElement = element(by.model('text'));
  29123. * textElement.clear();
  29124. * textElement.sendKeys('TEXT');
  29125. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  29126. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29127. * });
  29128. * </file>
  29129. * </example>
  29130. *
  29131. * @example
  29132. * ### Transclude fallback content
  29133. * This example shows how to use `NgTransclude` with fallback content, that
  29134. * is displayed if no transcluded content is provided.
  29135. *
  29136. * <example module="transcludeFallbackContentExample" name="ng-transclude">
  29137. * <file name="index.html">
  29138. * <script>
  29139. * angular.module('transcludeFallbackContentExample', [])
  29140. * .directive('myButton', function(){
  29141. * return {
  29142. * restrict: 'E',
  29143. * transclude: true,
  29144. * scope: true,
  29145. * template: '<button style="cursor: pointer;">' +
  29146. * '<ng-transclude>' +
  29147. * '<b style="color: red;">Button1</b>' +
  29148. * '</ng-transclude>' +
  29149. * '</button>'
  29150. * };
  29151. * });
  29152. * </script>
  29153. * <!-- fallback button content -->
  29154. * <my-button id="fallback"></my-button>
  29155. * <!-- modified button content -->
  29156. * <my-button id="modified">
  29157. * <i style="color: green;">Button2</i>
  29158. * </my-button>
  29159. * </file>
  29160. * <file name="protractor.js" type="protractor">
  29161. * it('should have different transclude element content', function() {
  29162. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  29163. * expect(element(by.id('modified')).getText()).toBe('Button2');
  29164. * });
  29165. * </file>
  29166. * </example>
  29167. *
  29168. * @example
  29169. * ### Multi-slot transclusion
  29170. * This example demonstrates using multi-slot transclusion in a component directive.
  29171. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  29172. * <file name="index.html">
  29173. * <style>
  29174. * .title, .footer {
  29175. * background-color: gray
  29176. * }
  29177. * </style>
  29178. * <div ng-controller="ExampleController">
  29179. * <input ng-model="title" aria-label="title"> <br/>
  29180. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  29181. * <pane>
  29182. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  29183. * <pane-body><p>{{text}}</p></pane-body>
  29184. * </pane>
  29185. * </div>
  29186. * </file>
  29187. * <file name="app.js">
  29188. * angular.module('multiSlotTranscludeExample', [])
  29189. * .directive('pane', function() {
  29190. * return {
  29191. * restrict: 'E',
  29192. * transclude: {
  29193. * 'title': '?paneTitle',
  29194. * 'body': 'paneBody',
  29195. * 'footer': '?paneFooter'
  29196. * },
  29197. * template: '<div style="border: 1px solid black;">' +
  29198. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  29199. * '<div ng-transclude="body"></div>' +
  29200. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  29201. * '</div>'
  29202. * };
  29203. * })
  29204. * .controller('ExampleController', ['$scope', function($scope) {
  29205. * $scope.title = 'Lorem Ipsum';
  29206. * $scope.link = 'https://google.com';
  29207. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29208. * }]);
  29209. * </file>
  29210. * <file name="protractor.js" type="protractor">
  29211. * it('should have transcluded the title and the body', function() {
  29212. * var titleElement = element(by.model('title'));
  29213. * titleElement.clear();
  29214. * titleElement.sendKeys('TITLE');
  29215. * var textElement = element(by.model('text'));
  29216. * textElement.clear();
  29217. * textElement.sendKeys('TEXT');
  29218. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  29219. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29220. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  29221. * });
  29222. * </file>
  29223. * </example>
  29224. */
  29225. var ngTranscludeMinErr = minErr('ngTransclude');
  29226. var ngTranscludeDirective = ['$compile', function($compile) {
  29227. return {
  29228. restrict: 'EAC',
  29229. terminal: true,
  29230. compile: function ngTranscludeCompile(tElement) {
  29231. // Remove and cache any original content to act as a fallback
  29232. var fallbackLinkFn = $compile(tElement.contents());
  29233. tElement.empty();
  29234. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  29235. if (!$transclude) {
  29236. throw ngTranscludeMinErr('orphan',
  29237. 'Illegal use of ngTransclude directive in the template! ' +
  29238. 'No parent directive that requires a transclusion found. ' +
  29239. 'Element: {0}',
  29240. startingTag($element));
  29241. }
  29242. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  29243. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  29244. $attrs.ngTransclude = '';
  29245. }
  29246. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  29247. // If the slot is required and no transclusion content is provided then this call will throw an error
  29248. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  29249. // If the slot is optional and no transclusion content is provided then use the fallback content
  29250. if (slotName && !$transclude.isSlotFilled(slotName)) {
  29251. useFallbackContent();
  29252. }
  29253. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  29254. if (clone.length && notWhitespace(clone)) {
  29255. $element.append(clone);
  29256. } else {
  29257. useFallbackContent();
  29258. // There is nothing linked against the transcluded scope since no content was available,
  29259. // so it should be safe to clean up the generated scope.
  29260. transcludedScope.$destroy();
  29261. }
  29262. }
  29263. function useFallbackContent() {
  29264. // Since this is the fallback content rather than the transcluded content,
  29265. // we link against the scope of this directive rather than the transcluded scope
  29266. fallbackLinkFn($scope, function(clone) {
  29267. $element.append(clone);
  29268. });
  29269. }
  29270. function notWhitespace(nodes) {
  29271. for (var i = 0, ii = nodes.length; i < ii; i++) {
  29272. var node = nodes[i];
  29273. if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {
  29274. return true;
  29275. }
  29276. }
  29277. }
  29278. };
  29279. }
  29280. };
  29281. }];
  29282. /**
  29283. * @ngdoc directive
  29284. * @name script
  29285. * @restrict E
  29286. *
  29287. * @description
  29288. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  29289. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  29290. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  29291. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  29292. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  29293. *
  29294. * @param {string} type Must be set to `'text/ng-template'`.
  29295. * @param {string} id Cache name of the template.
  29296. *
  29297. * @example
  29298. <example name="script-tag">
  29299. <file name="index.html">
  29300. <script type="text/ng-template" id="/tpl.html">
  29301. Content of the template.
  29302. </script>
  29303. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  29304. <div id="tpl-content" ng-include src="currentTpl"></div>
  29305. </file>
  29306. <file name="protractor.js" type="protractor">
  29307. it('should load template defined inside script tag', function() {
  29308. element(by.css('#tpl-link')).click();
  29309. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  29310. });
  29311. </file>
  29312. </example>
  29313. */
  29314. var scriptDirective = ['$templateCache', function($templateCache) {
  29315. return {
  29316. restrict: 'E',
  29317. terminal: true,
  29318. compile: function(element, attr) {
  29319. if (attr.type === 'text/ng-template') {
  29320. var templateUrl = attr.id,
  29321. text = element[0].text;
  29322. $templateCache.put(templateUrl, text);
  29323. }
  29324. }
  29325. };
  29326. }];
  29327. /* exported selectDirective, optionDirective */
  29328. var noopNgModelController = { $setViewValue: noop, $render: noop };
  29329. function setOptionSelectedStatus(optionEl, value) {
  29330. optionEl.prop('selected', value); // needed for IE
  29331. /**
  29332. * When unselecting an option, setting the property to null / false should be enough
  29333. * However, screenreaders might react to the selected attribute instead, see
  29334. * https://github.com/angular/angular.js/issues/14419
  29335. * Note: "selected" is a boolean attr and will be removed when the "value" arg in attr() is false
  29336. * or null
  29337. */
  29338. optionEl.attr('selected', value);
  29339. }
  29340. /**
  29341. * @ngdoc type
  29342. * @name select.SelectController
  29343. * @description
  29344. * The controller for the `<select>` directive. This provides support for reading
  29345. * and writing the selected value(s) of the control and also coordinates dynamically
  29346. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  29347. */
  29348. var SelectController =
  29349. ['$element', '$scope', /** @this */ function($element, $scope) {
  29350. var self = this,
  29351. optionsMap = new NgMap();
  29352. self.selectValueMap = {}; // Keys are the hashed values, values the original values
  29353. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  29354. self.ngModelCtrl = noopNgModelController;
  29355. self.multiple = false;
  29356. // The "unknown" option is one that is prepended to the list if the viewValue
  29357. // does not match any of the options. When it is rendered the value of the unknown
  29358. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  29359. //
  29360. // We can't just jqLite('<option>') since jqLite is not smart enough
  29361. // to create it in <select> and IE barfs otherwise.
  29362. self.unknownOption = jqLite(window.document.createElement('option'));
  29363. // The empty option is an option with the value '' that te application developer can
  29364. // provide inside the select. When the model changes to a value that doesn't match an option,
  29365. // it is selected - so if an empty option is provided, no unknown option is generated.
  29366. // However, the empty option is not removed when the model matches an option. It is always selectable
  29367. // and indicates that a "null" selection has been made.
  29368. self.hasEmptyOption = false;
  29369. self.emptyOption = undefined;
  29370. self.renderUnknownOption = function(val) {
  29371. var unknownVal = self.generateUnknownOptionValue(val);
  29372. self.unknownOption.val(unknownVal);
  29373. $element.prepend(self.unknownOption);
  29374. setOptionSelectedStatus(self.unknownOption, true);
  29375. $element.val(unknownVal);
  29376. };
  29377. self.updateUnknownOption = function(val) {
  29378. var unknownVal = self.generateUnknownOptionValue(val);
  29379. self.unknownOption.val(unknownVal);
  29380. setOptionSelectedStatus(self.unknownOption, true);
  29381. $element.val(unknownVal);
  29382. };
  29383. self.generateUnknownOptionValue = function(val) {
  29384. return '? ' + hashKey(val) + ' ?';
  29385. };
  29386. self.removeUnknownOption = function() {
  29387. if (self.unknownOption.parent()) self.unknownOption.remove();
  29388. };
  29389. self.selectEmptyOption = function() {
  29390. if (self.emptyOption) {
  29391. $element.val('');
  29392. setOptionSelectedStatus(self.emptyOption, true);
  29393. }
  29394. };
  29395. self.unselectEmptyOption = function() {
  29396. if (self.hasEmptyOption) {
  29397. self.emptyOption.removeAttr('selected');
  29398. }
  29399. };
  29400. $scope.$on('$destroy', function() {
  29401. // disable unknown option so that we don't do work when the whole select is being destroyed
  29402. self.renderUnknownOption = noop;
  29403. });
  29404. // Read the value of the select control, the implementation of this changes depending
  29405. // upon whether the select can have multiple values and whether ngOptions is at work.
  29406. self.readValue = function readSingleValue() {
  29407. var val = $element.val();
  29408. // ngValue added option values are stored in the selectValueMap, normal interpolations are not
  29409. var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
  29410. if (self.hasOption(realVal)) {
  29411. return realVal;
  29412. }
  29413. return null;
  29414. };
  29415. // Write the value to the select control, the implementation of this changes depending
  29416. // upon whether the select can have multiple values and whether ngOptions is at work.
  29417. self.writeValue = function writeSingleValue(value) {
  29418. // Make sure to remove the selected attribute from the previously selected option
  29419. // Otherwise, screen readers might get confused
  29420. var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
  29421. if (currentlySelectedOption) setOptionSelectedStatus(jqLite(currentlySelectedOption), false);
  29422. if (self.hasOption(value)) {
  29423. self.removeUnknownOption();
  29424. var hashedVal = hashKey(value);
  29425. $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
  29426. // Set selected attribute and property on selected option for screen readers
  29427. var selectedOption = $element[0].options[$element[0].selectedIndex];
  29428. setOptionSelectedStatus(jqLite(selectedOption), true);
  29429. } else {
  29430. if (value == null && self.emptyOption) {
  29431. self.removeUnknownOption();
  29432. self.selectEmptyOption();
  29433. } else if (self.unknownOption.parent().length) {
  29434. self.updateUnknownOption(value);
  29435. } else {
  29436. self.renderUnknownOption(value);
  29437. }
  29438. }
  29439. };
  29440. // Tell the select control that an option, with the given value, has been added
  29441. self.addOption = function(value, element) {
  29442. // Skip comment nodes, as they only pollute the `optionsMap`
  29443. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  29444. assertNotHasOwnProperty(value, '"option value"');
  29445. if (value === '') {
  29446. self.hasEmptyOption = true;
  29447. self.emptyOption = element;
  29448. }
  29449. var count = optionsMap.get(value) || 0;
  29450. optionsMap.set(value, count + 1);
  29451. // Only render at the end of a digest. This improves render performance when many options
  29452. // are added during a digest and ensures all relevant options are correctly marked as selected
  29453. scheduleRender();
  29454. };
  29455. // Tell the select control that an option, with the given value, has been removed
  29456. self.removeOption = function(value) {
  29457. var count = optionsMap.get(value);
  29458. if (count) {
  29459. if (count === 1) {
  29460. optionsMap.delete(value);
  29461. if (value === '') {
  29462. self.hasEmptyOption = false;
  29463. self.emptyOption = undefined;
  29464. }
  29465. } else {
  29466. optionsMap.set(value, count - 1);
  29467. }
  29468. }
  29469. };
  29470. // Check whether the select control has an option matching the given value
  29471. self.hasOption = function(value) {
  29472. return !!optionsMap.get(value);
  29473. };
  29474. var renderScheduled = false;
  29475. function scheduleRender() {
  29476. if (renderScheduled) return;
  29477. renderScheduled = true;
  29478. $scope.$$postDigest(function() {
  29479. renderScheduled = false;
  29480. self.ngModelCtrl.$render();
  29481. });
  29482. }
  29483. var updateScheduled = false;
  29484. function scheduleViewValueUpdate(renderAfter) {
  29485. if (updateScheduled) return;
  29486. updateScheduled = true;
  29487. $scope.$$postDigest(function() {
  29488. if ($scope.$$destroyed) return;
  29489. updateScheduled = false;
  29490. self.ngModelCtrl.$setViewValue(self.readValue());
  29491. if (renderAfter) self.ngModelCtrl.$render();
  29492. });
  29493. }
  29494. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  29495. if (optionAttrs.$attr.ngValue) {
  29496. // The value attribute is set by ngValue
  29497. var oldVal, hashedVal = NaN;
  29498. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29499. var removal;
  29500. var previouslySelected = optionElement.prop('selected');
  29501. if (isDefined(hashedVal)) {
  29502. self.removeOption(oldVal);
  29503. delete self.selectValueMap[hashedVal];
  29504. removal = true;
  29505. }
  29506. hashedVal = hashKey(newVal);
  29507. oldVal = newVal;
  29508. self.selectValueMap[hashedVal] = newVal;
  29509. self.addOption(newVal, optionElement);
  29510. // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
  29511. // from firing a second time. Other $observers on value will also get the result of the
  29512. // ngValue expression, not the hashed value
  29513. optionElement.attr('value', hashedVal);
  29514. if (removal && previouslySelected) {
  29515. scheduleViewValueUpdate();
  29516. }
  29517. });
  29518. } else if (interpolateValueFn) {
  29519. // The value attribute is interpolated
  29520. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29521. // This method is overwritten in ngOptions and has side-effects!
  29522. self.readValue();
  29523. var removal;
  29524. var previouslySelected = optionElement.prop('selected');
  29525. if (isDefined(oldVal)) {
  29526. self.removeOption(oldVal);
  29527. removal = true;
  29528. }
  29529. oldVal = newVal;
  29530. self.addOption(newVal, optionElement);
  29531. if (removal && previouslySelected) {
  29532. scheduleViewValueUpdate();
  29533. }
  29534. });
  29535. } else if (interpolateTextFn) {
  29536. // The text content is interpolated
  29537. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  29538. optionAttrs.$set('value', newVal);
  29539. var previouslySelected = optionElement.prop('selected');
  29540. if (oldVal !== newVal) {
  29541. self.removeOption(oldVal);
  29542. }
  29543. self.addOption(newVal, optionElement);
  29544. if (oldVal && previouslySelected) {
  29545. scheduleViewValueUpdate();
  29546. }
  29547. });
  29548. } else {
  29549. // The value attribute is static
  29550. self.addOption(optionAttrs.value, optionElement);
  29551. }
  29552. optionAttrs.$observe('disabled', function(newVal) {
  29553. // Since model updates will also select disabled options (like ngOptions),
  29554. // we only have to handle options becoming disabled, not enabled
  29555. if (newVal === 'true' || newVal && optionElement.prop('selected')) {
  29556. if (self.multiple) {
  29557. scheduleViewValueUpdate(true);
  29558. } else {
  29559. self.ngModelCtrl.$setViewValue(null);
  29560. self.ngModelCtrl.$render();
  29561. }
  29562. }
  29563. });
  29564. optionElement.on('$destroy', function() {
  29565. var currentValue = self.readValue();
  29566. var removeValue = optionAttrs.value;
  29567. self.removeOption(removeValue);
  29568. scheduleRender();
  29569. if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
  29570. currentValue === removeValue
  29571. ) {
  29572. // When multiple (selected) options are destroyed at the same time, we don't want
  29573. // to run a model update for each of them. Instead, run a single update in the $$postDigest
  29574. scheduleViewValueUpdate(true);
  29575. }
  29576. });
  29577. };
  29578. }];
  29579. /**
  29580. * @ngdoc directive
  29581. * @name select
  29582. * @restrict E
  29583. *
  29584. * @description
  29585. * HTML `select` element with angular data-binding.
  29586. *
  29587. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  29588. * between the scope and the `<select>` control (including setting default values).
  29589. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  29590. * {@link ngOptions `ngOptions`} directives.
  29591. *
  29592. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  29593. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  29594. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  29595. * Value and textContent can be interpolated.
  29596. *
  29597. * ## Matching model and option values
  29598. *
  29599. * In general, the match between the model and an option is evaluated by strictly comparing the model
  29600. * value against the value of the available options.
  29601. *
  29602. * If you are setting the option value with the option's `value` attribute, or textContent, the
  29603. * value will always be a `string` which means that the model value must also be a string.
  29604. * Otherwise the `select` directive cannot match them correctly.
  29605. *
  29606. * To bind the model to a non-string value, you can use one of the following strategies:
  29607. * - the {@link ng.ngOptions `ngOptions`} directive
  29608. * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
  29609. * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
  29610. * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
  29611. * - model $parsers / $formatters to convert the string value
  29612. * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
  29613. *
  29614. * If the viewValue of `ngModel` does not match any of the options, then the control
  29615. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  29616. *
  29617. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  29618. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  29619. * option. See example below for demonstration.
  29620. *
  29621. * ## Choosing between `ngRepeat` and `ngOptions`
  29622. *
  29623. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  29624. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
  29625. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  29626. * comprehension expression
  29627. * - reduced memory consumption by not creating a new scope for each repeated instance
  29628. * - increased render speed by creating the options in a documentFragment instead of individually
  29629. *
  29630. * Specifically, select with repeated options slows down significantly starting at 2000 options in
  29631. * Chrome and Internet Explorer / Edge.
  29632. *
  29633. *
  29634. * @param {string} ngModel Assignable angular expression to data-bind to.
  29635. * @param {string=} name Property name of the form under which the control is published.
  29636. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  29637. * bound to the model as an array.
  29638. * @param {string=} required Sets `required` validation error key if the value is not entered.
  29639. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  29640. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  29641. * when you want to data-bind to the required attribute.
  29642. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  29643. * interaction with the select element.
  29644. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  29645. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  29646. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  29647. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  29648. *
  29649. * @example
  29650. * ### Simple `select` elements with static options
  29651. *
  29652. * <example name="static-select" module="staticSelect">
  29653. * <file name="index.html">
  29654. * <div ng-controller="ExampleController">
  29655. * <form name="myForm">
  29656. * <label for="singleSelect"> Single select: </label><br>
  29657. * <select name="singleSelect" ng-model="data.singleSelect">
  29658. * <option value="option-1">Option 1</option>
  29659. * <option value="option-2">Option 2</option>
  29660. * </select><br>
  29661. *
  29662. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  29663. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  29664. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  29665. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  29666. * <option value="option-2">Option 2</option>
  29667. * </select><br>
  29668. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  29669. * <tt>singleSelect = {{data.singleSelect}}</tt>
  29670. *
  29671. * <hr>
  29672. * <label for="multipleSelect"> Multiple select: </label><br>
  29673. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  29674. * <option value="option-1">Option 1</option>
  29675. * <option value="option-2">Option 2</option>
  29676. * <option value="option-3">Option 3</option>
  29677. * </select><br>
  29678. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  29679. * </form>
  29680. * </div>
  29681. * </file>
  29682. * <file name="app.js">
  29683. * angular.module('staticSelect', [])
  29684. * .controller('ExampleController', ['$scope', function($scope) {
  29685. * $scope.data = {
  29686. * singleSelect: null,
  29687. * multipleSelect: [],
  29688. * option1: 'option-1'
  29689. * };
  29690. *
  29691. * $scope.forceUnknownOption = function() {
  29692. * $scope.data.singleSelect = 'nonsense';
  29693. * };
  29694. * }]);
  29695. * </file>
  29696. *</example>
  29697. *
  29698. * ### Using `ngRepeat` to generate `select` options
  29699. * <example name="select-ngrepeat" module="ngrepeatSelect">
  29700. * <file name="index.html">
  29701. * <div ng-controller="ExampleController">
  29702. * <form name="myForm">
  29703. * <label for="repeatSelect"> Repeat select: </label>
  29704. * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  29705. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  29706. * </select>
  29707. * </form>
  29708. * <hr>
  29709. * <tt>model = {{data.model}}</tt><br/>
  29710. * </div>
  29711. * </file>
  29712. * <file name="app.js">
  29713. * angular.module('ngrepeatSelect', [])
  29714. * .controller('ExampleController', ['$scope', function($scope) {
  29715. * $scope.data = {
  29716. * model: null,
  29717. * availableOptions: [
  29718. * {id: '1', name: 'Option A'},
  29719. * {id: '2', name: 'Option B'},
  29720. * {id: '3', name: 'Option C'}
  29721. * ]
  29722. * };
  29723. * }]);
  29724. * </file>
  29725. *</example>
  29726. *
  29727. * ### Using `ngValue` to bind the model to an array of objects
  29728. * <example name="select-ngvalue" module="ngvalueSelect">
  29729. * <file name="index.html">
  29730. * <div ng-controller="ExampleController">
  29731. * <form name="myForm">
  29732. * <label for="ngvalueselect"> ngvalue select: </label>
  29733. * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
  29734. * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
  29735. * </select>
  29736. * </form>
  29737. * <hr>
  29738. * <pre>model = {{data.model | json}}</pre><br/>
  29739. * </div>
  29740. * </file>
  29741. * <file name="app.js">
  29742. * angular.module('ngvalueSelect', [])
  29743. * .controller('ExampleController', ['$scope', function($scope) {
  29744. * $scope.data = {
  29745. * model: null,
  29746. * availableOptions: [
  29747. {value: 'myString', name: 'string'},
  29748. {value: 1, name: 'integer'},
  29749. {value: true, name: 'boolean'},
  29750. {value: null, name: 'null'},
  29751. {value: {prop: 'value'}, name: 'object'},
  29752. {value: ['a'], name: 'array'}
  29753. * ]
  29754. * };
  29755. * }]);
  29756. * </file>
  29757. *</example>
  29758. *
  29759. * ### Using `select` with `ngOptions` and setting a default value
  29760. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  29761. *
  29762. * <example name="select-with-default-values" module="defaultValueSelect">
  29763. * <file name="index.html">
  29764. * <div ng-controller="ExampleController">
  29765. * <form name="myForm">
  29766. * <label for="mySelect">Make a choice:</label>
  29767. * <select name="mySelect" id="mySelect"
  29768. * ng-options="option.name for option in data.availableOptions track by option.id"
  29769. * ng-model="data.selectedOption"></select>
  29770. * </form>
  29771. * <hr>
  29772. * <tt>option = {{data.selectedOption}}</tt><br/>
  29773. * </div>
  29774. * </file>
  29775. * <file name="app.js">
  29776. * angular.module('defaultValueSelect', [])
  29777. * .controller('ExampleController', ['$scope', function($scope) {
  29778. * $scope.data = {
  29779. * availableOptions: [
  29780. * {id: '1', name: 'Option A'},
  29781. * {id: '2', name: 'Option B'},
  29782. * {id: '3', name: 'Option C'}
  29783. * ],
  29784. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  29785. * };
  29786. * }]);
  29787. * </file>
  29788. *</example>
  29789. *
  29790. *
  29791. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  29792. *
  29793. * <example name="select-with-non-string-options" module="nonStringSelect">
  29794. * <file name="index.html">
  29795. * <select ng-model="model.id" convert-to-number>
  29796. * <option value="0">Zero</option>
  29797. * <option value="1">One</option>
  29798. * <option value="2">Two</option>
  29799. * </select>
  29800. * {{ model }}
  29801. * </file>
  29802. * <file name="app.js">
  29803. * angular.module('nonStringSelect', [])
  29804. * .run(function($rootScope) {
  29805. * $rootScope.model = { id: 2 };
  29806. * })
  29807. * .directive('convertToNumber', function() {
  29808. * return {
  29809. * require: 'ngModel',
  29810. * link: function(scope, element, attrs, ngModel) {
  29811. * ngModel.$parsers.push(function(val) {
  29812. * return parseInt(val, 10);
  29813. * });
  29814. * ngModel.$formatters.push(function(val) {
  29815. * return '' + val;
  29816. * });
  29817. * }
  29818. * };
  29819. * });
  29820. * </file>
  29821. * <file name="protractor.js" type="protractor">
  29822. * it('should initialize to model', function() {
  29823. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  29824. * });
  29825. * </file>
  29826. * </example>
  29827. *
  29828. */
  29829. var selectDirective = function() {
  29830. return {
  29831. restrict: 'E',
  29832. require: ['select', '?ngModel'],
  29833. controller: SelectController,
  29834. priority: 1,
  29835. link: {
  29836. pre: selectPreLink,
  29837. post: selectPostLink
  29838. }
  29839. };
  29840. function selectPreLink(scope, element, attr, ctrls) {
  29841. var selectCtrl = ctrls[0];
  29842. var ngModelCtrl = ctrls[1];
  29843. // if ngModel is not defined, we don't need to do anything but set the registerOption
  29844. // function to noop, so options don't get added internally
  29845. if (!ngModelCtrl) {
  29846. selectCtrl.registerOption = noop;
  29847. return;
  29848. }
  29849. selectCtrl.ngModelCtrl = ngModelCtrl;
  29850. // When the selected item(s) changes we delegate getting the value of the select control
  29851. // to the `readValue` method, which can be changed if the select can have multiple
  29852. // selected values or if the options are being generated by `ngOptions`
  29853. element.on('change', function() {
  29854. selectCtrl.removeUnknownOption();
  29855. scope.$apply(function() {
  29856. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  29857. });
  29858. });
  29859. // If the select allows multiple values then we need to modify how we read and write
  29860. // values from and to the control; also what it means for the value to be empty and
  29861. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  29862. // doesn't trigger rendering if only an item in the array changes.
  29863. if (attr.multiple) {
  29864. selectCtrl.multiple = true;
  29865. // Read value now needs to check each option to see if it is selected
  29866. selectCtrl.readValue = function readMultipleValue() {
  29867. var array = [];
  29868. forEach(element.find('option'), function(option) {
  29869. if (option.selected && !option.disabled) {
  29870. var val = option.value;
  29871. array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
  29872. }
  29873. });
  29874. return array;
  29875. };
  29876. // Write value now needs to set the selected property of each matching option
  29877. selectCtrl.writeValue = function writeMultipleValue(value) {
  29878. forEach(element.find('option'), function(option) {
  29879. var shouldBeSelected = !!value && (includes(value, option.value) ||
  29880. includes(value, selectCtrl.selectValueMap[option.value]));
  29881. var currentlySelected = option.selected;
  29882. // IE and Edge, adding options to the selection via shift+click/UP/DOWN,
  29883. // will de-select already selected options if "selected" on those options was set
  29884. // more than once (i.e. when the options were already selected)
  29885. // So we only modify the selected property if neccessary.
  29886. // Note: this behavior cannot be replicated via unit tests because it only shows in the
  29887. // actual user interface.
  29888. if (shouldBeSelected !== currentlySelected) {
  29889. setOptionSelectedStatus(jqLite(option), shouldBeSelected);
  29890. }
  29891. });
  29892. };
  29893. // we have to do it on each watch since ngModel watches reference, but
  29894. // we need to work of an array, so we need to see if anything was inserted/removed
  29895. var lastView, lastViewRef = NaN;
  29896. scope.$watch(function selectMultipleWatch() {
  29897. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  29898. lastView = shallowCopy(ngModelCtrl.$viewValue);
  29899. ngModelCtrl.$render();
  29900. }
  29901. lastViewRef = ngModelCtrl.$viewValue;
  29902. });
  29903. // If we are a multiple select then value is now a collection
  29904. // so the meaning of $isEmpty changes
  29905. ngModelCtrl.$isEmpty = function(value) {
  29906. return !value || value.length === 0;
  29907. };
  29908. }
  29909. }
  29910. function selectPostLink(scope, element, attrs, ctrls) {
  29911. // if ngModel is not defined, we don't need to do anything
  29912. var ngModelCtrl = ctrls[1];
  29913. if (!ngModelCtrl) return;
  29914. var selectCtrl = ctrls[0];
  29915. // We delegate rendering to the `writeValue` method, which can be changed
  29916. // if the select can have multiple selected values or if the options are being
  29917. // generated by `ngOptions`.
  29918. // This must be done in the postLink fn to prevent $render to be called before
  29919. // all nodes have been linked correctly.
  29920. ngModelCtrl.$render = function() {
  29921. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  29922. };
  29923. }
  29924. };
  29925. // The option directive is purely designed to communicate the existence (or lack of)
  29926. // of dynamically created (and destroyed) option elements to their containing select
  29927. // directive via its controller.
  29928. var optionDirective = ['$interpolate', function($interpolate) {
  29929. return {
  29930. restrict: 'E',
  29931. priority: 100,
  29932. compile: function(element, attr) {
  29933. var interpolateValueFn, interpolateTextFn;
  29934. if (isDefined(attr.ngValue)) {
  29935. // Will be handled by registerOption
  29936. } else if (isDefined(attr.value)) {
  29937. // If the value attribute is defined, check if it contains an interpolation
  29938. interpolateValueFn = $interpolate(attr.value, true);
  29939. } else {
  29940. // If the value attribute is not defined then we fall back to the
  29941. // text content of the option element, which may be interpolated
  29942. interpolateTextFn = $interpolate(element.text(), true);
  29943. if (!interpolateTextFn) {
  29944. attr.$set('value', element.text());
  29945. }
  29946. }
  29947. return function(scope, element, attr) {
  29948. // This is an optimization over using ^^ since we don't want to have to search
  29949. // all the way to the root of the DOM for every single option element
  29950. var selectCtrlName = '$selectController',
  29951. parent = element.parent(),
  29952. selectCtrl = parent.data(selectCtrlName) ||
  29953. parent.parent().data(selectCtrlName); // in case we are in optgroup
  29954. if (selectCtrl) {
  29955. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  29956. }
  29957. };
  29958. }
  29959. };
  29960. }];
  29961. /**
  29962. * @ngdoc directive
  29963. * @name ngRequired
  29964. * @restrict A
  29965. *
  29966. * @description
  29967. *
  29968. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29969. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  29970. * applied to custom controls.
  29971. *
  29972. * The directive sets the `required` attribute on the element if the Angular expression inside
  29973. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  29974. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  29975. * for more info.
  29976. *
  29977. * The validator will set the `required` error key to true if the `required` attribute is set and
  29978. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  29979. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  29980. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  29981. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  29982. *
  29983. * @example
  29984. * <example name="ngRequiredDirective" module="ngRequiredExample">
  29985. * <file name="index.html">
  29986. * <script>
  29987. * angular.module('ngRequiredExample', [])
  29988. * .controller('ExampleController', ['$scope', function($scope) {
  29989. * $scope.required = true;
  29990. * }]);
  29991. * </script>
  29992. * <div ng-controller="ExampleController">
  29993. * <form name="form">
  29994. * <label for="required">Toggle required: </label>
  29995. * <input type="checkbox" ng-model="required" id="required" />
  29996. * <br>
  29997. * <label for="input">This input must be filled if `required` is true: </label>
  29998. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  29999. * <hr>
  30000. * required error set? = <code>{{form.input.$error.required}}</code><br>
  30001. * model = <code>{{model}}</code>
  30002. * </form>
  30003. * </div>
  30004. * </file>
  30005. * <file name="protractor.js" type="protractor">
  30006. var required = element(by.binding('form.input.$error.required'));
  30007. var model = element(by.binding('model'));
  30008. var input = element(by.id('input'));
  30009. it('should set the required error', function() {
  30010. expect(required.getText()).toContain('true');
  30011. input.sendKeys('123');
  30012. expect(required.getText()).not.toContain('true');
  30013. expect(model.getText()).toContain('123');
  30014. });
  30015. * </file>
  30016. * </example>
  30017. */
  30018. var requiredDirective = function() {
  30019. return {
  30020. restrict: 'A',
  30021. require: '?ngModel',
  30022. link: function(scope, elm, attr, ctrl) {
  30023. if (!ctrl) return;
  30024. attr.required = true; // force truthy in case we are on non input element
  30025. ctrl.$validators.required = function(modelValue, viewValue) {
  30026. return !attr.required || !ctrl.$isEmpty(viewValue);
  30027. };
  30028. attr.$observe('required', function() {
  30029. ctrl.$validate();
  30030. });
  30031. }
  30032. };
  30033. };
  30034. /**
  30035. * @ngdoc directive
  30036. * @name ngPattern
  30037. *
  30038. * @description
  30039. *
  30040. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30041. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30042. *
  30043. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30044. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  30045. * `ngPattern` attribute value:
  30046. * * If the expression evaluates to a RegExp object, then this is used directly.
  30047. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  30048. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  30049. *
  30050. * <div class="alert alert-info">
  30051. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  30052. * start at the index of the last search's match, thus not taking the whole input value into
  30053. * account.
  30054. * </div>
  30055. *
  30056. * <div class="alert alert-info">
  30057. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  30058. * differences:
  30059. * <ol>
  30060. * <li>
  30061. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  30062. * not available.
  30063. * </li>
  30064. * <li>
  30065. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  30066. * interpolated.
  30067. * </li>
  30068. * </ol>
  30069. * </div>
  30070. *
  30071. * @example
  30072. * <example name="ngPatternDirective" module="ngPatternExample">
  30073. * <file name="index.html">
  30074. * <script>
  30075. * angular.module('ngPatternExample', [])
  30076. * .controller('ExampleController', ['$scope', function($scope) {
  30077. * $scope.regex = '\\d+';
  30078. * }]);
  30079. * </script>
  30080. * <div ng-controller="ExampleController">
  30081. * <form name="form">
  30082. * <label for="regex">Set a pattern (regex string): </label>
  30083. * <input type="text" ng-model="regex" id="regex" />
  30084. * <br>
  30085. * <label for="input">This input is restricted by the current pattern: </label>
  30086. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  30087. * <hr>
  30088. * input valid? = <code>{{form.input.$valid}}</code><br>
  30089. * model = <code>{{model}}</code>
  30090. * </form>
  30091. * </div>
  30092. * </file>
  30093. * <file name="protractor.js" type="protractor">
  30094. var model = element(by.binding('model'));
  30095. var input = element(by.id('input'));
  30096. it('should validate the input with the default pattern', function() {
  30097. input.sendKeys('aaa');
  30098. expect(model.getText()).not.toContain('aaa');
  30099. input.clear().then(function() {
  30100. input.sendKeys('123');
  30101. expect(model.getText()).toContain('123');
  30102. });
  30103. });
  30104. * </file>
  30105. * </example>
  30106. */
  30107. var patternDirective = function() {
  30108. return {
  30109. restrict: 'A',
  30110. require: '?ngModel',
  30111. link: function(scope, elm, attr, ctrl) {
  30112. if (!ctrl) return;
  30113. var regexp, patternExp = attr.ngPattern || attr.pattern;
  30114. attr.$observe('pattern', function(regex) {
  30115. if (isString(regex) && regex.length > 0) {
  30116. regex = new RegExp('^' + regex + '$');
  30117. }
  30118. if (regex && !regex.test) {
  30119. throw minErr('ngPattern')('noregexp',
  30120. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  30121. regex, startingTag(elm));
  30122. }
  30123. regexp = regex || undefined;
  30124. ctrl.$validate();
  30125. });
  30126. ctrl.$validators.pattern = function(modelValue, viewValue) {
  30127. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  30128. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  30129. };
  30130. }
  30131. };
  30132. };
  30133. /**
  30134. * @ngdoc directive
  30135. * @name ngMaxlength
  30136. *
  30137. * @description
  30138. *
  30139. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30140. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30141. *
  30142. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30143. * is longer than the integer obtained by evaluating the Angular expression given in the
  30144. * `ngMaxlength` attribute value.
  30145. *
  30146. * <div class="alert alert-info">
  30147. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  30148. * differences:
  30149. * <ol>
  30150. * <li>
  30151. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  30152. * validation is not available.
  30153. * </li>
  30154. * <li>
  30155. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  30156. * interpolated.
  30157. * </li>
  30158. * </ol>
  30159. * </div>
  30160. *
  30161. * @example
  30162. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  30163. * <file name="index.html">
  30164. * <script>
  30165. * angular.module('ngMaxlengthExample', [])
  30166. * .controller('ExampleController', ['$scope', function($scope) {
  30167. * $scope.maxlength = 5;
  30168. * }]);
  30169. * </script>
  30170. * <div ng-controller="ExampleController">
  30171. * <form name="form">
  30172. * <label for="maxlength">Set a maxlength: </label>
  30173. * <input type="number" ng-model="maxlength" id="maxlength" />
  30174. * <br>
  30175. * <label for="input">This input is restricted by the current maxlength: </label>
  30176. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  30177. * <hr>
  30178. * input valid? = <code>{{form.input.$valid}}</code><br>
  30179. * model = <code>{{model}}</code>
  30180. * </form>
  30181. * </div>
  30182. * </file>
  30183. * <file name="protractor.js" type="protractor">
  30184. var model = element(by.binding('model'));
  30185. var input = element(by.id('input'));
  30186. it('should validate the input with the default maxlength', function() {
  30187. input.sendKeys('abcdef');
  30188. expect(model.getText()).not.toContain('abcdef');
  30189. input.clear().then(function() {
  30190. input.sendKeys('abcde');
  30191. expect(model.getText()).toContain('abcde');
  30192. });
  30193. });
  30194. * </file>
  30195. * </example>
  30196. */
  30197. var maxlengthDirective = function() {
  30198. return {
  30199. restrict: 'A',
  30200. require: '?ngModel',
  30201. link: function(scope, elm, attr, ctrl) {
  30202. if (!ctrl) return;
  30203. var maxlength = -1;
  30204. attr.$observe('maxlength', function(value) {
  30205. var intVal = toInt(value);
  30206. maxlength = isNumberNaN(intVal) ? -1 : intVal;
  30207. ctrl.$validate();
  30208. });
  30209. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  30210. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  30211. };
  30212. }
  30213. };
  30214. };
  30215. /**
  30216. * @ngdoc directive
  30217. * @name ngMinlength
  30218. *
  30219. * @description
  30220. *
  30221. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30222. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30223. *
  30224. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30225. * is shorter than the integer obtained by evaluating the Angular expression given in the
  30226. * `ngMinlength` attribute value.
  30227. *
  30228. * <div class="alert alert-info">
  30229. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  30230. * differences:
  30231. * <ol>
  30232. * <li>
  30233. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  30234. * validation is not available.
  30235. * </li>
  30236. * <li>
  30237. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  30238. * interpolated.
  30239. * </li>
  30240. * </ol>
  30241. * </div>
  30242. *
  30243. * @example
  30244. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  30245. * <file name="index.html">
  30246. * <script>
  30247. * angular.module('ngMinlengthExample', [])
  30248. * .controller('ExampleController', ['$scope', function($scope) {
  30249. * $scope.minlength = 3;
  30250. * }]);
  30251. * </script>
  30252. * <div ng-controller="ExampleController">
  30253. * <form name="form">
  30254. * <label for="minlength">Set a minlength: </label>
  30255. * <input type="number" ng-model="minlength" id="minlength" />
  30256. * <br>
  30257. * <label for="input">This input is restricted by the current minlength: </label>
  30258. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  30259. * <hr>
  30260. * input valid? = <code>{{form.input.$valid}}</code><br>
  30261. * model = <code>{{model}}</code>
  30262. * </form>
  30263. * </div>
  30264. * </file>
  30265. * <file name="protractor.js" type="protractor">
  30266. var model = element(by.binding('model'));
  30267. var input = element(by.id('input'));
  30268. it('should validate the input with the default minlength', function() {
  30269. input.sendKeys('ab');
  30270. expect(model.getText()).not.toContain('ab');
  30271. input.sendKeys('abc');
  30272. expect(model.getText()).toContain('abc');
  30273. });
  30274. * </file>
  30275. * </example>
  30276. */
  30277. var minlengthDirective = function() {
  30278. return {
  30279. restrict: 'A',
  30280. require: '?ngModel',
  30281. link: function(scope, elm, attr, ctrl) {
  30282. if (!ctrl) return;
  30283. var minlength = 0;
  30284. attr.$observe('minlength', function(value) {
  30285. minlength = toInt(value) || 0;
  30286. ctrl.$validate();
  30287. });
  30288. ctrl.$validators.minlength = function(modelValue, viewValue) {
  30289. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  30290. };
  30291. }
  30292. };
  30293. };
  30294. if (window.angular.bootstrap) {
  30295. // AngularJS is already loaded, so we can return here...
  30296. if (window.console) {
  30297. console.log('WARNING: Tried to load angular more than once.');
  30298. }
  30299. return;
  30300. }
  30301. // try to bind to jquery now so that one can write jqLite(fn)
  30302. // but we will rebind on bootstrap again.
  30303. bindJQuery();
  30304. publishExternalAPI(angular);
  30305. angular.module("ngLocale", [], ["$provide", function($provide) {
  30306. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  30307. function getDecimals(n) {
  30308. n = n + '';
  30309. var i = n.indexOf('.');
  30310. return (i == -1) ? 0 : n.length - i - 1;
  30311. }
  30312. function getVF(n, opt_precision) {
  30313. var v = opt_precision;
  30314. if (undefined === v) {
  30315. v = Math.min(getDecimals(n), 3);
  30316. }
  30317. var base = Math.pow(10, v);
  30318. var f = ((n * base) | 0) % base;
  30319. return {v: v, f: f};
  30320. }
  30321. $provide.value("$locale", {
  30322. "DATETIME_FORMATS": {
  30323. "AMPMS": [
  30324. "AM",
  30325. "PM"
  30326. ],
  30327. "DAY": [
  30328. "Sunday",
  30329. "Monday",
  30330. "Tuesday",
  30331. "Wednesday",
  30332. "Thursday",
  30333. "Friday",
  30334. "Saturday"
  30335. ],
  30336. "ERANAMES": [
  30337. "Before Christ",
  30338. "Anno Domini"
  30339. ],
  30340. "ERAS": [
  30341. "BC",
  30342. "AD"
  30343. ],
  30344. "FIRSTDAYOFWEEK": 6,
  30345. "MONTH": [
  30346. "January",
  30347. "February",
  30348. "March",
  30349. "April",
  30350. "May",
  30351. "June",
  30352. "July",
  30353. "August",
  30354. "September",
  30355. "October",
  30356. "November",
  30357. "December"
  30358. ],
  30359. "SHORTDAY": [
  30360. "Sun",
  30361. "Mon",
  30362. "Tue",
  30363. "Wed",
  30364. "Thu",
  30365. "Fri",
  30366. "Sat"
  30367. ],
  30368. "SHORTMONTH": [
  30369. "Jan",
  30370. "Feb",
  30371. "Mar",
  30372. "Apr",
  30373. "May",
  30374. "Jun",
  30375. "Jul",
  30376. "Aug",
  30377. "Sep",
  30378. "Oct",
  30379. "Nov",
  30380. "Dec"
  30381. ],
  30382. "STANDALONEMONTH": [
  30383. "January",
  30384. "February",
  30385. "March",
  30386. "April",
  30387. "May",
  30388. "June",
  30389. "July",
  30390. "August",
  30391. "September",
  30392. "October",
  30393. "November",
  30394. "December"
  30395. ],
  30396. "WEEKENDRANGE": [
  30397. 5,
  30398. 6
  30399. ],
  30400. "fullDate": "EEEE, MMMM d, y",
  30401. "longDate": "MMMM d, y",
  30402. "medium": "MMM d, y h:mm:ss a",
  30403. "mediumDate": "MMM d, y",
  30404. "mediumTime": "h:mm:ss a",
  30405. "short": "M/d/yy h:mm a",
  30406. "shortDate": "M/d/yy",
  30407. "shortTime": "h:mm a"
  30408. },
  30409. "NUMBER_FORMATS": {
  30410. "CURRENCY_SYM": "$",
  30411. "DECIMAL_SEP": ".",
  30412. "GROUP_SEP": ",",
  30413. "PATTERNS": [
  30414. {
  30415. "gSize": 3,
  30416. "lgSize": 3,
  30417. "maxFrac": 3,
  30418. "minFrac": 0,
  30419. "minInt": 1,
  30420. "negPre": "-",
  30421. "negSuf": "",
  30422. "posPre": "",
  30423. "posSuf": ""
  30424. },
  30425. {
  30426. "gSize": 3,
  30427. "lgSize": 3,
  30428. "maxFrac": 2,
  30429. "minFrac": 2,
  30430. "minInt": 1,
  30431. "negPre": "-\u00a4",
  30432. "negSuf": "",
  30433. "posPre": "\u00a4",
  30434. "posSuf": ""
  30435. }
  30436. ]
  30437. },
  30438. "id": "en-us",
  30439. "localeID": "en_US",
  30440. "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;}
  30441. });
  30442. }]);
  30443. jqLite(function() {
  30444. angularInit(window.document, bootstrap);
  30445. });
  30446. })(window);
  30447. !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>');