Aucune description

angular.js 1.1MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768
  1. /**
  2. * @license AngularJS v1.5.8
  3. * (c) 2010-2016 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 SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.5.8/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  57. encodeURIComponent(toDebugString(templateArgs[i]));
  58. }
  59. return new ErrorConstructor(message);
  60. };
  61. }
  62. /* We need to tell jshint what variables are being exported */
  63. /* global angular: true,
  64. msie: true,
  65. jqLite: true,
  66. jQuery: true,
  67. slice: true,
  68. splice: true,
  69. push: true,
  70. toString: true,
  71. ngMinErr: true,
  72. angularModule: true,
  73. uid: true,
  74. REGEX_STRING_REGEXP: true,
  75. VALIDITY_STATE_PROPERTY: true,
  76. lowercase: true,
  77. uppercase: true,
  78. manualLowercase: true,
  79. manualUppercase: true,
  80. nodeName_: true,
  81. isArrayLike: true,
  82. forEach: true,
  83. forEachSorted: true,
  84. reverseParams: true,
  85. nextUid: true,
  86. setHashKey: true,
  87. extend: true,
  88. toInt: true,
  89. inherit: true,
  90. merge: true,
  91. noop: true,
  92. identity: true,
  93. valueFn: true,
  94. isUndefined: true,
  95. isDefined: true,
  96. isObject: true,
  97. isBlankObject: true,
  98. isString: true,
  99. isNumber: true,
  100. isDate: true,
  101. isArray: true,
  102. isFunction: true,
  103. isRegExp: true,
  104. isWindow: true,
  105. isScope: true,
  106. isFile: true,
  107. isFormData: true,
  108. isBlob: true,
  109. isBoolean: true,
  110. isPromiseLike: true,
  111. trim: true,
  112. escapeForRegexp: true,
  113. isElement: true,
  114. makeMap: true,
  115. includes: true,
  116. arrayRemove: true,
  117. copy: true,
  118. equals: true,
  119. csp: true,
  120. jq: true,
  121. concat: true,
  122. sliceArgs: true,
  123. bind: true,
  124. toJsonReplacer: true,
  125. toJson: true,
  126. fromJson: true,
  127. convertTimezoneToLocal: true,
  128. timezoneToOffset: true,
  129. startingTag: true,
  130. tryDecodeURIComponent: true,
  131. parseKeyValue: true,
  132. toKeyValue: true,
  133. encodeUriSegment: true,
  134. encodeUriQuery: true,
  135. angularInit: true,
  136. bootstrap: true,
  137. getTestability: true,
  138. snake_case: true,
  139. bindJQuery: true,
  140. assertArg: true,
  141. assertArgFn: true,
  142. assertNotHasOwnProperty: true,
  143. getter: true,
  144. getBlockNodes: true,
  145. hasOwnProperty: true,
  146. createMap: true,
  147. NODE_TYPE_ELEMENT: true,
  148. NODE_TYPE_ATTRIBUTE: true,
  149. NODE_TYPE_TEXT: true,
  150. NODE_TYPE_COMMENT: true,
  151. NODE_TYPE_DOCUMENT: true,
  152. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  153. */
  154. ////////////////////////////////////
  155. /**
  156. * @ngdoc module
  157. * @name ng
  158. * @module ng
  159. * @installation
  160. * @description
  161. *
  162. * # ng (core module)
  163. * The ng module is loaded by default when an AngularJS application is started. The module itself
  164. * contains the essential components for an AngularJS application to function. The table below
  165. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  166. * components available within this core module.
  167. *
  168. * <div doc-module-components="ng"></div>
  169. */
  170. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  171. // The name of a form control's ValidityState property.
  172. // This is used so that it's possible for internal tests to create mock ValidityStates.
  173. var VALIDITY_STATE_PROPERTY = 'validity';
  174. var hasOwnProperty = Object.prototype.hasOwnProperty;
  175. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  176. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  177. var manualLowercase = function(s) {
  178. /* jshint bitwise: false */
  179. return isString(s)
  180. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  181. : s;
  182. };
  183. var manualUppercase = function(s) {
  184. /* jshint bitwise: false */
  185. return isString(s)
  186. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  187. : s;
  188. };
  189. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  190. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  191. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  192. if ('i' !== 'I'.toLowerCase()) {
  193. lowercase = manualLowercase;
  194. uppercase = manualUppercase;
  195. }
  196. var
  197. msie, // holds major version number for IE, or NaN if UA is not IE.
  198. jqLite, // delay binding since jQuery could be loaded after us.
  199. jQuery, // delay binding
  200. slice = [].slice,
  201. splice = [].splice,
  202. push = [].push,
  203. toString = Object.prototype.toString,
  204. getPrototypeOf = Object.getPrototypeOf,
  205. ngMinErr = minErr('ng'),
  206. /** @name angular */
  207. angular = window.angular || (window.angular = {}),
  208. angularModule,
  209. uid = 0;
  210. /**
  211. * documentMode is an IE-only property
  212. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  213. */
  214. msie = window.document.documentMode;
  215. /**
  216. * @private
  217. * @param {*} obj
  218. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  219. * String ...)
  220. */
  221. function isArrayLike(obj) {
  222. // `null`, `undefined` and `window` are not array-like
  223. if (obj == null || isWindow(obj)) return false;
  224. // arrays, strings and jQuery/jqLite objects are array like
  225. // * jqLite is either the jQuery or jqLite constructor function
  226. // * we have to check the existence of jqLite first as this method is called
  227. // via the forEach method when constructing the jqLite object in the first place
  228. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  229. // Support: iOS 8.2 (not reproducible in simulator)
  230. // "length" in obj used to prevent JIT error (gh-11508)
  231. var length = "length" in Object(obj) && obj.length;
  232. // NodeList objects (with `item` method) and
  233. // other objects with suitable length characteristics are array-like
  234. return isNumber(length) &&
  235. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item == 'function');
  236. }
  237. /**
  238. * @ngdoc function
  239. * @name angular.forEach
  240. * @module ng
  241. * @kind function
  242. *
  243. * @description
  244. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  245. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  246. * is the value of an object property or an array element, `key` is the object property key or
  247. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  248. *
  249. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  250. * using the `hasOwnProperty` method.
  251. *
  252. * Unlike ES262's
  253. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  254. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  255. * return the value provided.
  256. *
  257. ```js
  258. var values = {name: 'misko', gender: 'male'};
  259. var log = [];
  260. angular.forEach(values, function(value, key) {
  261. this.push(key + ': ' + value);
  262. }, log);
  263. expect(log).toEqual(['name: misko', 'gender: male']);
  264. ```
  265. *
  266. * @param {Object|Array} obj Object to iterate over.
  267. * @param {Function} iterator Iterator function.
  268. * @param {Object=} context Object to become context (`this`) for the iterator function.
  269. * @returns {Object|Array} Reference to `obj`.
  270. */
  271. function forEach(obj, iterator, context) {
  272. var key, length;
  273. if (obj) {
  274. if (isFunction(obj)) {
  275. for (key in obj) {
  276. // Need to check if hasOwnProperty exists,
  277. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  278. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  279. iterator.call(context, obj[key], key, obj);
  280. }
  281. }
  282. } else if (isArray(obj) || isArrayLike(obj)) {
  283. var isPrimitive = typeof obj !== 'object';
  284. for (key = 0, length = obj.length; key < length; key++) {
  285. if (isPrimitive || key in obj) {
  286. iterator.call(context, obj[key], key, obj);
  287. }
  288. }
  289. } else if (obj.forEach && obj.forEach !== forEach) {
  290. obj.forEach(iterator, context, obj);
  291. } else if (isBlankObject(obj)) {
  292. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  293. for (key in obj) {
  294. iterator.call(context, obj[key], key, obj);
  295. }
  296. } else if (typeof obj.hasOwnProperty === 'function') {
  297. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  298. for (key in obj) {
  299. if (obj.hasOwnProperty(key)) {
  300. iterator.call(context, obj[key], key, obj);
  301. }
  302. }
  303. } else {
  304. // Slow path for objects which do not have a method `hasOwnProperty`
  305. for (key in obj) {
  306. if (hasOwnProperty.call(obj, key)) {
  307. iterator.call(context, obj[key], key, obj);
  308. }
  309. }
  310. }
  311. }
  312. return obj;
  313. }
  314. function forEachSorted(obj, iterator, context) {
  315. var keys = Object.keys(obj).sort();
  316. for (var i = 0; i < keys.length; i++) {
  317. iterator.call(context, obj[keys[i]], keys[i]);
  318. }
  319. return keys;
  320. }
  321. /**
  322. * when using forEach the params are value, key, but it is often useful to have key, value.
  323. * @param {function(string, *)} iteratorFn
  324. * @returns {function(*, string)}
  325. */
  326. function reverseParams(iteratorFn) {
  327. return function(value, key) {iteratorFn(key, value);};
  328. }
  329. /**
  330. * A consistent way of creating unique IDs in angular.
  331. *
  332. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  333. * we hit number precision issues in JavaScript.
  334. *
  335. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  336. *
  337. * @returns {number} an unique alpha-numeric string
  338. */
  339. function nextUid() {
  340. return ++uid;
  341. }
  342. /**
  343. * Set or clear the hashkey for an object.
  344. * @param obj object
  345. * @param h the hashkey (!truthy to delete the hashkey)
  346. */
  347. function setHashKey(obj, h) {
  348. if (h) {
  349. obj.$$hashKey = h;
  350. } else {
  351. delete obj.$$hashKey;
  352. }
  353. }
  354. function baseExtend(dst, objs, deep) {
  355. var h = dst.$$hashKey;
  356. for (var i = 0, ii = objs.length; i < ii; ++i) {
  357. var obj = objs[i];
  358. if (!isObject(obj) && !isFunction(obj)) continue;
  359. var keys = Object.keys(obj);
  360. for (var j = 0, jj = keys.length; j < jj; j++) {
  361. var key = keys[j];
  362. var src = obj[key];
  363. if (deep && isObject(src)) {
  364. if (isDate(src)) {
  365. dst[key] = new Date(src.valueOf());
  366. } else if (isRegExp(src)) {
  367. dst[key] = new RegExp(src);
  368. } else if (src.nodeName) {
  369. dst[key] = src.cloneNode(true);
  370. } else if (isElement(src)) {
  371. dst[key] = src.clone();
  372. } else {
  373. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  374. baseExtend(dst[key], [src], true);
  375. }
  376. } else {
  377. dst[key] = src;
  378. }
  379. }
  380. }
  381. setHashKey(dst, h);
  382. return dst;
  383. }
  384. /**
  385. * @ngdoc function
  386. * @name angular.extend
  387. * @module ng
  388. * @kind function
  389. *
  390. * @description
  391. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  392. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  393. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  394. *
  395. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  396. * {@link angular.merge} for this.
  397. *
  398. * @param {Object} dst Destination object.
  399. * @param {...Object} src Source object(s).
  400. * @returns {Object} Reference to `dst`.
  401. */
  402. function extend(dst) {
  403. return baseExtend(dst, slice.call(arguments, 1), false);
  404. }
  405. /**
  406. * @ngdoc function
  407. * @name angular.merge
  408. * @module ng
  409. * @kind function
  410. *
  411. * @description
  412. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  413. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  414. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  415. *
  416. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  417. * objects, performing a deep copy.
  418. *
  419. * @param {Object} dst Destination object.
  420. * @param {...Object} src Source object(s).
  421. * @returns {Object} Reference to `dst`.
  422. */
  423. function merge(dst) {
  424. return baseExtend(dst, slice.call(arguments, 1), true);
  425. }
  426. function toInt(str) {
  427. return parseInt(str, 10);
  428. }
  429. function inherit(parent, extra) {
  430. return extend(Object.create(parent), extra);
  431. }
  432. /**
  433. * @ngdoc function
  434. * @name angular.noop
  435. * @module ng
  436. * @kind function
  437. *
  438. * @description
  439. * A function that performs no operations. This function can be useful when writing code in the
  440. * functional style.
  441. ```js
  442. function foo(callback) {
  443. var result = calculateResult();
  444. (callback || angular.noop)(result);
  445. }
  446. ```
  447. */
  448. function noop() {}
  449. noop.$inject = [];
  450. /**
  451. * @ngdoc function
  452. * @name angular.identity
  453. * @module ng
  454. * @kind function
  455. *
  456. * @description
  457. * A function that returns its first argument. This function is useful when writing code in the
  458. * functional style.
  459. *
  460. ```js
  461. function transformer(transformationFn, value) {
  462. return (transformationFn || angular.identity)(value);
  463. };
  464. // E.g.
  465. function getResult(fn, input) {
  466. return (fn || angular.identity)(input);
  467. };
  468. getResult(function(n) { return n * 2; }, 21); // returns 42
  469. getResult(null, 21); // returns 21
  470. getResult(undefined, 21); // returns 21
  471. ```
  472. *
  473. * @param {*} value to be returned.
  474. * @returns {*} the value passed in.
  475. */
  476. function identity($) {return $;}
  477. identity.$inject = [];
  478. function valueFn(value) {return function valueRef() {return value;};}
  479. function hasCustomToString(obj) {
  480. return isFunction(obj.toString) && obj.toString !== toString;
  481. }
  482. /**
  483. * @ngdoc function
  484. * @name angular.isUndefined
  485. * @module ng
  486. * @kind function
  487. *
  488. * @description
  489. * Determines if a reference is undefined.
  490. *
  491. * @param {*} value Reference to check.
  492. * @returns {boolean} True if `value` is undefined.
  493. */
  494. function isUndefined(value) {return typeof value === 'undefined';}
  495. /**
  496. * @ngdoc function
  497. * @name angular.isDefined
  498. * @module ng
  499. * @kind function
  500. *
  501. * @description
  502. * Determines if a reference is defined.
  503. *
  504. * @param {*} value Reference to check.
  505. * @returns {boolean} True if `value` is defined.
  506. */
  507. function isDefined(value) {return typeof value !== 'undefined';}
  508. /**
  509. * @ngdoc function
  510. * @name angular.isObject
  511. * @module ng
  512. * @kind function
  513. *
  514. * @description
  515. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  516. * considered to be objects. Note that JavaScript arrays are objects.
  517. *
  518. * @param {*} value Reference to check.
  519. * @returns {boolean} True if `value` is an `Object` but not `null`.
  520. */
  521. function isObject(value) {
  522. // http://jsperf.com/isobject4
  523. return value !== null && typeof value === 'object';
  524. }
  525. /**
  526. * Determine if a value is an object with a null prototype
  527. *
  528. * @returns {boolean} True if `value` is an `Object` with a null prototype
  529. */
  530. function isBlankObject(value) {
  531. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  532. }
  533. /**
  534. * @ngdoc function
  535. * @name angular.isString
  536. * @module ng
  537. * @kind function
  538. *
  539. * @description
  540. * Determines if a reference is a `String`.
  541. *
  542. * @param {*} value Reference to check.
  543. * @returns {boolean} True if `value` is a `String`.
  544. */
  545. function isString(value) {return typeof value === 'string';}
  546. /**
  547. * @ngdoc function
  548. * @name angular.isNumber
  549. * @module ng
  550. * @kind function
  551. *
  552. * @description
  553. * Determines if a reference is a `Number`.
  554. *
  555. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  556. *
  557. * If you wish to exclude these then you can use the native
  558. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  559. * method.
  560. *
  561. * @param {*} value Reference to check.
  562. * @returns {boolean} True if `value` is a `Number`.
  563. */
  564. function isNumber(value) {return typeof value === 'number';}
  565. /**
  566. * @ngdoc function
  567. * @name angular.isDate
  568. * @module ng
  569. * @kind function
  570. *
  571. * @description
  572. * Determines if a value is a date.
  573. *
  574. * @param {*} value Reference to check.
  575. * @returns {boolean} True if `value` is a `Date`.
  576. */
  577. function isDate(value) {
  578. return toString.call(value) === '[object Date]';
  579. }
  580. /**
  581. * @ngdoc function
  582. * @name angular.isArray
  583. * @module ng
  584. * @kind function
  585. *
  586. * @description
  587. * Determines if a reference is an `Array`.
  588. *
  589. * @param {*} value Reference to check.
  590. * @returns {boolean} True if `value` is an `Array`.
  591. */
  592. var isArray = Array.isArray;
  593. /**
  594. * @ngdoc function
  595. * @name angular.isFunction
  596. * @module ng
  597. * @kind function
  598. *
  599. * @description
  600. * Determines if a reference is a `Function`.
  601. *
  602. * @param {*} value Reference to check.
  603. * @returns {boolean} True if `value` is a `Function`.
  604. */
  605. function isFunction(value) {return typeof value === 'function';}
  606. /**
  607. * Determines if a value is a regular expression object.
  608. *
  609. * @private
  610. * @param {*} value Reference to check.
  611. * @returns {boolean} True if `value` is a `RegExp`.
  612. */
  613. function isRegExp(value) {
  614. return toString.call(value) === '[object RegExp]';
  615. }
  616. /**
  617. * Checks if `obj` is a window object.
  618. *
  619. * @private
  620. * @param {*} obj Object to check
  621. * @returns {boolean} True if `obj` is a window obj.
  622. */
  623. function isWindow(obj) {
  624. return obj && obj.window === obj;
  625. }
  626. function isScope(obj) {
  627. return obj && obj.$evalAsync && obj.$watch;
  628. }
  629. function isFile(obj) {
  630. return toString.call(obj) === '[object File]';
  631. }
  632. function isFormData(obj) {
  633. return toString.call(obj) === '[object FormData]';
  634. }
  635. function isBlob(obj) {
  636. return toString.call(obj) === '[object Blob]';
  637. }
  638. function isBoolean(value) {
  639. return typeof value === 'boolean';
  640. }
  641. function isPromiseLike(obj) {
  642. return obj && isFunction(obj.then);
  643. }
  644. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
  645. function isTypedArray(value) {
  646. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  647. }
  648. function isArrayBuffer(obj) {
  649. return toString.call(obj) === '[object ArrayBuffer]';
  650. }
  651. var trim = function(value) {
  652. return isString(value) ? value.trim() : value;
  653. };
  654. // Copied from:
  655. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  656. // Prereq: s is a string.
  657. var escapeForRegexp = function(s) {
  658. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  659. replace(/\x08/g, '\\x08');
  660. };
  661. /**
  662. * @ngdoc function
  663. * @name angular.isElement
  664. * @module ng
  665. * @kind function
  666. *
  667. * @description
  668. * Determines if a reference is a DOM element (or wrapped jQuery element).
  669. *
  670. * @param {*} value Reference to check.
  671. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  672. */
  673. function isElement(node) {
  674. return !!(node &&
  675. (node.nodeName // We are a direct element.
  676. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  677. }
  678. /**
  679. * @param str 'key1,key2,...'
  680. * @returns {object} in the form of {key1:true, key2:true, ...}
  681. */
  682. function makeMap(str) {
  683. var obj = {}, items = str.split(','), i;
  684. for (i = 0; i < items.length; i++) {
  685. obj[items[i]] = true;
  686. }
  687. return obj;
  688. }
  689. function nodeName_(element) {
  690. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  691. }
  692. function includes(array, obj) {
  693. return Array.prototype.indexOf.call(array, obj) != -1;
  694. }
  695. function arrayRemove(array, value) {
  696. var index = array.indexOf(value);
  697. if (index >= 0) {
  698. array.splice(index, 1);
  699. }
  700. return index;
  701. }
  702. /**
  703. * @ngdoc function
  704. * @name angular.copy
  705. * @module ng
  706. * @kind function
  707. *
  708. * @description
  709. * Creates a deep copy of `source`, which should be an object or an array.
  710. *
  711. * * If no destination is supplied, a copy of the object or array is created.
  712. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  713. * are deleted and then all elements/properties from the source are copied to it.
  714. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  715. * * If `source` is identical to `destination` an exception will be thrown.
  716. *
  717. * <br />
  718. * <div class="alert alert-warning">
  719. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  720. * and on `destination`) will be ignored.
  721. * </div>
  722. *
  723. * @param {*} source The source that will be used to make a copy.
  724. * Can be any type, including primitives, `null`, and `undefined`.
  725. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  726. * provided, must be of the same type as `source`.
  727. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  728. *
  729. * @example
  730. <example module="copyExample">
  731. <file name="index.html">
  732. <div ng-controller="ExampleController">
  733. <form novalidate class="simple-form">
  734. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  735. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  736. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  737. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  738. <button ng-click="reset()">RESET</button>
  739. <button ng-click="update(user)">SAVE</button>
  740. </form>
  741. <pre>form = {{user | json}}</pre>
  742. <pre>master = {{master | json}}</pre>
  743. </div>
  744. </file>
  745. <file name="script.js">
  746. // Module: copyExample
  747. angular.
  748. module('copyExample', []).
  749. controller('ExampleController', ['$scope', function($scope) {
  750. $scope.master = {};
  751. $scope.reset = function() {
  752. // Example with 1 argument
  753. $scope.user = angular.copy($scope.master);
  754. };
  755. $scope.update = function(user) {
  756. // Example with 2 arguments
  757. angular.copy(user, $scope.master);
  758. };
  759. $scope.reset();
  760. }]);
  761. </file>
  762. </example>
  763. */
  764. function copy(source, destination) {
  765. var stackSource = [];
  766. var stackDest = [];
  767. if (destination) {
  768. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  769. throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
  770. }
  771. if (source === destination) {
  772. throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
  773. }
  774. // Empty the destination object
  775. if (isArray(destination)) {
  776. destination.length = 0;
  777. } else {
  778. forEach(destination, function(value, key) {
  779. if (key !== '$$hashKey') {
  780. delete destination[key];
  781. }
  782. });
  783. }
  784. stackSource.push(source);
  785. stackDest.push(destination);
  786. return copyRecurse(source, destination);
  787. }
  788. return copyElement(source);
  789. function copyRecurse(source, destination) {
  790. var h = destination.$$hashKey;
  791. var key;
  792. if (isArray(source)) {
  793. for (var i = 0, ii = source.length; i < ii; i++) {
  794. destination.push(copyElement(source[i]));
  795. }
  796. } else if (isBlankObject(source)) {
  797. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  798. for (key in source) {
  799. destination[key] = copyElement(source[key]);
  800. }
  801. } else if (source && typeof source.hasOwnProperty === 'function') {
  802. // Slow path, which must rely on hasOwnProperty
  803. for (key in source) {
  804. if (source.hasOwnProperty(key)) {
  805. destination[key] = copyElement(source[key]);
  806. }
  807. }
  808. } else {
  809. // Slowest path --- hasOwnProperty can't be called as a method
  810. for (key in source) {
  811. if (hasOwnProperty.call(source, key)) {
  812. destination[key] = copyElement(source[key]);
  813. }
  814. }
  815. }
  816. setHashKey(destination, h);
  817. return destination;
  818. }
  819. function copyElement(source) {
  820. // Simple values
  821. if (!isObject(source)) {
  822. return source;
  823. }
  824. // Already copied values
  825. var index = stackSource.indexOf(source);
  826. if (index !== -1) {
  827. return stackDest[index];
  828. }
  829. if (isWindow(source) || isScope(source)) {
  830. throw ngMinErr('cpws',
  831. "Can't copy! Making copies of Window or Scope instances is not supported.");
  832. }
  833. var needsRecurse = false;
  834. var destination = copyType(source);
  835. if (destination === undefined) {
  836. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  837. needsRecurse = true;
  838. }
  839. stackSource.push(source);
  840. stackDest.push(destination);
  841. return needsRecurse
  842. ? copyRecurse(source, destination)
  843. : destination;
  844. }
  845. function copyType(source) {
  846. switch (toString.call(source)) {
  847. case '[object Int8Array]':
  848. case '[object Int16Array]':
  849. case '[object Int32Array]':
  850. case '[object Float32Array]':
  851. case '[object Float64Array]':
  852. case '[object Uint8Array]':
  853. case '[object Uint8ClampedArray]':
  854. case '[object Uint16Array]':
  855. case '[object Uint32Array]':
  856. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  857. case '[object ArrayBuffer]':
  858. //Support: IE10
  859. if (!source.slice) {
  860. var copied = new ArrayBuffer(source.byteLength);
  861. new Uint8Array(copied).set(new Uint8Array(source));
  862. return copied;
  863. }
  864. return source.slice(0);
  865. case '[object Boolean]':
  866. case '[object Number]':
  867. case '[object String]':
  868. case '[object Date]':
  869. return new source.constructor(source.valueOf());
  870. case '[object RegExp]':
  871. var re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  872. re.lastIndex = source.lastIndex;
  873. return re;
  874. case '[object Blob]':
  875. return new source.constructor([source], {type: source.type});
  876. }
  877. if (isFunction(source.cloneNode)) {
  878. return source.cloneNode(true);
  879. }
  880. }
  881. }
  882. /**
  883. * @ngdoc function
  884. * @name angular.equals
  885. * @module ng
  886. * @kind function
  887. *
  888. * @description
  889. * Determines if two objects or two values are equivalent. Supports value types, regular
  890. * expressions, arrays and objects.
  891. *
  892. * Two objects or values are considered equivalent if at least one of the following is true:
  893. *
  894. * * Both objects or values pass `===` comparison.
  895. * * Both objects or values are of the same type and all of their properties are equal by
  896. * comparing them with `angular.equals`.
  897. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  898. * * Both values represent the same regular expression (In JavaScript,
  899. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  900. * representation matches).
  901. *
  902. * During a property comparison, properties of `function` type and properties with names
  903. * that begin with `$` are ignored.
  904. *
  905. * Scope and DOMWindow objects are being compared only by identify (`===`).
  906. *
  907. * @param {*} o1 Object or value to compare.
  908. * @param {*} o2 Object or value to compare.
  909. * @returns {boolean} True if arguments are equal.
  910. *
  911. * @example
  912. <example module="equalsExample" name="equalsExample">
  913. <file name="index.html">
  914. <div ng-controller="ExampleController">
  915. <form novalidate>
  916. <h3>User 1</h3>
  917. Name: <input type="text" ng-model="user1.name">
  918. Age: <input type="number" ng-model="user1.age">
  919. <h3>User 2</h3>
  920. Name: <input type="text" ng-model="user2.name">
  921. Age: <input type="number" ng-model="user2.age">
  922. <div>
  923. <br/>
  924. <input type="button" value="Compare" ng-click="compare()">
  925. </div>
  926. User 1: <pre>{{user1 | json}}</pre>
  927. User 2: <pre>{{user2 | json}}</pre>
  928. Equal: <pre>{{result}}</pre>
  929. </form>
  930. </div>
  931. </file>
  932. <file name="script.js">
  933. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  934. $scope.user1 = {};
  935. $scope.user2 = {};
  936. $scope.result;
  937. $scope.compare = function() {
  938. $scope.result = angular.equals($scope.user1, $scope.user2);
  939. };
  940. }]);
  941. </file>
  942. </example>
  943. */
  944. function equals(o1, o2) {
  945. if (o1 === o2) return true;
  946. if (o1 === null || o2 === null) return false;
  947. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  948. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  949. if (t1 == t2 && t1 == 'object') {
  950. if (isArray(o1)) {
  951. if (!isArray(o2)) return false;
  952. if ((length = o1.length) == o2.length) {
  953. for (key = 0; key < length; key++) {
  954. if (!equals(o1[key], o2[key])) return false;
  955. }
  956. return true;
  957. }
  958. } else if (isDate(o1)) {
  959. if (!isDate(o2)) return false;
  960. return equals(o1.getTime(), o2.getTime());
  961. } else if (isRegExp(o1)) {
  962. if (!isRegExp(o2)) return false;
  963. return o1.toString() == o2.toString();
  964. } else {
  965. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  966. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  967. keySet = createMap();
  968. for (key in o1) {
  969. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  970. if (!equals(o1[key], o2[key])) return false;
  971. keySet[key] = true;
  972. }
  973. for (key in o2) {
  974. if (!(key in keySet) &&
  975. key.charAt(0) !== '$' &&
  976. isDefined(o2[key]) &&
  977. !isFunction(o2[key])) return false;
  978. }
  979. return true;
  980. }
  981. }
  982. return false;
  983. }
  984. var csp = function() {
  985. if (!isDefined(csp.rules)) {
  986. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  987. window.document.querySelector('[data-ng-csp]'));
  988. if (ngCspElement) {
  989. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  990. ngCspElement.getAttribute('data-ng-csp');
  991. csp.rules = {
  992. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  993. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  994. };
  995. } else {
  996. csp.rules = {
  997. noUnsafeEval: noUnsafeEval(),
  998. noInlineStyle: false
  999. };
  1000. }
  1001. }
  1002. return csp.rules;
  1003. function noUnsafeEval() {
  1004. try {
  1005. /* jshint -W031, -W054 */
  1006. new Function('');
  1007. /* jshint +W031, +W054 */
  1008. return false;
  1009. } catch (e) {
  1010. return true;
  1011. }
  1012. }
  1013. };
  1014. /**
  1015. * @ngdoc directive
  1016. * @module ng
  1017. * @name ngJq
  1018. *
  1019. * @element ANY
  1020. * @param {string=} ngJq the name of the library available under `window`
  1021. * to be used for angular.element
  1022. * @description
  1023. * Use this directive to force the angular.element library. This should be
  1024. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1025. * the jquery variable under window (eg. jQuery).
  1026. *
  1027. * Since angular looks for this directive when it is loaded (doesn't wait for the
  1028. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1029. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1030. * others ignored.
  1031. *
  1032. * @example
  1033. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1034. ```html
  1035. <!doctype html>
  1036. <html ng-app ng-jq>
  1037. ...
  1038. ...
  1039. </html>
  1040. ```
  1041. * @example
  1042. * This example shows how to use a jQuery based library of a different name.
  1043. * The library name must be available at the top most 'window'.
  1044. ```html
  1045. <!doctype html>
  1046. <html ng-app ng-jq="jQueryLib">
  1047. ...
  1048. ...
  1049. </html>
  1050. ```
  1051. */
  1052. var jq = function() {
  1053. if (isDefined(jq.name_)) return jq.name_;
  1054. var el;
  1055. var i, ii = ngAttrPrefixes.length, prefix, name;
  1056. for (i = 0; i < ii; ++i) {
  1057. prefix = ngAttrPrefixes[i];
  1058. if (el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  1059. name = el.getAttribute(prefix + 'jq');
  1060. break;
  1061. }
  1062. }
  1063. return (jq.name_ = name);
  1064. };
  1065. function concat(array1, array2, index) {
  1066. return array1.concat(slice.call(array2, index));
  1067. }
  1068. function sliceArgs(args, startIndex) {
  1069. return slice.call(args, startIndex || 0);
  1070. }
  1071. /* jshint -W101 */
  1072. /**
  1073. * @ngdoc function
  1074. * @name angular.bind
  1075. * @module ng
  1076. * @kind function
  1077. *
  1078. * @description
  1079. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1080. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1081. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1082. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1083. *
  1084. * @param {Object} self Context which `fn` should be evaluated in.
  1085. * @param {function()} fn Function to be bound.
  1086. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1087. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1088. */
  1089. /* jshint +W101 */
  1090. function bind(self, fn) {
  1091. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1092. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1093. return curryArgs.length
  1094. ? function() {
  1095. return arguments.length
  1096. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1097. : fn.apply(self, curryArgs);
  1098. }
  1099. : function() {
  1100. return arguments.length
  1101. ? fn.apply(self, arguments)
  1102. : fn.call(self);
  1103. };
  1104. } else {
  1105. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1106. return fn;
  1107. }
  1108. }
  1109. function toJsonReplacer(key, value) {
  1110. var val = value;
  1111. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1112. val = undefined;
  1113. } else if (isWindow(value)) {
  1114. val = '$WINDOW';
  1115. } else if (value && window.document === value) {
  1116. val = '$DOCUMENT';
  1117. } else if (isScope(value)) {
  1118. val = '$SCOPE';
  1119. }
  1120. return val;
  1121. }
  1122. /**
  1123. * @ngdoc function
  1124. * @name angular.toJson
  1125. * @module ng
  1126. * @kind function
  1127. *
  1128. * @description
  1129. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1130. * stripped since angular uses this notation internally.
  1131. *
  1132. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1133. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1134. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1135. * @returns {string|undefined} JSON-ified string representing `obj`.
  1136. * @knownIssue
  1137. *
  1138. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1139. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1140. * `Date.prototype.toJSON` method as follows:
  1141. *
  1142. * ```
  1143. * var _DatetoJSON = Date.prototype.toJSON;
  1144. * Date.prototype.toJSON = function() {
  1145. * try {
  1146. * return _DatetoJSON.call(this);
  1147. * } catch(e) {
  1148. * if (e instanceof RangeError) {
  1149. * return null;
  1150. * }
  1151. * throw e;
  1152. * }
  1153. * };
  1154. * ```
  1155. *
  1156. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1157. */
  1158. function toJson(obj, pretty) {
  1159. if (isUndefined(obj)) return undefined;
  1160. if (!isNumber(pretty)) {
  1161. pretty = pretty ? 2 : null;
  1162. }
  1163. return JSON.stringify(obj, toJsonReplacer, pretty);
  1164. }
  1165. /**
  1166. * @ngdoc function
  1167. * @name angular.fromJson
  1168. * @module ng
  1169. * @kind function
  1170. *
  1171. * @description
  1172. * Deserializes a JSON string.
  1173. *
  1174. * @param {string} json JSON string to deserialize.
  1175. * @returns {Object|Array|string|number} Deserialized JSON string.
  1176. */
  1177. function fromJson(json) {
  1178. return isString(json)
  1179. ? JSON.parse(json)
  1180. : json;
  1181. }
  1182. var ALL_COLONS = /:/g;
  1183. function timezoneToOffset(timezone, fallback) {
  1184. // IE/Edge do not "understand" colon (`:`) in timezone
  1185. timezone = timezone.replace(ALL_COLONS, '');
  1186. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1187. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1188. }
  1189. function addDateMinutes(date, minutes) {
  1190. date = new Date(date.getTime());
  1191. date.setMinutes(date.getMinutes() + minutes);
  1192. return date;
  1193. }
  1194. function convertTimezoneToLocal(date, timezone, reverse) {
  1195. reverse = reverse ? -1 : 1;
  1196. var dateTimezoneOffset = date.getTimezoneOffset();
  1197. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1198. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1199. }
  1200. /**
  1201. * @returns {string} Returns the string representation of the element.
  1202. */
  1203. function startingTag(element) {
  1204. element = jqLite(element).clone();
  1205. try {
  1206. // turns out IE does not let you set .html() on elements which
  1207. // are not allowed to have children. So we just ignore it.
  1208. element.empty();
  1209. } catch (e) {}
  1210. var elemHtml = jqLite('<div>').append(element).html();
  1211. try {
  1212. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1213. elemHtml.
  1214. match(/^(<[^>]+>)/)[1].
  1215. replace(/^<([\w\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1216. } catch (e) {
  1217. return lowercase(elemHtml);
  1218. }
  1219. }
  1220. /////////////////////////////////////////////////
  1221. /**
  1222. * Tries to decode the URI component without throwing an exception.
  1223. *
  1224. * @private
  1225. * @param str value potential URI component to check.
  1226. * @returns {boolean} True if `value` can be decoded
  1227. * with the decodeURIComponent function.
  1228. */
  1229. function tryDecodeURIComponent(value) {
  1230. try {
  1231. return decodeURIComponent(value);
  1232. } catch (e) {
  1233. // Ignore any invalid uri component.
  1234. }
  1235. }
  1236. /**
  1237. * Parses an escaped url query string into key-value pairs.
  1238. * @returns {Object.<string,boolean|Array>}
  1239. */
  1240. function parseKeyValue(/**string*/keyValue) {
  1241. var obj = {};
  1242. forEach((keyValue || "").split('&'), function(keyValue) {
  1243. var splitPoint, key, val;
  1244. if (keyValue) {
  1245. key = keyValue = keyValue.replace(/\+/g,'%20');
  1246. splitPoint = keyValue.indexOf('=');
  1247. if (splitPoint !== -1) {
  1248. key = keyValue.substring(0, splitPoint);
  1249. val = keyValue.substring(splitPoint + 1);
  1250. }
  1251. key = tryDecodeURIComponent(key);
  1252. if (isDefined(key)) {
  1253. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1254. if (!hasOwnProperty.call(obj, key)) {
  1255. obj[key] = val;
  1256. } else if (isArray(obj[key])) {
  1257. obj[key].push(val);
  1258. } else {
  1259. obj[key] = [obj[key],val];
  1260. }
  1261. }
  1262. }
  1263. });
  1264. return obj;
  1265. }
  1266. function toKeyValue(obj) {
  1267. var parts = [];
  1268. forEach(obj, function(value, key) {
  1269. if (isArray(value)) {
  1270. forEach(value, function(arrayValue) {
  1271. parts.push(encodeUriQuery(key, true) +
  1272. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1273. });
  1274. } else {
  1275. parts.push(encodeUriQuery(key, true) +
  1276. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1277. }
  1278. });
  1279. return parts.length ? parts.join('&') : '';
  1280. }
  1281. /**
  1282. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1283. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1284. * segments:
  1285. * segment = *pchar
  1286. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1287. * pct-encoded = "%" HEXDIG HEXDIG
  1288. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1289. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1290. * / "*" / "+" / "," / ";" / "="
  1291. */
  1292. function encodeUriSegment(val) {
  1293. return encodeUriQuery(val, true).
  1294. replace(/%26/gi, '&').
  1295. replace(/%3D/gi, '=').
  1296. replace(/%2B/gi, '+');
  1297. }
  1298. /**
  1299. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1300. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1301. * encoded per http://tools.ietf.org/html/rfc3986:
  1302. * query = *( pchar / "/" / "?" )
  1303. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1304. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1305. * pct-encoded = "%" HEXDIG HEXDIG
  1306. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1307. * / "*" / "+" / "," / ";" / "="
  1308. */
  1309. function encodeUriQuery(val, pctEncodeSpaces) {
  1310. return encodeURIComponent(val).
  1311. replace(/%40/gi, '@').
  1312. replace(/%3A/gi, ':').
  1313. replace(/%24/g, '$').
  1314. replace(/%2C/gi, ',').
  1315. replace(/%3B/gi, ';').
  1316. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1317. }
  1318. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1319. function getNgAttribute(element, ngAttr) {
  1320. var attr, i, ii = ngAttrPrefixes.length;
  1321. for (i = 0; i < ii; ++i) {
  1322. attr = ngAttrPrefixes[i] + ngAttr;
  1323. if (isString(attr = element.getAttribute(attr))) {
  1324. return attr;
  1325. }
  1326. }
  1327. return null;
  1328. }
  1329. /**
  1330. * @ngdoc directive
  1331. * @name ngApp
  1332. * @module ng
  1333. *
  1334. * @element ANY
  1335. * @param {angular.Module} ngApp an optional application
  1336. * {@link angular.module module} name to load.
  1337. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1338. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1339. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1340. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1341. * tracking down the root of these bugs.
  1342. *
  1343. * @description
  1344. *
  1345. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1346. * designates the **root element** of the application and is typically placed near the root element
  1347. * of the page - e.g. on the `<body>` or `<html>` tags.
  1348. *
  1349. * There are a few things to keep in mind when using `ngApp`:
  1350. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1351. * found in the document will be used to define the root element to auto-bootstrap as an
  1352. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1353. * {@link angular.bootstrap} instead.
  1354. * - AngularJS applications cannot be nested within each other.
  1355. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1356. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1357. * {@link ngRoute.ngView `ngView`}.
  1358. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1359. * causing animations to stop working and making the injector inaccessible from outside the app.
  1360. *
  1361. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1362. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1363. * should contain the application code needed or have dependencies on other modules that will
  1364. * contain the code. See {@link angular.module} for more information.
  1365. *
  1366. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1367. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1368. * would not be resolved to `3`.
  1369. *
  1370. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1371. *
  1372. <example module="ngAppDemo">
  1373. <file name="index.html">
  1374. <div ng-controller="ngAppDemoController">
  1375. I can add: {{a}} + {{b}} = {{ a+b }}
  1376. </div>
  1377. </file>
  1378. <file name="script.js">
  1379. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1380. $scope.a = 1;
  1381. $scope.b = 2;
  1382. });
  1383. </file>
  1384. </example>
  1385. *
  1386. * Using `ngStrictDi`, you would see something like this:
  1387. *
  1388. <example ng-app-included="true">
  1389. <file name="index.html">
  1390. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1391. <div ng-controller="GoodController1">
  1392. I can add: {{a}} + {{b}} = {{ a+b }}
  1393. <p>This renders because the controller does not fail to
  1394. instantiate, by using explicit annotation style (see
  1395. script.js for details)
  1396. </p>
  1397. </div>
  1398. <div ng-controller="GoodController2">
  1399. Name: <input ng-model="name"><br />
  1400. Hello, {{name}}!
  1401. <p>This renders because the controller does not fail to
  1402. instantiate, by using explicit annotation style
  1403. (see script.js for details)
  1404. </p>
  1405. </div>
  1406. <div ng-controller="BadController">
  1407. I can add: {{a}} + {{b}} = {{ a+b }}
  1408. <p>The controller could not be instantiated, due to relying
  1409. on automatic function annotations (which are disabled in
  1410. strict mode). As such, the content of this section is not
  1411. interpolated, and there should be an error in your web console.
  1412. </p>
  1413. </div>
  1414. </div>
  1415. </file>
  1416. <file name="script.js">
  1417. angular.module('ngAppStrictDemo', [])
  1418. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1419. // rather than an explicit annotation
  1420. .controller('BadController', function($scope) {
  1421. $scope.a = 1;
  1422. $scope.b = 2;
  1423. })
  1424. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1425. // due to using explicit annotations using the array style and $inject property, respectively.
  1426. .controller('GoodController1', ['$scope', function($scope) {
  1427. $scope.a = 1;
  1428. $scope.b = 2;
  1429. }])
  1430. .controller('GoodController2', GoodController2);
  1431. function GoodController2($scope) {
  1432. $scope.name = "World";
  1433. }
  1434. GoodController2.$inject = ['$scope'];
  1435. </file>
  1436. <file name="style.css">
  1437. div[ng-controller] {
  1438. margin-bottom: 1em;
  1439. -webkit-border-radius: 4px;
  1440. border-radius: 4px;
  1441. border: 1px solid;
  1442. padding: .5em;
  1443. }
  1444. div[ng-controller^=Good] {
  1445. border-color: #d6e9c6;
  1446. background-color: #dff0d8;
  1447. color: #3c763d;
  1448. }
  1449. div[ng-controller^=Bad] {
  1450. border-color: #ebccd1;
  1451. background-color: #f2dede;
  1452. color: #a94442;
  1453. margin-bottom: 0;
  1454. }
  1455. </file>
  1456. </example>
  1457. */
  1458. function angularInit(element, bootstrap) {
  1459. var appElement,
  1460. module,
  1461. config = {};
  1462. // The element `element` has priority over any other element.
  1463. forEach(ngAttrPrefixes, function(prefix) {
  1464. var name = prefix + 'app';
  1465. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1466. appElement = element;
  1467. module = element.getAttribute(name);
  1468. }
  1469. });
  1470. forEach(ngAttrPrefixes, function(prefix) {
  1471. var name = prefix + 'app';
  1472. var candidate;
  1473. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1474. appElement = candidate;
  1475. module = candidate.getAttribute(name);
  1476. }
  1477. });
  1478. if (appElement) {
  1479. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1480. bootstrap(appElement, module ? [module] : [], config);
  1481. }
  1482. }
  1483. /**
  1484. * @ngdoc function
  1485. * @name angular.bootstrap
  1486. * @module ng
  1487. * @description
  1488. * Use this function to manually start up angular application.
  1489. *
  1490. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1491. *
  1492. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1493. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1494. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1495. * multiple instances of Angular try to work on the DOM.
  1496. *
  1497. * <div class="alert alert-warning">
  1498. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1499. * They must use {@link ng.directive:ngApp ngApp}.
  1500. * </div>
  1501. *
  1502. * <div class="alert alert-warning">
  1503. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1504. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1505. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1506. * causing animations to stop working and making the injector inaccessible from outside the app.
  1507. * </div>
  1508. *
  1509. * ```html
  1510. * <!doctype html>
  1511. * <html>
  1512. * <body>
  1513. * <div ng-controller="WelcomeController">
  1514. * {{greeting}}
  1515. * </div>
  1516. *
  1517. * <script src="angular.js"></script>
  1518. * <script>
  1519. * var app = angular.module('demo', [])
  1520. * .controller('WelcomeController', function($scope) {
  1521. * $scope.greeting = 'Welcome!';
  1522. * });
  1523. * angular.bootstrap(document, ['demo']);
  1524. * </script>
  1525. * </body>
  1526. * </html>
  1527. * ```
  1528. *
  1529. * @param {DOMElement} element DOM element which is the root of angular application.
  1530. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1531. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1532. * function that will be invoked by the injector as a `config` block.
  1533. * See: {@link angular.module modules}
  1534. * @param {Object=} config an object for defining configuration options for the application. The
  1535. * following keys are supported:
  1536. *
  1537. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1538. * assist in finding bugs which break minified code. Defaults to `false`.
  1539. *
  1540. * @returns {auto.$injector} Returns the newly created injector for this app.
  1541. */
  1542. function bootstrap(element, modules, config) {
  1543. if (!isObject(config)) config = {};
  1544. var defaultConfig = {
  1545. strictDi: false
  1546. };
  1547. config = extend(defaultConfig, config);
  1548. var doBootstrap = function() {
  1549. element = jqLite(element);
  1550. if (element.injector()) {
  1551. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1552. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1553. throw ngMinErr(
  1554. 'btstrpd',
  1555. "App already bootstrapped with this element '{0}'",
  1556. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1557. }
  1558. modules = modules || [];
  1559. modules.unshift(['$provide', function($provide) {
  1560. $provide.value('$rootElement', element);
  1561. }]);
  1562. if (config.debugInfoEnabled) {
  1563. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1564. modules.push(['$compileProvider', function($compileProvider) {
  1565. $compileProvider.debugInfoEnabled(true);
  1566. }]);
  1567. }
  1568. modules.unshift('ng');
  1569. var injector = createInjector(modules, config.strictDi);
  1570. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1571. function bootstrapApply(scope, element, compile, injector) {
  1572. scope.$apply(function() {
  1573. element.data('$injector', injector);
  1574. compile(element)(scope);
  1575. });
  1576. }]
  1577. );
  1578. return injector;
  1579. };
  1580. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1581. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1582. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1583. config.debugInfoEnabled = true;
  1584. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1585. }
  1586. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1587. return doBootstrap();
  1588. }
  1589. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1590. angular.resumeBootstrap = function(extraModules) {
  1591. forEach(extraModules, function(module) {
  1592. modules.push(module);
  1593. });
  1594. return doBootstrap();
  1595. };
  1596. if (isFunction(angular.resumeDeferredBootstrap)) {
  1597. angular.resumeDeferredBootstrap();
  1598. }
  1599. }
  1600. /**
  1601. * @ngdoc function
  1602. * @name angular.reloadWithDebugInfo
  1603. * @module ng
  1604. * @description
  1605. * Use this function to reload the current application with debug information turned on.
  1606. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1607. *
  1608. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1609. */
  1610. function reloadWithDebugInfo() {
  1611. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1612. window.location.reload();
  1613. }
  1614. /**
  1615. * @name angular.getTestability
  1616. * @module ng
  1617. * @description
  1618. * Get the testability service for the instance of Angular on the given
  1619. * element.
  1620. * @param {DOMElement} element DOM element which is the root of angular application.
  1621. */
  1622. function getTestability(rootElement) {
  1623. var injector = angular.element(rootElement).injector();
  1624. if (!injector) {
  1625. throw ngMinErr('test',
  1626. 'no injector found for element argument to getTestability');
  1627. }
  1628. return injector.get('$$testability');
  1629. }
  1630. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1631. function snake_case(name, separator) {
  1632. separator = separator || '_';
  1633. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1634. return (pos ? separator : '') + letter.toLowerCase();
  1635. });
  1636. }
  1637. var bindJQueryFired = false;
  1638. function bindJQuery() {
  1639. var originalCleanData;
  1640. if (bindJQueryFired) {
  1641. return;
  1642. }
  1643. // bind to jQuery if present;
  1644. var jqName = jq();
  1645. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1646. !jqName ? undefined : // use jqLite
  1647. window[jqName]; // use jQuery specified by `ngJq`
  1648. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1649. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1650. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1651. // versions. It will not work for sure with jQuery <1.7, though.
  1652. if (jQuery && jQuery.fn.on) {
  1653. jqLite = jQuery;
  1654. extend(jQuery.fn, {
  1655. scope: JQLitePrototype.scope,
  1656. isolateScope: JQLitePrototype.isolateScope,
  1657. controller: JQLitePrototype.controller,
  1658. injector: JQLitePrototype.injector,
  1659. inheritedData: JQLitePrototype.inheritedData
  1660. });
  1661. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1662. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1663. // the $destroy event on all removed nodes.
  1664. originalCleanData = jQuery.cleanData;
  1665. jQuery.cleanData = function(elems) {
  1666. var events;
  1667. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1668. events = jQuery._data(elem, "events");
  1669. if (events && events.$destroy) {
  1670. jQuery(elem).triggerHandler('$destroy');
  1671. }
  1672. }
  1673. originalCleanData(elems);
  1674. };
  1675. } else {
  1676. jqLite = JQLite;
  1677. }
  1678. angular.element = jqLite;
  1679. // Prevent double-proxying.
  1680. bindJQueryFired = true;
  1681. }
  1682. /**
  1683. * throw error if the argument is falsy.
  1684. */
  1685. function assertArg(arg, name, reason) {
  1686. if (!arg) {
  1687. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1688. }
  1689. return arg;
  1690. }
  1691. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1692. if (acceptArrayAnnotation && isArray(arg)) {
  1693. arg = arg[arg.length - 1];
  1694. }
  1695. assertArg(isFunction(arg), name, 'not a function, got ' +
  1696. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1697. return arg;
  1698. }
  1699. /**
  1700. * throw error if the name given is hasOwnProperty
  1701. * @param {String} name the name to test
  1702. * @param {String} context the context in which the name is used, such as module or directive
  1703. */
  1704. function assertNotHasOwnProperty(name, context) {
  1705. if (name === 'hasOwnProperty') {
  1706. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1707. }
  1708. }
  1709. /**
  1710. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1711. * @param {Object} obj starting object
  1712. * @param {String} path path to traverse
  1713. * @param {boolean} [bindFnToScope=true]
  1714. * @returns {Object} value as accessible by path
  1715. */
  1716. //TODO(misko): this function needs to be removed
  1717. function getter(obj, path, bindFnToScope) {
  1718. if (!path) return obj;
  1719. var keys = path.split('.');
  1720. var key;
  1721. var lastInstance = obj;
  1722. var len = keys.length;
  1723. for (var i = 0; i < len; i++) {
  1724. key = keys[i];
  1725. if (obj) {
  1726. obj = (lastInstance = obj)[key];
  1727. }
  1728. }
  1729. if (!bindFnToScope && isFunction(obj)) {
  1730. return bind(lastInstance, obj);
  1731. }
  1732. return obj;
  1733. }
  1734. /**
  1735. * Return the DOM siblings between the first and last node in the given array.
  1736. * @param {Array} array like object
  1737. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1738. */
  1739. function getBlockNodes(nodes) {
  1740. // TODO(perf): update `nodes` instead of creating a new object?
  1741. var node = nodes[0];
  1742. var endNode = nodes[nodes.length - 1];
  1743. var blockNodes;
  1744. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1745. if (blockNodes || nodes[i] !== node) {
  1746. if (!blockNodes) {
  1747. blockNodes = jqLite(slice.call(nodes, 0, i));
  1748. }
  1749. blockNodes.push(node);
  1750. }
  1751. }
  1752. return blockNodes || nodes;
  1753. }
  1754. /**
  1755. * Creates a new object without a prototype. This object is useful for lookup without having to
  1756. * guard against prototypically inherited properties via hasOwnProperty.
  1757. *
  1758. * Related micro-benchmarks:
  1759. * - http://jsperf.com/object-create2
  1760. * - http://jsperf.com/proto-map-lookup/2
  1761. * - http://jsperf.com/for-in-vs-object-keys2
  1762. *
  1763. * @returns {Object}
  1764. */
  1765. function createMap() {
  1766. return Object.create(null);
  1767. }
  1768. var NODE_TYPE_ELEMENT = 1;
  1769. var NODE_TYPE_ATTRIBUTE = 2;
  1770. var NODE_TYPE_TEXT = 3;
  1771. var NODE_TYPE_COMMENT = 8;
  1772. var NODE_TYPE_DOCUMENT = 9;
  1773. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1774. /**
  1775. * @ngdoc type
  1776. * @name angular.Module
  1777. * @module ng
  1778. * @description
  1779. *
  1780. * Interface for configuring angular {@link angular.module modules}.
  1781. */
  1782. function setupModuleLoader(window) {
  1783. var $injectorMinErr = minErr('$injector');
  1784. var ngMinErr = minErr('ng');
  1785. function ensure(obj, name, factory) {
  1786. return obj[name] || (obj[name] = factory());
  1787. }
  1788. var angular = ensure(window, 'angular', Object);
  1789. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1790. angular.$$minErr = angular.$$minErr || minErr;
  1791. return ensure(angular, 'module', function() {
  1792. /** @type {Object.<string, angular.Module>} */
  1793. var modules = {};
  1794. /**
  1795. * @ngdoc function
  1796. * @name angular.module
  1797. * @module ng
  1798. * @description
  1799. *
  1800. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1801. * modules.
  1802. * All modules (angular core or 3rd party) that should be available to an application must be
  1803. * registered using this mechanism.
  1804. *
  1805. * Passing one argument retrieves an existing {@link angular.Module},
  1806. * whereas passing more than one argument creates a new {@link angular.Module}
  1807. *
  1808. *
  1809. * # Module
  1810. *
  1811. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1812. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1813. *
  1814. * ```js
  1815. * // Create a new module
  1816. * var myModule = angular.module('myModule', []);
  1817. *
  1818. * // register a new service
  1819. * myModule.value('appName', 'MyCoolApp');
  1820. *
  1821. * // configure existing services inside initialization blocks.
  1822. * myModule.config(['$locationProvider', function($locationProvider) {
  1823. * // Configure existing providers
  1824. * $locationProvider.hashPrefix('!');
  1825. * }]);
  1826. * ```
  1827. *
  1828. * Then you can create an injector and load your modules like this:
  1829. *
  1830. * ```js
  1831. * var injector = angular.injector(['ng', 'myModule'])
  1832. * ```
  1833. *
  1834. * However it's more likely that you'll just use
  1835. * {@link ng.directive:ngApp ngApp} or
  1836. * {@link angular.bootstrap} to simplify this process for you.
  1837. *
  1838. * @param {!string} name The name of the module to create or retrieve.
  1839. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1840. * unspecified then the module is being retrieved for further configuration.
  1841. * @param {Function=} configFn Optional configuration function for the module. Same as
  1842. * {@link angular.Module#config Module#config()}.
  1843. * @returns {angular.Module} new module with the {@link angular.Module} api.
  1844. */
  1845. return function module(name, requires, configFn) {
  1846. var assertNotHasOwnProperty = function(name, context) {
  1847. if (name === 'hasOwnProperty') {
  1848. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1849. }
  1850. };
  1851. assertNotHasOwnProperty(name, 'module');
  1852. if (requires && modules.hasOwnProperty(name)) {
  1853. modules[name] = null;
  1854. }
  1855. return ensure(modules, name, function() {
  1856. if (!requires) {
  1857. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1858. "the module name or forgot to load it. If registering a module ensure that you " +
  1859. "specify the dependencies as the second argument.", name);
  1860. }
  1861. /** @type {!Array.<Array.<*>>} */
  1862. var invokeQueue = [];
  1863. /** @type {!Array.<Function>} */
  1864. var configBlocks = [];
  1865. /** @type {!Array.<Function>} */
  1866. var runBlocks = [];
  1867. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1868. /** @type {angular.Module} */
  1869. var moduleInstance = {
  1870. // Private state
  1871. _invokeQueue: invokeQueue,
  1872. _configBlocks: configBlocks,
  1873. _runBlocks: runBlocks,
  1874. /**
  1875. * @ngdoc property
  1876. * @name angular.Module#requires
  1877. * @module ng
  1878. *
  1879. * @description
  1880. * Holds the list of modules which the injector will load before the current module is
  1881. * loaded.
  1882. */
  1883. requires: requires,
  1884. /**
  1885. * @ngdoc property
  1886. * @name angular.Module#name
  1887. * @module ng
  1888. *
  1889. * @description
  1890. * Name of the module.
  1891. */
  1892. name: name,
  1893. /**
  1894. * @ngdoc method
  1895. * @name angular.Module#provider
  1896. * @module ng
  1897. * @param {string} name service name
  1898. * @param {Function} providerType Construction function for creating new instance of the
  1899. * service.
  1900. * @description
  1901. * See {@link auto.$provide#provider $provide.provider()}.
  1902. */
  1903. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1904. /**
  1905. * @ngdoc method
  1906. * @name angular.Module#factory
  1907. * @module ng
  1908. * @param {string} name service name
  1909. * @param {Function} providerFunction Function for creating new instance of the service.
  1910. * @description
  1911. * See {@link auto.$provide#factory $provide.factory()}.
  1912. */
  1913. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1914. /**
  1915. * @ngdoc method
  1916. * @name angular.Module#service
  1917. * @module ng
  1918. * @param {string} name service name
  1919. * @param {Function} constructor A constructor function that will be instantiated.
  1920. * @description
  1921. * See {@link auto.$provide#service $provide.service()}.
  1922. */
  1923. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1924. /**
  1925. * @ngdoc method
  1926. * @name angular.Module#value
  1927. * @module ng
  1928. * @param {string} name service name
  1929. * @param {*} object Service instance object.
  1930. * @description
  1931. * See {@link auto.$provide#value $provide.value()}.
  1932. */
  1933. value: invokeLater('$provide', 'value'),
  1934. /**
  1935. * @ngdoc method
  1936. * @name angular.Module#constant
  1937. * @module ng
  1938. * @param {string} name constant name
  1939. * @param {*} object Constant value.
  1940. * @description
  1941. * Because the constants are fixed, they get applied before other provide methods.
  1942. * See {@link auto.$provide#constant $provide.constant()}.
  1943. */
  1944. constant: invokeLater('$provide', 'constant', 'unshift'),
  1945. /**
  1946. * @ngdoc method
  1947. * @name angular.Module#decorator
  1948. * @module ng
  1949. * @param {string} name The name of the service to decorate.
  1950. * @param {Function} decorFn This function will be invoked when the service needs to be
  1951. * instantiated and should return the decorated service instance.
  1952. * @description
  1953. * See {@link auto.$provide#decorator $provide.decorator()}.
  1954. */
  1955. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1956. /**
  1957. * @ngdoc method
  1958. * @name angular.Module#animation
  1959. * @module ng
  1960. * @param {string} name animation name
  1961. * @param {Function} animationFactory Factory function for creating new instance of an
  1962. * animation.
  1963. * @description
  1964. *
  1965. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1966. *
  1967. *
  1968. * Defines an animation hook that can be later used with
  1969. * {@link $animate $animate} service and directives that use this service.
  1970. *
  1971. * ```js
  1972. * module.animation('.animation-name', function($inject1, $inject2) {
  1973. * return {
  1974. * eventName : function(element, done) {
  1975. * //code to run the animation
  1976. * //once complete, then run done()
  1977. * return function cancellationFunction(element) {
  1978. * //code to cancel the animation
  1979. * }
  1980. * }
  1981. * }
  1982. * })
  1983. * ```
  1984. *
  1985. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1986. * {@link ngAnimate ngAnimate module} for more information.
  1987. */
  1988. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1989. /**
  1990. * @ngdoc method
  1991. * @name angular.Module#filter
  1992. * @module ng
  1993. * @param {string} name Filter name - this must be a valid angular expression identifier
  1994. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1995. * @description
  1996. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1997. *
  1998. * <div class="alert alert-warning">
  1999. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2000. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2001. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2002. * (`myapp_subsection_filterx`).
  2003. * </div>
  2004. */
  2005. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2006. /**
  2007. * @ngdoc method
  2008. * @name angular.Module#controller
  2009. * @module ng
  2010. * @param {string|Object} name Controller name, or an object map of controllers where the
  2011. * keys are the names and the values are the constructors.
  2012. * @param {Function} constructor Controller constructor function.
  2013. * @description
  2014. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2015. */
  2016. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2017. /**
  2018. * @ngdoc method
  2019. * @name angular.Module#directive
  2020. * @module ng
  2021. * @param {string|Object} name Directive name, or an object map of directives where the
  2022. * keys are the names and the values are the factories.
  2023. * @param {Function} directiveFactory Factory function for creating new instance of
  2024. * directives.
  2025. * @description
  2026. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2027. */
  2028. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2029. /**
  2030. * @ngdoc method
  2031. * @name angular.Module#component
  2032. * @module ng
  2033. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  2034. * @param {Object} options Component definition object (a simplified
  2035. * {@link ng.$compile#directive-definition-object directive definition object})
  2036. *
  2037. * @description
  2038. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2039. */
  2040. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2041. /**
  2042. * @ngdoc method
  2043. * @name angular.Module#config
  2044. * @module ng
  2045. * @param {Function} configFn Execute this function on module load. Useful for service
  2046. * configuration.
  2047. * @description
  2048. * Use this method to register work which needs to be performed on module loading.
  2049. * For more about how to configure services, see
  2050. * {@link providers#provider-recipe Provider Recipe}.
  2051. */
  2052. config: config,
  2053. /**
  2054. * @ngdoc method
  2055. * @name angular.Module#run
  2056. * @module ng
  2057. * @param {Function} initializationFn Execute this function after injector creation.
  2058. * Useful for application initialization.
  2059. * @description
  2060. * Use this method to register work which should be performed when the injector is done
  2061. * loading all modules.
  2062. */
  2063. run: function(block) {
  2064. runBlocks.push(block);
  2065. return this;
  2066. }
  2067. };
  2068. if (configFn) {
  2069. config(configFn);
  2070. }
  2071. return moduleInstance;
  2072. /**
  2073. * @param {string} provider
  2074. * @param {string} method
  2075. * @param {String=} insertMethod
  2076. * @returns {angular.Module}
  2077. */
  2078. function invokeLater(provider, method, insertMethod, queue) {
  2079. if (!queue) queue = invokeQueue;
  2080. return function() {
  2081. queue[insertMethod || 'push']([provider, method, arguments]);
  2082. return moduleInstance;
  2083. };
  2084. }
  2085. /**
  2086. * @param {string} provider
  2087. * @param {string} method
  2088. * @returns {angular.Module}
  2089. */
  2090. function invokeLaterAndSetModuleName(provider, method) {
  2091. return function(recipeName, factoryFunction) {
  2092. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2093. invokeQueue.push([provider, method, arguments]);
  2094. return moduleInstance;
  2095. };
  2096. }
  2097. });
  2098. };
  2099. });
  2100. }
  2101. /* global shallowCopy: true */
  2102. /**
  2103. * Creates a shallow copy of an object, an array or a primitive.
  2104. *
  2105. * Assumes that there are no proto properties for objects.
  2106. */
  2107. function shallowCopy(src, dst) {
  2108. if (isArray(src)) {
  2109. dst = dst || [];
  2110. for (var i = 0, ii = src.length; i < ii; i++) {
  2111. dst[i] = src[i];
  2112. }
  2113. } else if (isObject(src)) {
  2114. dst = dst || {};
  2115. for (var key in src) {
  2116. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2117. dst[key] = src[key];
  2118. }
  2119. }
  2120. }
  2121. return dst || src;
  2122. }
  2123. /* global toDebugString: true */
  2124. function serializeObject(obj) {
  2125. var seen = [];
  2126. return JSON.stringify(obj, function(key, val) {
  2127. val = toJsonReplacer(key, val);
  2128. if (isObject(val)) {
  2129. if (seen.indexOf(val) >= 0) return '...';
  2130. seen.push(val);
  2131. }
  2132. return val;
  2133. });
  2134. }
  2135. function toDebugString(obj) {
  2136. if (typeof obj === 'function') {
  2137. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2138. } else if (isUndefined(obj)) {
  2139. return 'undefined';
  2140. } else if (typeof obj !== 'string') {
  2141. return serializeObject(obj);
  2142. }
  2143. return obj;
  2144. }
  2145. /* global angularModule: true,
  2146. version: true,
  2147. $CompileProvider,
  2148. htmlAnchorDirective,
  2149. inputDirective,
  2150. inputDirective,
  2151. formDirective,
  2152. scriptDirective,
  2153. selectDirective,
  2154. styleDirective,
  2155. optionDirective,
  2156. ngBindDirective,
  2157. ngBindHtmlDirective,
  2158. ngBindTemplateDirective,
  2159. ngClassDirective,
  2160. ngClassEvenDirective,
  2161. ngClassOddDirective,
  2162. ngCloakDirective,
  2163. ngControllerDirective,
  2164. ngFormDirective,
  2165. ngHideDirective,
  2166. ngIfDirective,
  2167. ngIncludeDirective,
  2168. ngIncludeFillContentDirective,
  2169. ngInitDirective,
  2170. ngNonBindableDirective,
  2171. ngPluralizeDirective,
  2172. ngRepeatDirective,
  2173. ngShowDirective,
  2174. ngStyleDirective,
  2175. ngSwitchDirective,
  2176. ngSwitchWhenDirective,
  2177. ngSwitchDefaultDirective,
  2178. ngOptionsDirective,
  2179. ngTranscludeDirective,
  2180. ngModelDirective,
  2181. ngListDirective,
  2182. ngChangeDirective,
  2183. patternDirective,
  2184. patternDirective,
  2185. requiredDirective,
  2186. requiredDirective,
  2187. minlengthDirective,
  2188. minlengthDirective,
  2189. maxlengthDirective,
  2190. maxlengthDirective,
  2191. ngValueDirective,
  2192. ngModelOptionsDirective,
  2193. ngAttributeAliasDirectives,
  2194. ngEventDirectives,
  2195. $AnchorScrollProvider,
  2196. $AnimateProvider,
  2197. $CoreAnimateCssProvider,
  2198. $$CoreAnimateJsProvider,
  2199. $$CoreAnimateQueueProvider,
  2200. $$AnimateRunnerFactoryProvider,
  2201. $$AnimateAsyncRunFactoryProvider,
  2202. $BrowserProvider,
  2203. $CacheFactoryProvider,
  2204. $ControllerProvider,
  2205. $DateProvider,
  2206. $DocumentProvider,
  2207. $ExceptionHandlerProvider,
  2208. $FilterProvider,
  2209. $$ForceReflowProvider,
  2210. $InterpolateProvider,
  2211. $IntervalProvider,
  2212. $$HashMapProvider,
  2213. $HttpProvider,
  2214. $HttpParamSerializerProvider,
  2215. $HttpParamSerializerJQLikeProvider,
  2216. $HttpBackendProvider,
  2217. $xhrFactoryProvider,
  2218. $jsonpCallbacksProvider,
  2219. $LocationProvider,
  2220. $LogProvider,
  2221. $ParseProvider,
  2222. $RootScopeProvider,
  2223. $QProvider,
  2224. $$QProvider,
  2225. $$SanitizeUriProvider,
  2226. $SceProvider,
  2227. $SceDelegateProvider,
  2228. $SnifferProvider,
  2229. $TemplateCacheProvider,
  2230. $TemplateRequestProvider,
  2231. $$TestabilityProvider,
  2232. $TimeoutProvider,
  2233. $$RAFProvider,
  2234. $WindowProvider,
  2235. $$jqLiteProvider,
  2236. $$CookieReaderProvider
  2237. */
  2238. /**
  2239. * @ngdoc object
  2240. * @name angular.version
  2241. * @module ng
  2242. * @description
  2243. * An object that contains information about the current AngularJS version.
  2244. *
  2245. * This object has the following properties:
  2246. *
  2247. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2248. * - `major` – `{number}` – Major version number, such as "0".
  2249. * - `minor` – `{number}` – Minor version number, such as "9".
  2250. * - `dot` – `{number}` – Dot version number, such as "18".
  2251. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2252. */
  2253. var version = {
  2254. full: '1.5.8', // all of these placeholder strings will be replaced by grunt's
  2255. major: 1, // package task
  2256. minor: 5,
  2257. dot: 8,
  2258. codeName: 'arbitrary-fallbacks'
  2259. };
  2260. function publishExternalAPI(angular) {
  2261. extend(angular, {
  2262. 'bootstrap': bootstrap,
  2263. 'copy': copy,
  2264. 'extend': extend,
  2265. 'merge': merge,
  2266. 'equals': equals,
  2267. 'element': jqLite,
  2268. 'forEach': forEach,
  2269. 'injector': createInjector,
  2270. 'noop': noop,
  2271. 'bind': bind,
  2272. 'toJson': toJson,
  2273. 'fromJson': fromJson,
  2274. 'identity': identity,
  2275. 'isUndefined': isUndefined,
  2276. 'isDefined': isDefined,
  2277. 'isString': isString,
  2278. 'isFunction': isFunction,
  2279. 'isObject': isObject,
  2280. 'isNumber': isNumber,
  2281. 'isElement': isElement,
  2282. 'isArray': isArray,
  2283. 'version': version,
  2284. 'isDate': isDate,
  2285. 'lowercase': lowercase,
  2286. 'uppercase': uppercase,
  2287. 'callbacks': {$$counter: 0},
  2288. 'getTestability': getTestability,
  2289. '$$minErr': minErr,
  2290. '$$csp': csp,
  2291. 'reloadWithDebugInfo': reloadWithDebugInfo
  2292. });
  2293. angularModule = setupModuleLoader(window);
  2294. angularModule('ng', ['ngLocale'], ['$provide',
  2295. function ngModule($provide) {
  2296. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2297. $provide.provider({
  2298. $$sanitizeUri: $$SanitizeUriProvider
  2299. });
  2300. $provide.provider('$compile', $CompileProvider).
  2301. directive({
  2302. a: htmlAnchorDirective,
  2303. input: inputDirective,
  2304. textarea: inputDirective,
  2305. form: formDirective,
  2306. script: scriptDirective,
  2307. select: selectDirective,
  2308. style: styleDirective,
  2309. option: optionDirective,
  2310. ngBind: ngBindDirective,
  2311. ngBindHtml: ngBindHtmlDirective,
  2312. ngBindTemplate: ngBindTemplateDirective,
  2313. ngClass: ngClassDirective,
  2314. ngClassEven: ngClassEvenDirective,
  2315. ngClassOdd: ngClassOddDirective,
  2316. ngCloak: ngCloakDirective,
  2317. ngController: ngControllerDirective,
  2318. ngForm: ngFormDirective,
  2319. ngHide: ngHideDirective,
  2320. ngIf: ngIfDirective,
  2321. ngInclude: ngIncludeDirective,
  2322. ngInit: ngInitDirective,
  2323. ngNonBindable: ngNonBindableDirective,
  2324. ngPluralize: ngPluralizeDirective,
  2325. ngRepeat: ngRepeatDirective,
  2326. ngShow: ngShowDirective,
  2327. ngStyle: ngStyleDirective,
  2328. ngSwitch: ngSwitchDirective,
  2329. ngSwitchWhen: ngSwitchWhenDirective,
  2330. ngSwitchDefault: ngSwitchDefaultDirective,
  2331. ngOptions: ngOptionsDirective,
  2332. ngTransclude: ngTranscludeDirective,
  2333. ngModel: ngModelDirective,
  2334. ngList: ngListDirective,
  2335. ngChange: ngChangeDirective,
  2336. pattern: patternDirective,
  2337. ngPattern: patternDirective,
  2338. required: requiredDirective,
  2339. ngRequired: requiredDirective,
  2340. minlength: minlengthDirective,
  2341. ngMinlength: minlengthDirective,
  2342. maxlength: maxlengthDirective,
  2343. ngMaxlength: maxlengthDirective,
  2344. ngValue: ngValueDirective,
  2345. ngModelOptions: ngModelOptionsDirective
  2346. }).
  2347. directive({
  2348. ngInclude: ngIncludeFillContentDirective
  2349. }).
  2350. directive(ngAttributeAliasDirectives).
  2351. directive(ngEventDirectives);
  2352. $provide.provider({
  2353. $anchorScroll: $AnchorScrollProvider,
  2354. $animate: $AnimateProvider,
  2355. $animateCss: $CoreAnimateCssProvider,
  2356. $$animateJs: $$CoreAnimateJsProvider,
  2357. $$animateQueue: $$CoreAnimateQueueProvider,
  2358. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2359. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2360. $browser: $BrowserProvider,
  2361. $cacheFactory: $CacheFactoryProvider,
  2362. $controller: $ControllerProvider,
  2363. $document: $DocumentProvider,
  2364. $exceptionHandler: $ExceptionHandlerProvider,
  2365. $filter: $FilterProvider,
  2366. $$forceReflow: $$ForceReflowProvider,
  2367. $interpolate: $InterpolateProvider,
  2368. $interval: $IntervalProvider,
  2369. $http: $HttpProvider,
  2370. $httpParamSerializer: $HttpParamSerializerProvider,
  2371. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2372. $httpBackend: $HttpBackendProvider,
  2373. $xhrFactory: $xhrFactoryProvider,
  2374. $jsonpCallbacks: $jsonpCallbacksProvider,
  2375. $location: $LocationProvider,
  2376. $log: $LogProvider,
  2377. $parse: $ParseProvider,
  2378. $rootScope: $RootScopeProvider,
  2379. $q: $QProvider,
  2380. $$q: $$QProvider,
  2381. $sce: $SceProvider,
  2382. $sceDelegate: $SceDelegateProvider,
  2383. $sniffer: $SnifferProvider,
  2384. $templateCache: $TemplateCacheProvider,
  2385. $templateRequest: $TemplateRequestProvider,
  2386. $$testability: $$TestabilityProvider,
  2387. $timeout: $TimeoutProvider,
  2388. $window: $WindowProvider,
  2389. $$rAF: $$RAFProvider,
  2390. $$jqLite: $$jqLiteProvider,
  2391. $$HashMap: $$HashMapProvider,
  2392. $$cookieReader: $$CookieReaderProvider
  2393. });
  2394. }
  2395. ]);
  2396. }
  2397. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2398. * Any commits to this file should be reviewed with security in mind. *
  2399. * Changes to this file can potentially create security vulnerabilities. *
  2400. * An approval from 2 Core members with history of modifying *
  2401. * this file is required. *
  2402. * *
  2403. * Does the change somehow allow for arbitrary javascript to be executed? *
  2404. * Or allows for someone to change the prototype of built-in objects? *
  2405. * Or gives undesired access to variables likes document or window? *
  2406. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2407. /* global JQLitePrototype: true,
  2408. addEventListenerFn: true,
  2409. removeEventListenerFn: true,
  2410. BOOLEAN_ATTR: true,
  2411. ALIASED_ATTR: true,
  2412. */
  2413. //////////////////////////////////
  2414. //JQLite
  2415. //////////////////////////////////
  2416. /**
  2417. * @ngdoc function
  2418. * @name angular.element
  2419. * @module ng
  2420. * @kind function
  2421. *
  2422. * @description
  2423. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2424. *
  2425. * If jQuery is available, `angular.element` is an alias for the
  2426. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2427. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2428. *
  2429. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2430. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2431. * commonly needed functionality with the goal of having a very small footprint.
  2432. *
  2433. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2434. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2435. * specific version of jQuery if multiple versions exist on the page.
  2436. *
  2437. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2438. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2439. *
  2440. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2441. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2442. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2443. *
  2444. * ## Angular's jqLite
  2445. * jqLite provides only the following jQuery methods:
  2446. *
  2447. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2448. * - [`after()`](http://api.jquery.com/after/)
  2449. * - [`append()`](http://api.jquery.com/append/)
  2450. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2451. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2452. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2453. * - [`clone()`](http://api.jquery.com/clone/)
  2454. * - [`contents()`](http://api.jquery.com/contents/)
  2455. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2456. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2457. * - [`data()`](http://api.jquery.com/data/)
  2458. * - [`detach()`](http://api.jquery.com/detach/)
  2459. * - [`empty()`](http://api.jquery.com/empty/)
  2460. * - [`eq()`](http://api.jquery.com/eq/)
  2461. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2462. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2463. * - [`html()`](http://api.jquery.com/html/)
  2464. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2465. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2466. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2467. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2468. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2469. * - [`prepend()`](http://api.jquery.com/prepend/)
  2470. * - [`prop()`](http://api.jquery.com/prop/)
  2471. * - [`ready()`](http://api.jquery.com/ready/)
  2472. * - [`remove()`](http://api.jquery.com/remove/)
  2473. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2474. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2475. * - [`removeData()`](http://api.jquery.com/removeData/)
  2476. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2477. * - [`text()`](http://api.jquery.com/text/)
  2478. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2479. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2480. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  2481. * - [`val()`](http://api.jquery.com/val/)
  2482. * - [`wrap()`](http://api.jquery.com/wrap/)
  2483. *
  2484. * ## jQuery/jqLite Extras
  2485. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2486. *
  2487. * ### Events
  2488. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2489. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2490. * element before it is removed.
  2491. *
  2492. * ### Methods
  2493. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2494. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2495. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2496. * `'ngModel'`).
  2497. * - `injector()` - retrieves the injector of the current element or its parent.
  2498. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2499. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2500. * be enabled.
  2501. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2502. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2503. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2504. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2505. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2506. * parent element is reached.
  2507. *
  2508. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2509. * https://github.com/angular/angular.js/issues/14251 for more information.
  2510. *
  2511. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2512. * @returns {Object} jQuery object.
  2513. */
  2514. JQLite.expando = 'ng339';
  2515. var jqCache = JQLite.cache = {},
  2516. jqId = 1,
  2517. addEventListenerFn = function(element, type, fn) {
  2518. element.addEventListener(type, fn, false);
  2519. },
  2520. removeEventListenerFn = function(element, type, fn) {
  2521. element.removeEventListener(type, fn, false);
  2522. };
  2523. /*
  2524. * !!! This is an undocumented "private" function !!!
  2525. */
  2526. JQLite._data = function(node) {
  2527. //jQuery always returns an object on cache miss
  2528. return this.cache[node[this.expando]] || {};
  2529. };
  2530. function jqNextId() { return ++jqId; }
  2531. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2532. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2533. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2534. var jqLiteMinErr = minErr('jqLite');
  2535. /**
  2536. * Converts snake_case to camelCase.
  2537. * Also there is special case for Moz prefix starting with upper case letter.
  2538. * @param name Name to normalize
  2539. */
  2540. function camelCase(name) {
  2541. return name.
  2542. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2543. return offset ? letter.toUpperCase() : letter;
  2544. }).
  2545. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2546. }
  2547. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2548. var HTML_REGEXP = /<|&#?\w+;/;
  2549. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2550. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2551. var wrapMap = {
  2552. 'option': [1, '<select multiple="multiple">', '</select>'],
  2553. 'thead': [1, '<table>', '</table>'],
  2554. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2555. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2556. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2557. '_default': [0, "", ""]
  2558. };
  2559. wrapMap.optgroup = wrapMap.option;
  2560. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2561. wrapMap.th = wrapMap.td;
  2562. function jqLiteIsTextNode(html) {
  2563. return !HTML_REGEXP.test(html);
  2564. }
  2565. function jqLiteAcceptsData(node) {
  2566. // The window object can accept data but has no nodeType
  2567. // Otherwise we are only interested in elements (1) and documents (9)
  2568. var nodeType = node.nodeType;
  2569. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2570. }
  2571. function jqLiteHasData(node) {
  2572. for (var key in jqCache[node.ng339]) {
  2573. return true;
  2574. }
  2575. return false;
  2576. }
  2577. function jqLiteCleanData(nodes) {
  2578. for (var i = 0, ii = nodes.length; i < ii; i++) {
  2579. jqLiteRemoveData(nodes[i]);
  2580. }
  2581. }
  2582. function jqLiteBuildFragment(html, context) {
  2583. var tmp, tag, wrap,
  2584. fragment = context.createDocumentFragment(),
  2585. nodes = [], i;
  2586. if (jqLiteIsTextNode(html)) {
  2587. // Convert non-html into a text node
  2588. nodes.push(context.createTextNode(html));
  2589. } else {
  2590. // Convert html into DOM nodes
  2591. tmp = fragment.appendChild(context.createElement("div"));
  2592. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2593. wrap = wrapMap[tag] || wrapMap._default;
  2594. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2595. // Descend through wrappers to the right content
  2596. i = wrap[0];
  2597. while (i--) {
  2598. tmp = tmp.lastChild;
  2599. }
  2600. nodes = concat(nodes, tmp.childNodes);
  2601. tmp = fragment.firstChild;
  2602. tmp.textContent = "";
  2603. }
  2604. // Remove wrapper from fragment
  2605. fragment.textContent = "";
  2606. fragment.innerHTML = ""; // Clear inner HTML
  2607. forEach(nodes, function(node) {
  2608. fragment.appendChild(node);
  2609. });
  2610. return fragment;
  2611. }
  2612. function jqLiteParseHTML(html, context) {
  2613. context = context || window.document;
  2614. var parsed;
  2615. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2616. return [context.createElement(parsed[1])];
  2617. }
  2618. if ((parsed = jqLiteBuildFragment(html, context))) {
  2619. return parsed.childNodes;
  2620. }
  2621. return [];
  2622. }
  2623. function jqLiteWrapNode(node, wrapper) {
  2624. var parent = node.parentNode;
  2625. if (parent) {
  2626. parent.replaceChild(wrapper, node);
  2627. }
  2628. wrapper.appendChild(node);
  2629. }
  2630. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2631. var jqLiteContains = window.Node.prototype.contains || function(arg) {
  2632. // jshint bitwise: false
  2633. return !!(this.compareDocumentPosition(arg) & 16);
  2634. // jshint bitwise: true
  2635. };
  2636. /////////////////////////////////////////////
  2637. function JQLite(element) {
  2638. if (element instanceof JQLite) {
  2639. return element;
  2640. }
  2641. var argIsString;
  2642. if (isString(element)) {
  2643. element = trim(element);
  2644. argIsString = true;
  2645. }
  2646. if (!(this instanceof JQLite)) {
  2647. if (argIsString && element.charAt(0) != '<') {
  2648. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2649. }
  2650. return new JQLite(element);
  2651. }
  2652. if (argIsString) {
  2653. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2654. } else {
  2655. jqLiteAddNodes(this, element);
  2656. }
  2657. }
  2658. function jqLiteClone(element) {
  2659. return element.cloneNode(true);
  2660. }
  2661. function jqLiteDealoc(element, onlyDescendants) {
  2662. if (!onlyDescendants) jqLiteRemoveData(element);
  2663. if (element.querySelectorAll) {
  2664. var descendants = element.querySelectorAll('*');
  2665. for (var i = 0, l = descendants.length; i < l; i++) {
  2666. jqLiteRemoveData(descendants[i]);
  2667. }
  2668. }
  2669. }
  2670. function jqLiteOff(element, type, fn, unsupported) {
  2671. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2672. var expandoStore = jqLiteExpandoStore(element);
  2673. var events = expandoStore && expandoStore.events;
  2674. var handle = expandoStore && expandoStore.handle;
  2675. if (!handle) return; //no listeners registered
  2676. if (!type) {
  2677. for (type in events) {
  2678. if (type !== '$destroy') {
  2679. removeEventListenerFn(element, type, handle);
  2680. }
  2681. delete events[type];
  2682. }
  2683. } else {
  2684. var removeHandler = function(type) {
  2685. var listenerFns = events[type];
  2686. if (isDefined(fn)) {
  2687. arrayRemove(listenerFns || [], fn);
  2688. }
  2689. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2690. removeEventListenerFn(element, type, handle);
  2691. delete events[type];
  2692. }
  2693. };
  2694. forEach(type.split(' '), function(type) {
  2695. removeHandler(type);
  2696. if (MOUSE_EVENT_MAP[type]) {
  2697. removeHandler(MOUSE_EVENT_MAP[type]);
  2698. }
  2699. });
  2700. }
  2701. }
  2702. function jqLiteRemoveData(element, name) {
  2703. var expandoId = element.ng339;
  2704. var expandoStore = expandoId && jqCache[expandoId];
  2705. if (expandoStore) {
  2706. if (name) {
  2707. delete expandoStore.data[name];
  2708. return;
  2709. }
  2710. if (expandoStore.handle) {
  2711. if (expandoStore.events.$destroy) {
  2712. expandoStore.handle({}, '$destroy');
  2713. }
  2714. jqLiteOff(element);
  2715. }
  2716. delete jqCache[expandoId];
  2717. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2718. }
  2719. }
  2720. function jqLiteExpandoStore(element, createIfNecessary) {
  2721. var expandoId = element.ng339,
  2722. expandoStore = expandoId && jqCache[expandoId];
  2723. if (createIfNecessary && !expandoStore) {
  2724. element.ng339 = expandoId = jqNextId();
  2725. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2726. }
  2727. return expandoStore;
  2728. }
  2729. function jqLiteData(element, key, value) {
  2730. if (jqLiteAcceptsData(element)) {
  2731. var isSimpleSetter = isDefined(value);
  2732. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2733. var massGetter = !key;
  2734. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2735. var data = expandoStore && expandoStore.data;
  2736. if (isSimpleSetter) { // data('key', value)
  2737. data[key] = value;
  2738. } else {
  2739. if (massGetter) { // data()
  2740. return data;
  2741. } else {
  2742. if (isSimpleGetter) { // data('key')
  2743. // don't force creation of expandoStore if it doesn't exist yet
  2744. return data && data[key];
  2745. } else { // mass-setter: data({key1: val1, key2: val2})
  2746. extend(data, key);
  2747. }
  2748. }
  2749. }
  2750. }
  2751. }
  2752. function jqLiteHasClass(element, selector) {
  2753. if (!element.getAttribute) return false;
  2754. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2755. indexOf(" " + selector + " ") > -1);
  2756. }
  2757. function jqLiteRemoveClass(element, cssClasses) {
  2758. if (cssClasses && element.setAttribute) {
  2759. forEach(cssClasses.split(' '), function(cssClass) {
  2760. element.setAttribute('class', trim(
  2761. (" " + (element.getAttribute('class') || '') + " ")
  2762. .replace(/[\n\t]/g, " ")
  2763. .replace(" " + trim(cssClass) + " ", " "))
  2764. );
  2765. });
  2766. }
  2767. }
  2768. function jqLiteAddClass(element, cssClasses) {
  2769. if (cssClasses && element.setAttribute) {
  2770. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2771. .replace(/[\n\t]/g, " ");
  2772. forEach(cssClasses.split(' '), function(cssClass) {
  2773. cssClass = trim(cssClass);
  2774. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2775. existingClasses += cssClass + ' ';
  2776. }
  2777. });
  2778. element.setAttribute('class', trim(existingClasses));
  2779. }
  2780. }
  2781. function jqLiteAddNodes(root, elements) {
  2782. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2783. if (elements) {
  2784. // if a Node (the most common case)
  2785. if (elements.nodeType) {
  2786. root[root.length++] = elements;
  2787. } else {
  2788. var length = elements.length;
  2789. // if an Array or NodeList and not a Window
  2790. if (typeof length === 'number' && elements.window !== elements) {
  2791. if (length) {
  2792. for (var i = 0; i < length; i++) {
  2793. root[root.length++] = elements[i];
  2794. }
  2795. }
  2796. } else {
  2797. root[root.length++] = elements;
  2798. }
  2799. }
  2800. }
  2801. }
  2802. function jqLiteController(element, name) {
  2803. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2804. }
  2805. function jqLiteInheritedData(element, name, value) {
  2806. // if element is the document object work with the html element instead
  2807. // this makes $(document).scope() possible
  2808. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2809. element = element.documentElement;
  2810. }
  2811. var names = isArray(name) ? name : [name];
  2812. while (element) {
  2813. for (var i = 0, ii = names.length; i < ii; i++) {
  2814. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  2815. }
  2816. // If dealing with a document fragment node with a host element, and no parent, use the host
  2817. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2818. // to lookup parent controllers.
  2819. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2820. }
  2821. }
  2822. function jqLiteEmpty(element) {
  2823. jqLiteDealoc(element, true);
  2824. while (element.firstChild) {
  2825. element.removeChild(element.firstChild);
  2826. }
  2827. }
  2828. function jqLiteRemove(element, keepData) {
  2829. if (!keepData) jqLiteDealoc(element);
  2830. var parent = element.parentNode;
  2831. if (parent) parent.removeChild(element);
  2832. }
  2833. function jqLiteDocumentLoaded(action, win) {
  2834. win = win || window;
  2835. if (win.document.readyState === 'complete') {
  2836. // Force the action to be run async for consistent behavior
  2837. // from the action's point of view
  2838. // i.e. it will definitely not be in a $apply
  2839. win.setTimeout(action);
  2840. } else {
  2841. // No need to unbind this handler as load is only ever called once
  2842. jqLite(win).on('load', action);
  2843. }
  2844. }
  2845. //////////////////////////////////////////
  2846. // Functions which are declared directly.
  2847. //////////////////////////////////////////
  2848. var JQLitePrototype = JQLite.prototype = {
  2849. ready: function(fn) {
  2850. var fired = false;
  2851. function trigger() {
  2852. if (fired) return;
  2853. fired = true;
  2854. fn();
  2855. }
  2856. // check if document is already loaded
  2857. if (window.document.readyState === 'complete') {
  2858. window.setTimeout(trigger);
  2859. } else {
  2860. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2861. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2862. // jshint -W064
  2863. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2864. // jshint +W064
  2865. }
  2866. },
  2867. toString: function() {
  2868. var value = [];
  2869. forEach(this, function(e) { value.push('' + e);});
  2870. return '[' + value.join(', ') + ']';
  2871. },
  2872. eq: function(index) {
  2873. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2874. },
  2875. length: 0,
  2876. push: push,
  2877. sort: [].sort,
  2878. splice: [].splice
  2879. };
  2880. //////////////////////////////////////////
  2881. // Functions iterating getter/setters.
  2882. // these functions return self on setter and
  2883. // value on get.
  2884. //////////////////////////////////////////
  2885. var BOOLEAN_ATTR = {};
  2886. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2887. BOOLEAN_ATTR[lowercase(value)] = value;
  2888. });
  2889. var BOOLEAN_ELEMENTS = {};
  2890. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2891. BOOLEAN_ELEMENTS[value] = true;
  2892. });
  2893. var ALIASED_ATTR = {
  2894. 'ngMinlength': 'minlength',
  2895. 'ngMaxlength': 'maxlength',
  2896. 'ngMin': 'min',
  2897. 'ngMax': 'max',
  2898. 'ngPattern': 'pattern'
  2899. };
  2900. function getBooleanAttrName(element, name) {
  2901. // check dom last since we will most likely fail on name
  2902. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2903. // booleanAttr is here twice to minimize DOM access
  2904. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2905. }
  2906. function getAliasedAttrName(name) {
  2907. return ALIASED_ATTR[name];
  2908. }
  2909. forEach({
  2910. data: jqLiteData,
  2911. removeData: jqLiteRemoveData,
  2912. hasData: jqLiteHasData,
  2913. cleanData: jqLiteCleanData
  2914. }, function(fn, name) {
  2915. JQLite[name] = fn;
  2916. });
  2917. forEach({
  2918. data: jqLiteData,
  2919. inheritedData: jqLiteInheritedData,
  2920. scope: function(element) {
  2921. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2922. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2923. },
  2924. isolateScope: function(element) {
  2925. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2926. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2927. },
  2928. controller: jqLiteController,
  2929. injector: function(element) {
  2930. return jqLiteInheritedData(element, '$injector');
  2931. },
  2932. removeAttr: function(element, name) {
  2933. element.removeAttribute(name);
  2934. },
  2935. hasClass: jqLiteHasClass,
  2936. css: function(element, name, value) {
  2937. name = camelCase(name);
  2938. if (isDefined(value)) {
  2939. element.style[name] = value;
  2940. } else {
  2941. return element.style[name];
  2942. }
  2943. },
  2944. attr: function(element, name, value) {
  2945. var nodeType = element.nodeType;
  2946. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2947. return;
  2948. }
  2949. var lowercasedName = lowercase(name);
  2950. if (BOOLEAN_ATTR[lowercasedName]) {
  2951. if (isDefined(value)) {
  2952. if (!!value) {
  2953. element[name] = true;
  2954. element.setAttribute(name, lowercasedName);
  2955. } else {
  2956. element[name] = false;
  2957. element.removeAttribute(lowercasedName);
  2958. }
  2959. } else {
  2960. return (element[name] ||
  2961. (element.attributes.getNamedItem(name) || noop).specified)
  2962. ? lowercasedName
  2963. : undefined;
  2964. }
  2965. } else if (isDefined(value)) {
  2966. element.setAttribute(name, value);
  2967. } else if (element.getAttribute) {
  2968. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2969. // some elements (e.g. Document) don't have get attribute, so return undefined
  2970. var ret = element.getAttribute(name, 2);
  2971. // normalize non-existing attributes to undefined (as jQuery)
  2972. return ret === null ? undefined : ret;
  2973. }
  2974. },
  2975. prop: function(element, name, value) {
  2976. if (isDefined(value)) {
  2977. element[name] = value;
  2978. } else {
  2979. return element[name];
  2980. }
  2981. },
  2982. text: (function() {
  2983. getText.$dv = '';
  2984. return getText;
  2985. function getText(element, value) {
  2986. if (isUndefined(value)) {
  2987. var nodeType = element.nodeType;
  2988. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2989. }
  2990. element.textContent = value;
  2991. }
  2992. })(),
  2993. val: function(element, value) {
  2994. if (isUndefined(value)) {
  2995. if (element.multiple && nodeName_(element) === 'select') {
  2996. var result = [];
  2997. forEach(element.options, function(option) {
  2998. if (option.selected) {
  2999. result.push(option.value || option.text);
  3000. }
  3001. });
  3002. return result.length === 0 ? null : result;
  3003. }
  3004. return element.value;
  3005. }
  3006. element.value = value;
  3007. },
  3008. html: function(element, value) {
  3009. if (isUndefined(value)) {
  3010. return element.innerHTML;
  3011. }
  3012. jqLiteDealoc(element, true);
  3013. element.innerHTML = value;
  3014. },
  3015. empty: jqLiteEmpty
  3016. }, function(fn, name) {
  3017. /**
  3018. * Properties: writes return selection, reads return first value
  3019. */
  3020. JQLite.prototype[name] = function(arg1, arg2) {
  3021. var i, key;
  3022. var nodeCount = this.length;
  3023. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3024. // in a way that survives minification.
  3025. // jqLiteEmpty takes no arguments but is a setter.
  3026. if (fn !== jqLiteEmpty &&
  3027. (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3028. if (isObject(arg1)) {
  3029. // we are a write, but the object properties are the key/values
  3030. for (i = 0; i < nodeCount; i++) {
  3031. if (fn === jqLiteData) {
  3032. // data() takes the whole object in jQuery
  3033. fn(this[i], arg1);
  3034. } else {
  3035. for (key in arg1) {
  3036. fn(this[i], key, arg1[key]);
  3037. }
  3038. }
  3039. }
  3040. // return self for chaining
  3041. return this;
  3042. } else {
  3043. // we are a read, so read the first child.
  3044. // TODO: do we still need this?
  3045. var value = fn.$dv;
  3046. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3047. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3048. for (var j = 0; j < jj; j++) {
  3049. var nodeValue = fn(this[j], arg1, arg2);
  3050. value = value ? value + nodeValue : nodeValue;
  3051. }
  3052. return value;
  3053. }
  3054. } else {
  3055. // we are a write, so apply to all children
  3056. for (i = 0; i < nodeCount; i++) {
  3057. fn(this[i], arg1, arg2);
  3058. }
  3059. // return self for chaining
  3060. return this;
  3061. }
  3062. };
  3063. });
  3064. function createEventHandler(element, events) {
  3065. var eventHandler = function(event, type) {
  3066. // jQuery specific api
  3067. event.isDefaultPrevented = function() {
  3068. return event.defaultPrevented;
  3069. };
  3070. var eventFns = events[type || event.type];
  3071. var eventFnsLength = eventFns ? eventFns.length : 0;
  3072. if (!eventFnsLength) return;
  3073. if (isUndefined(event.immediatePropagationStopped)) {
  3074. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3075. event.stopImmediatePropagation = function() {
  3076. event.immediatePropagationStopped = true;
  3077. if (event.stopPropagation) {
  3078. event.stopPropagation();
  3079. }
  3080. if (originalStopImmediatePropagation) {
  3081. originalStopImmediatePropagation.call(event);
  3082. }
  3083. };
  3084. }
  3085. event.isImmediatePropagationStopped = function() {
  3086. return event.immediatePropagationStopped === true;
  3087. };
  3088. // Some events have special handlers that wrap the real handler
  3089. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3090. // Copy event handlers in case event handlers array is modified during execution.
  3091. if ((eventFnsLength > 1)) {
  3092. eventFns = shallowCopy(eventFns);
  3093. }
  3094. for (var i = 0; i < eventFnsLength; i++) {
  3095. if (!event.isImmediatePropagationStopped()) {
  3096. handlerWrapper(element, event, eventFns[i]);
  3097. }
  3098. }
  3099. };
  3100. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3101. // events on `element`
  3102. eventHandler.elem = element;
  3103. return eventHandler;
  3104. }
  3105. function defaultHandlerWrapper(element, event, handler) {
  3106. handler.call(element, event);
  3107. }
  3108. function specialMouseHandlerWrapper(target, event, handler) {
  3109. // Refer to jQuery's implementation of mouseenter & mouseleave
  3110. // Read about mouseenter and mouseleave:
  3111. // http://www.quirksmode.org/js/events_mouse.html#link8
  3112. var related = event.relatedTarget;
  3113. // For mousenter/leave call the handler if related is outside the target.
  3114. // NB: No relatedTarget if the mouse left/entered the browser window
  3115. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3116. handler.call(target, event);
  3117. }
  3118. }
  3119. //////////////////////////////////////////
  3120. // Functions iterating traversal.
  3121. // These functions chain results into a single
  3122. // selector.
  3123. //////////////////////////////////////////
  3124. forEach({
  3125. removeData: jqLiteRemoveData,
  3126. on: function jqLiteOn(element, type, fn, unsupported) {
  3127. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3128. // Do not add event handlers to non-elements because they will not be cleaned up.
  3129. if (!jqLiteAcceptsData(element)) {
  3130. return;
  3131. }
  3132. var expandoStore = jqLiteExpandoStore(element, true);
  3133. var events = expandoStore.events;
  3134. var handle = expandoStore.handle;
  3135. if (!handle) {
  3136. handle = expandoStore.handle = createEventHandler(element, events);
  3137. }
  3138. // http://jsperf.com/string-indexof-vs-split
  3139. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3140. var i = types.length;
  3141. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3142. var eventFns = events[type];
  3143. if (!eventFns) {
  3144. eventFns = events[type] = [];
  3145. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3146. if (type !== '$destroy' && !noEventListener) {
  3147. addEventListenerFn(element, type, handle);
  3148. }
  3149. }
  3150. eventFns.push(fn);
  3151. };
  3152. while (i--) {
  3153. type = types[i];
  3154. if (MOUSE_EVENT_MAP[type]) {
  3155. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3156. addHandler(type, undefined, true);
  3157. } else {
  3158. addHandler(type);
  3159. }
  3160. }
  3161. },
  3162. off: jqLiteOff,
  3163. one: function(element, type, fn) {
  3164. element = jqLite(element);
  3165. //add the listener twice so that when it is called
  3166. //you can remove the original function and still be
  3167. //able to call element.off(ev, fn) normally
  3168. element.on(type, function onFn() {
  3169. element.off(type, fn);
  3170. element.off(type, onFn);
  3171. });
  3172. element.on(type, fn);
  3173. },
  3174. replaceWith: function(element, replaceNode) {
  3175. var index, parent = element.parentNode;
  3176. jqLiteDealoc(element);
  3177. forEach(new JQLite(replaceNode), function(node) {
  3178. if (index) {
  3179. parent.insertBefore(node, index.nextSibling);
  3180. } else {
  3181. parent.replaceChild(node, element);
  3182. }
  3183. index = node;
  3184. });
  3185. },
  3186. children: function(element) {
  3187. var children = [];
  3188. forEach(element.childNodes, function(element) {
  3189. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3190. children.push(element);
  3191. }
  3192. });
  3193. return children;
  3194. },
  3195. contents: function(element) {
  3196. return element.contentDocument || element.childNodes || [];
  3197. },
  3198. append: function(element, node) {
  3199. var nodeType = element.nodeType;
  3200. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3201. node = new JQLite(node);
  3202. for (var i = 0, ii = node.length; i < ii; i++) {
  3203. var child = node[i];
  3204. element.appendChild(child);
  3205. }
  3206. },
  3207. prepend: function(element, node) {
  3208. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3209. var index = element.firstChild;
  3210. forEach(new JQLite(node), function(child) {
  3211. element.insertBefore(child, index);
  3212. });
  3213. }
  3214. },
  3215. wrap: function(element, wrapNode) {
  3216. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3217. },
  3218. remove: jqLiteRemove,
  3219. detach: function(element) {
  3220. jqLiteRemove(element, true);
  3221. },
  3222. after: function(element, newElement) {
  3223. var index = element, parent = element.parentNode;
  3224. newElement = new JQLite(newElement);
  3225. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3226. var node = newElement[i];
  3227. parent.insertBefore(node, index.nextSibling);
  3228. index = node;
  3229. }
  3230. },
  3231. addClass: jqLiteAddClass,
  3232. removeClass: jqLiteRemoveClass,
  3233. toggleClass: function(element, selector, condition) {
  3234. if (selector) {
  3235. forEach(selector.split(' '), function(className) {
  3236. var classCondition = condition;
  3237. if (isUndefined(classCondition)) {
  3238. classCondition = !jqLiteHasClass(element, className);
  3239. }
  3240. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3241. });
  3242. }
  3243. },
  3244. parent: function(element) {
  3245. var parent = element.parentNode;
  3246. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3247. },
  3248. next: function(element) {
  3249. return element.nextElementSibling;
  3250. },
  3251. find: function(element, selector) {
  3252. if (element.getElementsByTagName) {
  3253. return element.getElementsByTagName(selector);
  3254. } else {
  3255. return [];
  3256. }
  3257. },
  3258. clone: jqLiteClone,
  3259. triggerHandler: function(element, event, extraParameters) {
  3260. var dummyEvent, eventFnsCopy, handlerArgs;
  3261. var eventName = event.type || event;
  3262. var expandoStore = jqLiteExpandoStore(element);
  3263. var events = expandoStore && expandoStore.events;
  3264. var eventFns = events && events[eventName];
  3265. if (eventFns) {
  3266. // Create a dummy event to pass to the handlers
  3267. dummyEvent = {
  3268. preventDefault: function() { this.defaultPrevented = true; },
  3269. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3270. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3271. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3272. stopPropagation: noop,
  3273. type: eventName,
  3274. target: element
  3275. };
  3276. // If a custom event was provided then extend our dummy event with it
  3277. if (event.type) {
  3278. dummyEvent = extend(dummyEvent, event);
  3279. }
  3280. // Copy event handlers in case event handlers array is modified during execution.
  3281. eventFnsCopy = shallowCopy(eventFns);
  3282. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3283. forEach(eventFnsCopy, function(fn) {
  3284. if (!dummyEvent.isImmediatePropagationStopped()) {
  3285. fn.apply(element, handlerArgs);
  3286. }
  3287. });
  3288. }
  3289. }
  3290. }, function(fn, name) {
  3291. /**
  3292. * chaining functions
  3293. */
  3294. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3295. var value;
  3296. for (var i = 0, ii = this.length; i < ii; i++) {
  3297. if (isUndefined(value)) {
  3298. value = fn(this[i], arg1, arg2, arg3);
  3299. if (isDefined(value)) {
  3300. // any function which returns a value needs to be wrapped
  3301. value = jqLite(value);
  3302. }
  3303. } else {
  3304. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3305. }
  3306. }
  3307. return isDefined(value) ? value : this;
  3308. };
  3309. // bind legacy bind/unbind to on/off
  3310. JQLite.prototype.bind = JQLite.prototype.on;
  3311. JQLite.prototype.unbind = JQLite.prototype.off;
  3312. });
  3313. // Provider for private $$jqLite service
  3314. function $$jqLiteProvider() {
  3315. this.$get = function $$jqLite() {
  3316. return extend(JQLite, {
  3317. hasClass: function(node, classes) {
  3318. if (node.attr) node = node[0];
  3319. return jqLiteHasClass(node, classes);
  3320. },
  3321. addClass: function(node, classes) {
  3322. if (node.attr) node = node[0];
  3323. return jqLiteAddClass(node, classes);
  3324. },
  3325. removeClass: function(node, classes) {
  3326. if (node.attr) node = node[0];
  3327. return jqLiteRemoveClass(node, classes);
  3328. }
  3329. });
  3330. };
  3331. }
  3332. /**
  3333. * Computes a hash of an 'obj'.
  3334. * Hash of a:
  3335. * string is string
  3336. * number is number as string
  3337. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3338. * that is also assigned to the $$hashKey property of the object.
  3339. *
  3340. * @param obj
  3341. * @returns {string} hash string such that the same input will have the same hash string.
  3342. * The resulting string key is in 'type:hashKey' format.
  3343. */
  3344. function hashKey(obj, nextUidFn) {
  3345. var key = obj && obj.$$hashKey;
  3346. if (key) {
  3347. if (typeof key === 'function') {
  3348. key = obj.$$hashKey();
  3349. }
  3350. return key;
  3351. }
  3352. var objType = typeof obj;
  3353. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3354. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3355. } else {
  3356. key = objType + ':' + obj;
  3357. }
  3358. return key;
  3359. }
  3360. /**
  3361. * HashMap which can use objects as keys
  3362. */
  3363. function HashMap(array, isolatedUid) {
  3364. if (isolatedUid) {
  3365. var uid = 0;
  3366. this.nextUid = function() {
  3367. return ++uid;
  3368. };
  3369. }
  3370. forEach(array, this.put, this);
  3371. }
  3372. HashMap.prototype = {
  3373. /**
  3374. * Store key value pair
  3375. * @param key key to store can be any type
  3376. * @param value value to store can be any type
  3377. */
  3378. put: function(key, value) {
  3379. this[hashKey(key, this.nextUid)] = value;
  3380. },
  3381. /**
  3382. * @param key
  3383. * @returns {Object} the value for the key
  3384. */
  3385. get: function(key) {
  3386. return this[hashKey(key, this.nextUid)];
  3387. },
  3388. /**
  3389. * Remove the key/value pair
  3390. * @param key
  3391. */
  3392. remove: function(key) {
  3393. var value = this[key = hashKey(key, this.nextUid)];
  3394. delete this[key];
  3395. return value;
  3396. }
  3397. };
  3398. var $$HashMapProvider = [function() {
  3399. this.$get = [function() {
  3400. return HashMap;
  3401. }];
  3402. }];
  3403. /**
  3404. * @ngdoc function
  3405. * @module ng
  3406. * @name angular.injector
  3407. * @kind function
  3408. *
  3409. * @description
  3410. * Creates an injector object that can be used for retrieving services as well as for
  3411. * dependency injection (see {@link guide/di dependency injection}).
  3412. *
  3413. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3414. * {@link angular.module}. The `ng` module must be explicitly added.
  3415. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3416. * disallows argument name annotation inference.
  3417. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3418. *
  3419. * @example
  3420. * Typical usage
  3421. * ```js
  3422. * // create an injector
  3423. * var $injector = angular.injector(['ng']);
  3424. *
  3425. * // use the injector to kick off your application
  3426. * // use the type inference to auto inject arguments, or use implicit injection
  3427. * $injector.invoke(function($rootScope, $compile, $document) {
  3428. * $compile($document)($rootScope);
  3429. * $rootScope.$digest();
  3430. * });
  3431. * ```
  3432. *
  3433. * Sometimes you want to get access to the injector of a currently running Angular app
  3434. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3435. * application has been bootstrapped. You can do this using the extra `injector()` added
  3436. * to JQuery/jqLite elements. See {@link angular.element}.
  3437. *
  3438. * *This is fairly rare but could be the case if a third party library is injecting the
  3439. * markup.*
  3440. *
  3441. * In the following example a new block of HTML containing a `ng-controller`
  3442. * directive is added to the end of the document body by JQuery. We then compile and link
  3443. * it into the current AngularJS scope.
  3444. *
  3445. * ```js
  3446. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3447. * $(document.body).append($div);
  3448. *
  3449. * angular.element(document).injector().invoke(function($compile) {
  3450. * var scope = angular.element($div).scope();
  3451. * $compile($div)(scope);
  3452. * });
  3453. * ```
  3454. */
  3455. /**
  3456. * @ngdoc module
  3457. * @name auto
  3458. * @installation
  3459. * @description
  3460. *
  3461. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3462. */
  3463. var ARROW_ARG = /^([^\(]+?)=>/;
  3464. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  3465. var FN_ARG_SPLIT = /,/;
  3466. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3467. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3468. var $injectorMinErr = minErr('$injector');
  3469. function stringifyFn(fn) {
  3470. // Support: Chrome 50-51 only
  3471. // Creating a new string by adding `' '` at the end, to hack around some bug in Chrome v50/51
  3472. // (See https://github.com/angular/angular.js/issues/14487.)
  3473. // TODO (gkalpak): Remove workaround when Chrome v52 is released
  3474. return Function.prototype.toString.call(fn) + ' ';
  3475. }
  3476. function extractArgs(fn) {
  3477. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3478. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3479. return args;
  3480. }
  3481. function anonFn(fn) {
  3482. // For anonymous functions, showing at the very least the function signature can help in
  3483. // debugging.
  3484. var args = extractArgs(fn);
  3485. if (args) {
  3486. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3487. }
  3488. return 'fn';
  3489. }
  3490. function annotate(fn, strictDi, name) {
  3491. var $inject,
  3492. argDecl,
  3493. last;
  3494. if (typeof fn === 'function') {
  3495. if (!($inject = fn.$inject)) {
  3496. $inject = [];
  3497. if (fn.length) {
  3498. if (strictDi) {
  3499. if (!isString(name) || !name) {
  3500. name = fn.name || anonFn(fn);
  3501. }
  3502. throw $injectorMinErr('strictdi',
  3503. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3504. }
  3505. argDecl = extractArgs(fn);
  3506. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3507. arg.replace(FN_ARG, function(all, underscore, name) {
  3508. $inject.push(name);
  3509. });
  3510. });
  3511. }
  3512. fn.$inject = $inject;
  3513. }
  3514. } else if (isArray(fn)) {
  3515. last = fn.length - 1;
  3516. assertArgFn(fn[last], 'fn');
  3517. $inject = fn.slice(0, last);
  3518. } else {
  3519. assertArgFn(fn, 'fn', true);
  3520. }
  3521. return $inject;
  3522. }
  3523. ///////////////////////////////////////
  3524. /**
  3525. * @ngdoc service
  3526. * @name $injector
  3527. *
  3528. * @description
  3529. *
  3530. * `$injector` is used to retrieve object instances as defined by
  3531. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3532. * and load modules.
  3533. *
  3534. * The following always holds true:
  3535. *
  3536. * ```js
  3537. * var $injector = angular.injector();
  3538. * expect($injector.get('$injector')).toBe($injector);
  3539. * expect($injector.invoke(function($injector) {
  3540. * return $injector;
  3541. * })).toBe($injector);
  3542. * ```
  3543. *
  3544. * # Injection Function Annotation
  3545. *
  3546. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3547. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3548. *
  3549. * ```js
  3550. * // inferred (only works if code not minified/obfuscated)
  3551. * $injector.invoke(function(serviceA){});
  3552. *
  3553. * // annotated
  3554. * function explicit(serviceA) {};
  3555. * explicit.$inject = ['serviceA'];
  3556. * $injector.invoke(explicit);
  3557. *
  3558. * // inline
  3559. * $injector.invoke(['serviceA', function(serviceA){}]);
  3560. * ```
  3561. *
  3562. * ## Inference
  3563. *
  3564. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3565. * can then be parsed and the function arguments can be extracted. This method of discovering
  3566. * annotations is disallowed when the injector is in strict mode.
  3567. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3568. * argument names.
  3569. *
  3570. * ## `$inject` Annotation
  3571. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3572. *
  3573. * ## Inline
  3574. * As an array of injection names, where the last item in the array is the function to call.
  3575. */
  3576. /**
  3577. * @ngdoc method
  3578. * @name $injector#get
  3579. *
  3580. * @description
  3581. * Return an instance of the service.
  3582. *
  3583. * @param {string} name The name of the instance to retrieve.
  3584. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3585. * @return {*} The instance.
  3586. */
  3587. /**
  3588. * @ngdoc method
  3589. * @name $injector#invoke
  3590. *
  3591. * @description
  3592. * Invoke the method and supply the method arguments from the `$injector`.
  3593. *
  3594. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3595. * injected according to the {@link guide/di $inject Annotation} rules.
  3596. * @param {Object=} self The `this` for the invoked method.
  3597. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3598. * object first, before the `$injector` is consulted.
  3599. * @returns {*} the value returned by the invoked `fn` function.
  3600. */
  3601. /**
  3602. * @ngdoc method
  3603. * @name $injector#has
  3604. *
  3605. * @description
  3606. * Allows the user to query if the particular service exists.
  3607. *
  3608. * @param {string} name Name of the service to query.
  3609. * @returns {boolean} `true` if injector has given service.
  3610. */
  3611. /**
  3612. * @ngdoc method
  3613. * @name $injector#instantiate
  3614. * @description
  3615. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3616. * operator, and supplies all of the arguments to the constructor function as specified by the
  3617. * constructor annotation.
  3618. *
  3619. * @param {Function} Type Annotated constructor function.
  3620. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3621. * object first, before the `$injector` is consulted.
  3622. * @returns {Object} new instance of `Type`.
  3623. */
  3624. /**
  3625. * @ngdoc method
  3626. * @name $injector#annotate
  3627. *
  3628. * @description
  3629. * Returns an array of service names which the function is requesting for injection. This API is
  3630. * used by the injector to determine which services need to be injected into the function when the
  3631. * function is invoked. There are three ways in which the function can be annotated with the needed
  3632. * dependencies.
  3633. *
  3634. * # Argument names
  3635. *
  3636. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3637. * by converting the function into a string using `toString()` method and extracting the argument
  3638. * names.
  3639. * ```js
  3640. * // Given
  3641. * function MyController($scope, $route) {
  3642. * // ...
  3643. * }
  3644. *
  3645. * // Then
  3646. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3647. * ```
  3648. *
  3649. * You can disallow this method by using strict injection mode.
  3650. *
  3651. * This method does not work with code minification / obfuscation. For this reason the following
  3652. * annotation strategies are supported.
  3653. *
  3654. * # The `$inject` property
  3655. *
  3656. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3657. * represent names of services to be injected into the function.
  3658. * ```js
  3659. * // Given
  3660. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3661. * // ...
  3662. * }
  3663. * // Define function dependencies
  3664. * MyController['$inject'] = ['$scope', '$route'];
  3665. *
  3666. * // Then
  3667. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3668. * ```
  3669. *
  3670. * # The array notation
  3671. *
  3672. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3673. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3674. * a way that survives minification is a better choice:
  3675. *
  3676. * ```js
  3677. * // We wish to write this (not minification / obfuscation safe)
  3678. * injector.invoke(function($compile, $rootScope) {
  3679. * // ...
  3680. * });
  3681. *
  3682. * // We are forced to write break inlining
  3683. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3684. * // ...
  3685. * };
  3686. * tmpFn.$inject = ['$compile', '$rootScope'];
  3687. * injector.invoke(tmpFn);
  3688. *
  3689. * // To better support inline function the inline annotation is supported
  3690. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3691. * // ...
  3692. * }]);
  3693. *
  3694. * // Therefore
  3695. * expect(injector.annotate(
  3696. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3697. * ).toEqual(['$compile', '$rootScope']);
  3698. * ```
  3699. *
  3700. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3701. * be retrieved as described above.
  3702. *
  3703. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3704. *
  3705. * @returns {Array.<string>} The names of the services which the function requires.
  3706. */
  3707. /**
  3708. * @ngdoc service
  3709. * @name $provide
  3710. *
  3711. * @description
  3712. *
  3713. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3714. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3715. * {@link angular.Module}.
  3716. *
  3717. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3718. * factories** are functions which, in turn, are created by a **service provider**.
  3719. * The **service providers** are constructor functions. When instantiated they must contain a
  3720. * property called `$get`, which holds the **service factory** function.
  3721. *
  3722. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3723. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3724. * function to get the instance of the **service**.
  3725. *
  3726. * Often services have no configuration options and there is no need to add methods to the service
  3727. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3728. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3729. * services without specifying a provider.
  3730. *
  3731. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  3732. * {@link auto.$injector $injector}
  3733. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  3734. * providers and services.
  3735. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  3736. * services, not providers.
  3737. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  3738. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3739. * given factory function.
  3740. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  3741. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3742. * a new object using the given constructor function.
  3743. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  3744. * will be able to modify or replace the implementation of another service.
  3745. *
  3746. * See the individual methods for more information and examples.
  3747. */
  3748. /**
  3749. * @ngdoc method
  3750. * @name $provide#provider
  3751. * @description
  3752. *
  3753. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3754. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3755. * service.
  3756. *
  3757. * Service provider names start with the name of the service they provide followed by `Provider`.
  3758. * For example, the {@link ng.$log $log} service has a provider called
  3759. * {@link ng.$logProvider $logProvider}.
  3760. *
  3761. * Service provider objects can have additional methods which allow configuration of the provider
  3762. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3763. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3764. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3765. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3766. * console or not.
  3767. *
  3768. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3769. 'Provider'` key.
  3770. * @param {(Object|function())} provider If the provider is:
  3771. *
  3772. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3773. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3774. * - `Constructor`: a new instance of the provider will be created using
  3775. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3776. *
  3777. * @returns {Object} registered provider instance
  3778. * @example
  3779. *
  3780. * The following example shows how to create a simple event tracking service and register it using
  3781. * {@link auto.$provide#provider $provide.provider()}.
  3782. *
  3783. * ```js
  3784. * // Define the eventTracker provider
  3785. * function EventTrackerProvider() {
  3786. * var trackingUrl = '/track';
  3787. *
  3788. * // A provider method for configuring where the tracked events should been saved
  3789. * this.setTrackingUrl = function(url) {
  3790. * trackingUrl = url;
  3791. * };
  3792. *
  3793. * // The service factory function
  3794. * this.$get = ['$http', function($http) {
  3795. * var trackedEvents = {};
  3796. * return {
  3797. * // Call this to track an event
  3798. * event: function(event) {
  3799. * var count = trackedEvents[event] || 0;
  3800. * count += 1;
  3801. * trackedEvents[event] = count;
  3802. * return count;
  3803. * },
  3804. * // Call this to save the tracked events to the trackingUrl
  3805. * save: function() {
  3806. * $http.post(trackingUrl, trackedEvents);
  3807. * }
  3808. * };
  3809. * }];
  3810. * }
  3811. *
  3812. * describe('eventTracker', function() {
  3813. * var postSpy;
  3814. *
  3815. * beforeEach(module(function($provide) {
  3816. * // Register the eventTracker provider
  3817. * $provide.provider('eventTracker', EventTrackerProvider);
  3818. * }));
  3819. *
  3820. * beforeEach(module(function(eventTrackerProvider) {
  3821. * // Configure eventTracker provider
  3822. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3823. * }));
  3824. *
  3825. * it('tracks events', inject(function(eventTracker) {
  3826. * expect(eventTracker.event('login')).toEqual(1);
  3827. * expect(eventTracker.event('login')).toEqual(2);
  3828. * }));
  3829. *
  3830. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3831. * postSpy = spyOn($http, 'post');
  3832. * eventTracker.event('login');
  3833. * eventTracker.save();
  3834. * expect(postSpy).toHaveBeenCalled();
  3835. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3836. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3837. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3838. * }));
  3839. * });
  3840. * ```
  3841. */
  3842. /**
  3843. * @ngdoc method
  3844. * @name $provide#factory
  3845. * @description
  3846. *
  3847. * Register a **service factory**, which will be called to return the service instance.
  3848. * This is short for registering a service where its provider consists of only a `$get` property,
  3849. * which is the given service factory function.
  3850. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3851. * configure your service in a provider.
  3852. *
  3853. * @param {string} name The name of the instance.
  3854. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3855. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3856. * @returns {Object} registered provider instance
  3857. *
  3858. * @example
  3859. * Here is an example of registering a service
  3860. * ```js
  3861. * $provide.factory('ping', ['$http', function($http) {
  3862. * return function ping() {
  3863. * return $http.send('/ping');
  3864. * };
  3865. * }]);
  3866. * ```
  3867. * You would then inject and use this service like this:
  3868. * ```js
  3869. * someModule.controller('Ctrl', ['ping', function(ping) {
  3870. * ping();
  3871. * }]);
  3872. * ```
  3873. */
  3874. /**
  3875. * @ngdoc method
  3876. * @name $provide#service
  3877. * @description
  3878. *
  3879. * Register a **service constructor**, which will be invoked with `new` to create the service
  3880. * instance.
  3881. * This is short for registering a service where its provider's `$get` property is a factory
  3882. * function that returns an instance instantiated by the injector from the service constructor
  3883. * function.
  3884. *
  3885. * Internally it looks a bit like this:
  3886. *
  3887. * ```
  3888. * {
  3889. * $get: function() {
  3890. * return $injector.instantiate(constructor);
  3891. * }
  3892. * }
  3893. * ```
  3894. *
  3895. *
  3896. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3897. * as a type/class.
  3898. *
  3899. * @param {string} name The name of the instance.
  3900. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3901. * that will be instantiated.
  3902. * @returns {Object} registered provider instance
  3903. *
  3904. * @example
  3905. * Here is an example of registering a service using
  3906. * {@link auto.$provide#service $provide.service(class)}.
  3907. * ```js
  3908. * var Ping = function($http) {
  3909. * this.$http = $http;
  3910. * };
  3911. *
  3912. * Ping.$inject = ['$http'];
  3913. *
  3914. * Ping.prototype.send = function() {
  3915. * return this.$http.get('/ping');
  3916. * };
  3917. * $provide.service('ping', Ping);
  3918. * ```
  3919. * You would then inject and use this service like this:
  3920. * ```js
  3921. * someModule.controller('Ctrl', ['ping', function(ping) {
  3922. * ping.send();
  3923. * }]);
  3924. * ```
  3925. */
  3926. /**
  3927. * @ngdoc method
  3928. * @name $provide#value
  3929. * @description
  3930. *
  3931. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3932. * number, an array, an object or a function. This is short for registering a service where its
  3933. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3934. * service**. That also means it is not possible to inject other services into a value service.
  3935. *
  3936. * Value services are similar to constant services, except that they cannot be injected into a
  3937. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3938. * an Angular {@link auto.$provide#decorator decorator}.
  3939. *
  3940. * @param {string} name The name of the instance.
  3941. * @param {*} value The value.
  3942. * @returns {Object} registered provider instance
  3943. *
  3944. * @example
  3945. * Here are some examples of creating value services.
  3946. * ```js
  3947. * $provide.value('ADMIN_USER', 'admin');
  3948. *
  3949. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3950. *
  3951. * $provide.value('halfOf', function(value) {
  3952. * return value / 2;
  3953. * });
  3954. * ```
  3955. */
  3956. /**
  3957. * @ngdoc method
  3958. * @name $provide#constant
  3959. * @description
  3960. *
  3961. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  3962. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  3963. * possible to inject other services into a constant.
  3964. *
  3965. * But unlike {@link auto.$provide#value value}, a constant can be
  3966. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3967. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3968. *
  3969. * @param {string} name The name of the constant.
  3970. * @param {*} value The constant value.
  3971. * @returns {Object} registered instance
  3972. *
  3973. * @example
  3974. * Here a some examples of creating constants:
  3975. * ```js
  3976. * $provide.constant('SHARD_HEIGHT', 306);
  3977. *
  3978. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3979. *
  3980. * $provide.constant('double', function(value) {
  3981. * return value * 2;
  3982. * });
  3983. * ```
  3984. */
  3985. /**
  3986. * @ngdoc method
  3987. * @name $provide#decorator
  3988. * @description
  3989. *
  3990. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  3991. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  3992. * service. The return value of the decorator function may be the original service, or a new service
  3993. * that replaces (or wraps and delegates to) the original service.
  3994. *
  3995. * You can find out more about using decorators in the {@link guide/decorators} guide.
  3996. *
  3997. * @param {string} name The name of the service to decorate.
  3998. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3999. * provided and should return the decorated service instance. The function is called using
  4000. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4001. * Local injection arguments:
  4002. *
  4003. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4004. * decorated or delegated to.
  4005. *
  4006. * @example
  4007. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4008. * calls to {@link ng.$log#error $log.warn()}.
  4009. * ```js
  4010. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4011. * $delegate.warn = $delegate.error;
  4012. * return $delegate;
  4013. * }]);
  4014. * ```
  4015. */
  4016. function createInjector(modulesToLoad, strictDi) {
  4017. strictDi = (strictDi === true);
  4018. var INSTANTIATING = {},
  4019. providerSuffix = 'Provider',
  4020. path = [],
  4021. loadedModules = new HashMap([], true),
  4022. providerCache = {
  4023. $provide: {
  4024. provider: supportObject(provider),
  4025. factory: supportObject(factory),
  4026. service: supportObject(service),
  4027. value: supportObject(value),
  4028. constant: supportObject(constant),
  4029. decorator: decorator
  4030. }
  4031. },
  4032. providerInjector = (providerCache.$injector =
  4033. createInternalInjector(providerCache, function(serviceName, caller) {
  4034. if (angular.isString(caller)) {
  4035. path.push(caller);
  4036. }
  4037. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  4038. })),
  4039. instanceCache = {},
  4040. protoInstanceInjector =
  4041. createInternalInjector(instanceCache, function(serviceName, caller) {
  4042. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4043. return instanceInjector.invoke(
  4044. provider.$get, provider, undefined, serviceName);
  4045. }),
  4046. instanceInjector = protoInstanceInjector;
  4047. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4048. var runBlocks = loadModules(modulesToLoad);
  4049. instanceInjector = protoInstanceInjector.get('$injector');
  4050. instanceInjector.strictDi = strictDi;
  4051. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4052. return instanceInjector;
  4053. ////////////////////////////////////
  4054. // $provider
  4055. ////////////////////////////////////
  4056. function supportObject(delegate) {
  4057. return function(key, value) {
  4058. if (isObject(key)) {
  4059. forEach(key, reverseParams(delegate));
  4060. } else {
  4061. return delegate(key, value);
  4062. }
  4063. };
  4064. }
  4065. function provider(name, provider_) {
  4066. assertNotHasOwnProperty(name, 'service');
  4067. if (isFunction(provider_) || isArray(provider_)) {
  4068. provider_ = providerInjector.instantiate(provider_);
  4069. }
  4070. if (!provider_.$get) {
  4071. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  4072. }
  4073. return providerCache[name + providerSuffix] = provider_;
  4074. }
  4075. function enforceReturnValue(name, factory) {
  4076. return function enforcedReturnValue() {
  4077. var result = instanceInjector.invoke(factory, this);
  4078. if (isUndefined(result)) {
  4079. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  4080. }
  4081. return result;
  4082. };
  4083. }
  4084. function factory(name, factoryFn, enforce) {
  4085. return provider(name, {
  4086. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4087. });
  4088. }
  4089. function service(name, constructor) {
  4090. return factory(name, ['$injector', function($injector) {
  4091. return $injector.instantiate(constructor);
  4092. }]);
  4093. }
  4094. function value(name, val) { return factory(name, valueFn(val), false); }
  4095. function constant(name, value) {
  4096. assertNotHasOwnProperty(name, 'constant');
  4097. providerCache[name] = value;
  4098. instanceCache[name] = value;
  4099. }
  4100. function decorator(serviceName, decorFn) {
  4101. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4102. orig$get = origProvider.$get;
  4103. origProvider.$get = function() {
  4104. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4105. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4106. };
  4107. }
  4108. ////////////////////////////////////
  4109. // Module Loading
  4110. ////////////////////////////////////
  4111. function loadModules(modulesToLoad) {
  4112. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4113. var runBlocks = [], moduleFn;
  4114. forEach(modulesToLoad, function(module) {
  4115. if (loadedModules.get(module)) return;
  4116. loadedModules.put(module, true);
  4117. function runInvokeQueue(queue) {
  4118. var i, ii;
  4119. for (i = 0, ii = queue.length; i < ii; i++) {
  4120. var invokeArgs = queue[i],
  4121. provider = providerInjector.get(invokeArgs[0]);
  4122. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4123. }
  4124. }
  4125. try {
  4126. if (isString(module)) {
  4127. moduleFn = angularModule(module);
  4128. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4129. runInvokeQueue(moduleFn._invokeQueue);
  4130. runInvokeQueue(moduleFn._configBlocks);
  4131. } else if (isFunction(module)) {
  4132. runBlocks.push(providerInjector.invoke(module));
  4133. } else if (isArray(module)) {
  4134. runBlocks.push(providerInjector.invoke(module));
  4135. } else {
  4136. assertArgFn(module, 'module');
  4137. }
  4138. } catch (e) {
  4139. if (isArray(module)) {
  4140. module = module[module.length - 1];
  4141. }
  4142. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  4143. // Safari & FF's stack traces don't contain error.message content
  4144. // unlike those of Chrome and IE
  4145. // So if stack doesn't contain message, we create a new string that contains both.
  4146. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4147. /* jshint -W022 */
  4148. e = e.message + '\n' + e.stack;
  4149. }
  4150. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  4151. module, e.stack || e.message || e);
  4152. }
  4153. });
  4154. return runBlocks;
  4155. }
  4156. ////////////////////////////////////
  4157. // internal Injector
  4158. ////////////////////////////////////
  4159. function createInternalInjector(cache, factory) {
  4160. function getService(serviceName, caller) {
  4161. if (cache.hasOwnProperty(serviceName)) {
  4162. if (cache[serviceName] === INSTANTIATING) {
  4163. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4164. serviceName + ' <- ' + path.join(' <- '));
  4165. }
  4166. return cache[serviceName];
  4167. } else {
  4168. try {
  4169. path.unshift(serviceName);
  4170. cache[serviceName] = INSTANTIATING;
  4171. return cache[serviceName] = factory(serviceName, caller);
  4172. } catch (err) {
  4173. if (cache[serviceName] === INSTANTIATING) {
  4174. delete cache[serviceName];
  4175. }
  4176. throw err;
  4177. } finally {
  4178. path.shift();
  4179. }
  4180. }
  4181. }
  4182. function injectionArgs(fn, locals, serviceName) {
  4183. var args = [],
  4184. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4185. for (var i = 0, length = $inject.length; i < length; i++) {
  4186. var key = $inject[i];
  4187. if (typeof key !== 'string') {
  4188. throw $injectorMinErr('itkn',
  4189. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4190. }
  4191. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4192. getService(key, serviceName));
  4193. }
  4194. return args;
  4195. }
  4196. function isClass(func) {
  4197. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4198. if (msie <= 11) {
  4199. return false;
  4200. }
  4201. // Support: Edge 12-13 only
  4202. // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
  4203. return typeof func === 'function'
  4204. && /^(?:class\b|constructor\()/.test(stringifyFn(func));
  4205. }
  4206. function invoke(fn, self, locals, serviceName) {
  4207. if (typeof locals === 'string') {
  4208. serviceName = locals;
  4209. locals = null;
  4210. }
  4211. var args = injectionArgs(fn, locals, serviceName);
  4212. if (isArray(fn)) {
  4213. fn = fn[fn.length - 1];
  4214. }
  4215. if (!isClass(fn)) {
  4216. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4217. // #5388
  4218. return fn.apply(self, args);
  4219. } else {
  4220. args.unshift(null);
  4221. return new (Function.prototype.bind.apply(fn, args))();
  4222. }
  4223. }
  4224. function instantiate(Type, locals, serviceName) {
  4225. // Check if Type is annotated and use just the given function at n-1 as parameter
  4226. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4227. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4228. var args = injectionArgs(Type, locals, serviceName);
  4229. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4230. args.unshift(null);
  4231. return new (Function.prototype.bind.apply(ctor, args))();
  4232. }
  4233. return {
  4234. invoke: invoke,
  4235. instantiate: instantiate,
  4236. get: getService,
  4237. annotate: createInjector.$$annotate,
  4238. has: function(name) {
  4239. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4240. }
  4241. };
  4242. }
  4243. }
  4244. createInjector.$$annotate = annotate;
  4245. /**
  4246. * @ngdoc provider
  4247. * @name $anchorScrollProvider
  4248. *
  4249. * @description
  4250. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4251. * {@link ng.$location#hash $location.hash()} changes.
  4252. */
  4253. function $AnchorScrollProvider() {
  4254. var autoScrollingEnabled = true;
  4255. /**
  4256. * @ngdoc method
  4257. * @name $anchorScrollProvider#disableAutoScrolling
  4258. *
  4259. * @description
  4260. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4261. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4262. * Use this method to disable automatic scrolling.
  4263. *
  4264. * If automatic scrolling is disabled, one must explicitly call
  4265. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4266. * current hash.
  4267. */
  4268. this.disableAutoScrolling = function() {
  4269. autoScrollingEnabled = false;
  4270. };
  4271. /**
  4272. * @ngdoc service
  4273. * @name $anchorScroll
  4274. * @kind function
  4275. * @requires $window
  4276. * @requires $location
  4277. * @requires $rootScope
  4278. *
  4279. * @description
  4280. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4281. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4282. * in the
  4283. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4284. *
  4285. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4286. * match any anchor whenever it changes. This can be disabled by calling
  4287. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4288. *
  4289. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4290. * vertical scroll-offset (either fixed or dynamic).
  4291. *
  4292. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4293. * {@link ng.$location#hash $location.hash()} will be used.
  4294. *
  4295. * @property {(number|function|jqLite)} yOffset
  4296. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4297. * positioned elements at the top of the page, such as navbars, headers etc.
  4298. *
  4299. * `yOffset` can be specified in various ways:
  4300. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4301. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4302. * a number representing the offset (in pixels).<br /><br />
  4303. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4304. * the top of the page to the element's bottom will be used as offset.<br />
  4305. * **Note**: The element will be taken into account only as long as its `position` is set to
  4306. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4307. * their height and/or positioning according to the viewport's size.
  4308. *
  4309. * <br />
  4310. * <div class="alert alert-warning">
  4311. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4312. * not some child element.
  4313. * </div>
  4314. *
  4315. * @example
  4316. <example module="anchorScrollExample">
  4317. <file name="index.html">
  4318. <div id="scrollArea" ng-controller="ScrollController">
  4319. <a ng-click="gotoBottom()">Go to bottom</a>
  4320. <a id="bottom"></a> You're at the bottom!
  4321. </div>
  4322. </file>
  4323. <file name="script.js">
  4324. angular.module('anchorScrollExample', [])
  4325. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4326. function ($scope, $location, $anchorScroll) {
  4327. $scope.gotoBottom = function() {
  4328. // set the location.hash to the id of
  4329. // the element you wish to scroll to.
  4330. $location.hash('bottom');
  4331. // call $anchorScroll()
  4332. $anchorScroll();
  4333. };
  4334. }]);
  4335. </file>
  4336. <file name="style.css">
  4337. #scrollArea {
  4338. height: 280px;
  4339. overflow: auto;
  4340. }
  4341. #bottom {
  4342. display: block;
  4343. margin-top: 2000px;
  4344. }
  4345. </file>
  4346. </example>
  4347. *
  4348. * <hr />
  4349. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4350. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4351. *
  4352. * @example
  4353. <example module="anchorScrollOffsetExample">
  4354. <file name="index.html">
  4355. <div class="fixed-header" ng-controller="headerCtrl">
  4356. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4357. Go to anchor {{x}}
  4358. </a>
  4359. </div>
  4360. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4361. Anchor {{x}} of 5
  4362. </div>
  4363. </file>
  4364. <file name="script.js">
  4365. angular.module('anchorScrollOffsetExample', [])
  4366. .run(['$anchorScroll', function($anchorScroll) {
  4367. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4368. }])
  4369. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4370. function ($anchorScroll, $location, $scope) {
  4371. $scope.gotoAnchor = function(x) {
  4372. var newHash = 'anchor' + x;
  4373. if ($location.hash() !== newHash) {
  4374. // set the $location.hash to `newHash` and
  4375. // $anchorScroll will automatically scroll to it
  4376. $location.hash('anchor' + x);
  4377. } else {
  4378. // call $anchorScroll() explicitly,
  4379. // since $location.hash hasn't changed
  4380. $anchorScroll();
  4381. }
  4382. };
  4383. }
  4384. ]);
  4385. </file>
  4386. <file name="style.css">
  4387. body {
  4388. padding-top: 50px;
  4389. }
  4390. .anchor {
  4391. border: 2px dashed DarkOrchid;
  4392. padding: 10px 10px 200px 10px;
  4393. }
  4394. .fixed-header {
  4395. background-color: rgba(0, 0, 0, 0.2);
  4396. height: 50px;
  4397. position: fixed;
  4398. top: 0; left: 0; right: 0;
  4399. }
  4400. .fixed-header > a {
  4401. display: inline-block;
  4402. margin: 5px 15px;
  4403. }
  4404. </file>
  4405. </example>
  4406. */
  4407. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4408. var document = $window.document;
  4409. // Helper function to get first anchor from a NodeList
  4410. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4411. // and working in all supported browsers.)
  4412. function getFirstAnchor(list) {
  4413. var result = null;
  4414. Array.prototype.some.call(list, function(element) {
  4415. if (nodeName_(element) === 'a') {
  4416. result = element;
  4417. return true;
  4418. }
  4419. });
  4420. return result;
  4421. }
  4422. function getYOffset() {
  4423. var offset = scroll.yOffset;
  4424. if (isFunction(offset)) {
  4425. offset = offset();
  4426. } else if (isElement(offset)) {
  4427. var elem = offset[0];
  4428. var style = $window.getComputedStyle(elem);
  4429. if (style.position !== 'fixed') {
  4430. offset = 0;
  4431. } else {
  4432. offset = elem.getBoundingClientRect().bottom;
  4433. }
  4434. } else if (!isNumber(offset)) {
  4435. offset = 0;
  4436. }
  4437. return offset;
  4438. }
  4439. function scrollTo(elem) {
  4440. if (elem) {
  4441. elem.scrollIntoView();
  4442. var offset = getYOffset();
  4443. if (offset) {
  4444. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4445. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4446. // top of the viewport.
  4447. //
  4448. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4449. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4450. // way down the page.
  4451. //
  4452. // This is often the case for elements near the bottom of the page.
  4453. //
  4454. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4455. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4456. // desired position.
  4457. var elemTop = elem.getBoundingClientRect().top;
  4458. $window.scrollBy(0, elemTop - offset);
  4459. }
  4460. } else {
  4461. $window.scrollTo(0, 0);
  4462. }
  4463. }
  4464. function scroll(hash) {
  4465. hash = isString(hash) ? hash : $location.hash();
  4466. var elm;
  4467. // empty hash, scroll to the top of the page
  4468. if (!hash) scrollTo(null);
  4469. // element with given id
  4470. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4471. // first anchor with given name :-D
  4472. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4473. // no element and hash == 'top', scroll to the top of the page
  4474. else if (hash === 'top') scrollTo(null);
  4475. }
  4476. // does not scroll when user clicks on anchor link that is currently on
  4477. // (no url change, no $location.hash() change), browser native does scroll
  4478. if (autoScrollingEnabled) {
  4479. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4480. function autoScrollWatchAction(newVal, oldVal) {
  4481. // skip the initial scroll if $location.hash is empty
  4482. if (newVal === oldVal && newVal === '') return;
  4483. jqLiteDocumentLoaded(function() {
  4484. $rootScope.$evalAsync(scroll);
  4485. });
  4486. });
  4487. }
  4488. return scroll;
  4489. }];
  4490. }
  4491. var $animateMinErr = minErr('$animate');
  4492. var ELEMENT_NODE = 1;
  4493. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4494. function mergeClasses(a,b) {
  4495. if (!a && !b) return '';
  4496. if (!a) return b;
  4497. if (!b) return a;
  4498. if (isArray(a)) a = a.join(' ');
  4499. if (isArray(b)) b = b.join(' ');
  4500. return a + ' ' + b;
  4501. }
  4502. function extractElementNode(element) {
  4503. for (var i = 0; i < element.length; i++) {
  4504. var elm = element[i];
  4505. if (elm.nodeType === ELEMENT_NODE) {
  4506. return elm;
  4507. }
  4508. }
  4509. }
  4510. function splitClasses(classes) {
  4511. if (isString(classes)) {
  4512. classes = classes.split(' ');
  4513. }
  4514. // Use createMap() to prevent class assumptions involving property names in
  4515. // Object.prototype
  4516. var obj = createMap();
  4517. forEach(classes, function(klass) {
  4518. // sometimes the split leaves empty string values
  4519. // incase extra spaces were applied to the options
  4520. if (klass.length) {
  4521. obj[klass] = true;
  4522. }
  4523. });
  4524. return obj;
  4525. }
  4526. // if any other type of options value besides an Object value is
  4527. // passed into the $animate.method() animation then this helper code
  4528. // will be run which will ignore it. While this patch is not the
  4529. // greatest solution to this, a lot of existing plugins depend on
  4530. // $animate to either call the callback (< 1.2) or return a promise
  4531. // that can be changed. This helper function ensures that the options
  4532. // are wiped clean incase a callback function is provided.
  4533. function prepareAnimateOptions(options) {
  4534. return isObject(options)
  4535. ? options
  4536. : {};
  4537. }
  4538. var $$CoreAnimateJsProvider = function() {
  4539. this.$get = noop;
  4540. };
  4541. // this is prefixed with Core since it conflicts with
  4542. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4543. var $$CoreAnimateQueueProvider = function() {
  4544. var postDigestQueue = new HashMap();
  4545. var postDigestElements = [];
  4546. this.$get = ['$$AnimateRunner', '$rootScope',
  4547. function($$AnimateRunner, $rootScope) {
  4548. return {
  4549. enabled: noop,
  4550. on: noop,
  4551. off: noop,
  4552. pin: noop,
  4553. push: function(element, event, options, domOperation) {
  4554. domOperation && domOperation();
  4555. options = options || {};
  4556. options.from && element.css(options.from);
  4557. options.to && element.css(options.to);
  4558. if (options.addClass || options.removeClass) {
  4559. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4560. }
  4561. var runner = new $$AnimateRunner(); // jshint ignore:line
  4562. // since there are no animations to run the runner needs to be
  4563. // notified that the animation call is complete.
  4564. runner.complete();
  4565. return runner;
  4566. }
  4567. };
  4568. function updateData(data, classes, value) {
  4569. var changed = false;
  4570. if (classes) {
  4571. classes = isString(classes) ? classes.split(' ') :
  4572. isArray(classes) ? classes : [];
  4573. forEach(classes, function(className) {
  4574. if (className) {
  4575. changed = true;
  4576. data[className] = value;
  4577. }
  4578. });
  4579. }
  4580. return changed;
  4581. }
  4582. function handleCSSClassChanges() {
  4583. forEach(postDigestElements, function(element) {
  4584. var data = postDigestQueue.get(element);
  4585. if (data) {
  4586. var existing = splitClasses(element.attr('class'));
  4587. var toAdd = '';
  4588. var toRemove = '';
  4589. forEach(data, function(status, className) {
  4590. var hasClass = !!existing[className];
  4591. if (status !== hasClass) {
  4592. if (status) {
  4593. toAdd += (toAdd.length ? ' ' : '') + className;
  4594. } else {
  4595. toRemove += (toRemove.length ? ' ' : '') + className;
  4596. }
  4597. }
  4598. });
  4599. forEach(element, function(elm) {
  4600. toAdd && jqLiteAddClass(elm, toAdd);
  4601. toRemove && jqLiteRemoveClass(elm, toRemove);
  4602. });
  4603. postDigestQueue.remove(element);
  4604. }
  4605. });
  4606. postDigestElements.length = 0;
  4607. }
  4608. function addRemoveClassesPostDigest(element, add, remove) {
  4609. var data = postDigestQueue.get(element) || {};
  4610. var classesAdded = updateData(data, add, true);
  4611. var classesRemoved = updateData(data, remove, false);
  4612. if (classesAdded || classesRemoved) {
  4613. postDigestQueue.put(element, data);
  4614. postDigestElements.push(element);
  4615. if (postDigestElements.length === 1) {
  4616. $rootScope.$$postDigest(handleCSSClassChanges);
  4617. }
  4618. }
  4619. }
  4620. }];
  4621. };
  4622. /**
  4623. * @ngdoc provider
  4624. * @name $animateProvider
  4625. *
  4626. * @description
  4627. * Default implementation of $animate that doesn't perform any animations, instead just
  4628. * synchronously performs DOM updates and resolves the returned runner promise.
  4629. *
  4630. * In order to enable animations the `ngAnimate` module has to be loaded.
  4631. *
  4632. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4633. */
  4634. var $AnimateProvider = ['$provide', function($provide) {
  4635. var provider = this;
  4636. this.$$registeredAnimations = Object.create(null);
  4637. /**
  4638. * @ngdoc method
  4639. * @name $animateProvider#register
  4640. *
  4641. * @description
  4642. * Registers a new injectable animation factory function. The factory function produces the
  4643. * animation object which contains callback functions for each event that is expected to be
  4644. * animated.
  4645. *
  4646. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4647. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4648. * on the type of animation additional arguments will be injected into the animation function. The
  4649. * list below explains the function signatures for the different animation methods:
  4650. *
  4651. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4652. * - addClass: function(element, addedClasses, doneFunction, options)
  4653. * - removeClass: function(element, removedClasses, doneFunction, options)
  4654. * - enter, leave, move: function(element, doneFunction, options)
  4655. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4656. *
  4657. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4658. *
  4659. * ```js
  4660. * return {
  4661. * //enter, leave, move signature
  4662. * eventFn : function(element, done, options) {
  4663. * //code to run the animation
  4664. * //once complete, then run done()
  4665. * return function endFunction(wasCancelled) {
  4666. * //code to cancel the animation
  4667. * }
  4668. * }
  4669. * }
  4670. * ```
  4671. *
  4672. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4673. * @param {Function} factory The factory function that will be executed to return the animation
  4674. * object.
  4675. */
  4676. this.register = function(name, factory) {
  4677. if (name && name.charAt(0) !== '.') {
  4678. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4679. }
  4680. var key = name + '-animation';
  4681. provider.$$registeredAnimations[name.substr(1)] = key;
  4682. $provide.factory(key, factory);
  4683. };
  4684. /**
  4685. * @ngdoc method
  4686. * @name $animateProvider#classNameFilter
  4687. *
  4688. * @description
  4689. * Sets and/or returns the CSS class regular expression that is checked when performing
  4690. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4691. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4692. * When setting the `classNameFilter` value, animations will only be performed on elements
  4693. * that successfully match the filter expression. This in turn can boost performance
  4694. * for low-powered devices as well as applications containing a lot of structural operations.
  4695. * @param {RegExp=} expression The className expression which will be checked against all animations
  4696. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4697. */
  4698. this.classNameFilter = function(expression) {
  4699. if (arguments.length === 1) {
  4700. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4701. if (this.$$classNameFilter) {
  4702. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4703. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4704. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4705. }
  4706. }
  4707. }
  4708. return this.$$classNameFilter;
  4709. };
  4710. this.$get = ['$$animateQueue', function($$animateQueue) {
  4711. function domInsert(element, parentElement, afterElement) {
  4712. // if for some reason the previous element was removed
  4713. // from the dom sometime before this code runs then let's
  4714. // just stick to using the parent element as the anchor
  4715. if (afterElement) {
  4716. var afterNode = extractElementNode(afterElement);
  4717. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4718. afterElement = null;
  4719. }
  4720. }
  4721. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4722. }
  4723. /**
  4724. * @ngdoc service
  4725. * @name $animate
  4726. * @description The $animate service exposes a series of DOM utility methods that provide support
  4727. * for animation hooks. The default behavior is the application of DOM operations, however,
  4728. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4729. * to ensure that animation runs with the triggered DOM operation.
  4730. *
  4731. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  4732. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4733. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4734. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4735. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4736. *
  4737. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4738. *
  4739. * To learn more about enabling animation support, click here to visit the
  4740. * {@link ngAnimate ngAnimate module page}.
  4741. */
  4742. return {
  4743. // we don't call it directly since non-existant arguments may
  4744. // be interpreted as null within the sub enabled function
  4745. /**
  4746. *
  4747. * @ngdoc method
  4748. * @name $animate#on
  4749. * @kind function
  4750. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4751. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4752. * is fired with the following params:
  4753. *
  4754. * ```js
  4755. * $animate.on('enter', container,
  4756. * function callback(element, phase) {
  4757. * // cool we detected an enter animation within the container
  4758. * }
  4759. * );
  4760. * ```
  4761. *
  4762. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4763. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4764. * as well as among its children
  4765. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4766. *
  4767. * The arguments present in the callback function are:
  4768. * * `element` - The captured DOM element that the animation was fired on.
  4769. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4770. */
  4771. on: $$animateQueue.on,
  4772. /**
  4773. *
  4774. * @ngdoc method
  4775. * @name $animate#off
  4776. * @kind function
  4777. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4778. * can be used in three different ways depending on the arguments:
  4779. *
  4780. * ```js
  4781. * // remove all the animation event listeners listening for `enter`
  4782. * $animate.off('enter');
  4783. *
  4784. * // remove listeners for all animation events from the container element
  4785. * $animate.off(container);
  4786. *
  4787. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4788. * $animate.off('enter', container);
  4789. *
  4790. * // remove the event listener function provided by `callback` that is set
  4791. * // to listen for `enter` on the given `container` as well as its children
  4792. * $animate.off('enter', container, callback);
  4793. * ```
  4794. *
  4795. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  4796. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  4797. * arguments are ignored.
  4798. * @param {DOMElement=} container the container element the event listener was placed on
  4799. * @param {Function=} callback the callback function that was registered as the listener
  4800. */
  4801. off: $$animateQueue.off,
  4802. /**
  4803. * @ngdoc method
  4804. * @name $animate#pin
  4805. * @kind function
  4806. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4807. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4808. * element despite being outside the realm of the application or within another application. Say for example if the application
  4809. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4810. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4811. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4812. *
  4813. * Note that this feature is only active when the `ngAnimate` module is used.
  4814. *
  4815. * @param {DOMElement} element the external element that will be pinned
  4816. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4817. */
  4818. pin: $$animateQueue.pin,
  4819. /**
  4820. *
  4821. * @ngdoc method
  4822. * @name $animate#enabled
  4823. * @kind function
  4824. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4825. * function can be called in four ways:
  4826. *
  4827. * ```js
  4828. * // returns true or false
  4829. * $animate.enabled();
  4830. *
  4831. * // changes the enabled state for all animations
  4832. * $animate.enabled(false);
  4833. * $animate.enabled(true);
  4834. *
  4835. * // returns true or false if animations are enabled for an element
  4836. * $animate.enabled(element);
  4837. *
  4838. * // changes the enabled state for an element and its children
  4839. * $animate.enabled(element, true);
  4840. * $animate.enabled(element, false);
  4841. * ```
  4842. *
  4843. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4844. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4845. *
  4846. * @return {boolean} whether or not animations are enabled
  4847. */
  4848. enabled: $$animateQueue.enabled,
  4849. /**
  4850. * @ngdoc method
  4851. * @name $animate#cancel
  4852. * @kind function
  4853. * @description Cancels the provided animation.
  4854. *
  4855. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4856. */
  4857. cancel: function(runner) {
  4858. runner.end && runner.end();
  4859. },
  4860. /**
  4861. *
  4862. * @ngdoc method
  4863. * @name $animate#enter
  4864. * @kind function
  4865. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4866. * as the first child within the `parent` element and then triggers an animation.
  4867. * A promise is returned that will be resolved during the next digest once the animation
  4868. * has completed.
  4869. *
  4870. * @param {DOMElement} element the element which will be inserted into the DOM
  4871. * @param {DOMElement} parent the parent element which will append the element as
  4872. * a child (so long as the after element is not present)
  4873. * @param {DOMElement=} after the sibling element after which the element will be appended
  4874. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4875. * The object can have the following properties:
  4876. *
  4877. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4878. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4879. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4880. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4881. *
  4882. * @return {Promise} the animation callback promise
  4883. */
  4884. enter: function(element, parent, after, options) {
  4885. parent = parent && jqLite(parent);
  4886. after = after && jqLite(after);
  4887. parent = parent || after.parent();
  4888. domInsert(element, parent, after);
  4889. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4890. },
  4891. /**
  4892. *
  4893. * @ngdoc method
  4894. * @name $animate#move
  4895. * @kind function
  4896. * @description Inserts (moves) the element into its new position in the DOM either after
  4897. * the `after` element (if provided) or as the first child within the `parent` element
  4898. * and then triggers an animation. A promise is returned that will be resolved
  4899. * during the next digest once the animation has completed.
  4900. *
  4901. * @param {DOMElement} element the element which will be moved into the new DOM position
  4902. * @param {DOMElement} parent the parent element which will append the element as
  4903. * a child (so long as the after element is not present)
  4904. * @param {DOMElement=} after the sibling element after which the element will be appended
  4905. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4906. * The object can have the following properties:
  4907. *
  4908. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4909. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4910. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4911. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4912. *
  4913. * @return {Promise} the animation callback promise
  4914. */
  4915. move: function(element, parent, after, options) {
  4916. parent = parent && jqLite(parent);
  4917. after = after && jqLite(after);
  4918. parent = parent || after.parent();
  4919. domInsert(element, parent, after);
  4920. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4921. },
  4922. /**
  4923. * @ngdoc method
  4924. * @name $animate#leave
  4925. * @kind function
  4926. * @description Triggers an animation and then removes the element from the DOM.
  4927. * When the function is called a promise is returned that will be resolved during the next
  4928. * digest once the animation has completed.
  4929. *
  4930. * @param {DOMElement} element the element which will be removed from the DOM
  4931. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4932. * The object can have the following properties:
  4933. *
  4934. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4935. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4936. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4937. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4938. *
  4939. * @return {Promise} the animation callback promise
  4940. */
  4941. leave: function(element, options) {
  4942. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4943. element.remove();
  4944. });
  4945. },
  4946. /**
  4947. * @ngdoc method
  4948. * @name $animate#addClass
  4949. * @kind function
  4950. *
  4951. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4952. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4953. * animation if element already contains the CSS class or if the class is removed at a later step.
  4954. * Note that class-based animations are treated differently compared to structural animations
  4955. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4956. * depending if CSS or JavaScript animations are used.
  4957. *
  4958. * @param {DOMElement} element the element which the CSS classes will be applied to
  4959. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4960. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4961. * The object can have the following properties:
  4962. *
  4963. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4964. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4965. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4966. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4967. *
  4968. * @return {Promise} the animation callback promise
  4969. */
  4970. addClass: function(element, className, options) {
  4971. options = prepareAnimateOptions(options);
  4972. options.addClass = mergeClasses(options.addclass, className);
  4973. return $$animateQueue.push(element, 'addClass', options);
  4974. },
  4975. /**
  4976. * @ngdoc method
  4977. * @name $animate#removeClass
  4978. * @kind function
  4979. *
  4980. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4981. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4982. * animation if element does not contain the CSS class or if the class is added at a later step.
  4983. * Note that class-based animations are treated differently compared to structural animations
  4984. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4985. * depending if CSS or JavaScript animations are used.
  4986. *
  4987. * @param {DOMElement} element the element which the CSS classes will be applied to
  4988. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4989. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4990. * The object can have the following properties:
  4991. *
  4992. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4993. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4994. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4995. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4996. *
  4997. * @return {Promise} the animation callback promise
  4998. */
  4999. removeClass: function(element, className, options) {
  5000. options = prepareAnimateOptions(options);
  5001. options.removeClass = mergeClasses(options.removeClass, className);
  5002. return $$animateQueue.push(element, 'removeClass', options);
  5003. },
  5004. /**
  5005. * @ngdoc method
  5006. * @name $animate#setClass
  5007. * @kind function
  5008. *
  5009. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5010. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5011. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5012. * passed. Note that class-based animations are treated differently compared to structural animations
  5013. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5014. * depending if CSS or JavaScript animations are used.
  5015. *
  5016. * @param {DOMElement} element the element which the CSS classes will be applied to
  5017. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5018. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5019. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5020. * The object can have the following properties:
  5021. *
  5022. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5023. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5024. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5025. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5026. *
  5027. * @return {Promise} the animation callback promise
  5028. */
  5029. setClass: function(element, add, remove, options) {
  5030. options = prepareAnimateOptions(options);
  5031. options.addClass = mergeClasses(options.addClass, add);
  5032. options.removeClass = mergeClasses(options.removeClass, remove);
  5033. return $$animateQueue.push(element, 'setClass', options);
  5034. },
  5035. /**
  5036. * @ngdoc method
  5037. * @name $animate#animate
  5038. * @kind function
  5039. *
  5040. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5041. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5042. * on the provided styles. For example, if a transition animation is set for the given classNamem, then the provided `from` and
  5043. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5044. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5045. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5046. * method (or as part of the `options` parameter):
  5047. *
  5048. * ```js
  5049. * ngModule.animation('.my-inline-animation', function() {
  5050. * return {
  5051. * animate : function(element, from, to, done, options) {
  5052. * //animation
  5053. * done();
  5054. * }
  5055. * }
  5056. * });
  5057. * ```
  5058. *
  5059. * @param {DOMElement} element the element which the CSS styles will be applied to
  5060. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5061. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5062. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5063. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5064. * (Note that if no animation is detected then this value will not be applied to the element.)
  5065. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5066. * The object can have the following properties:
  5067. *
  5068. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5069. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5070. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5071. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5072. *
  5073. * @return {Promise} the animation callback promise
  5074. */
  5075. animate: function(element, from, to, className, options) {
  5076. options = prepareAnimateOptions(options);
  5077. options.from = options.from ? extend(options.from, from) : from;
  5078. options.to = options.to ? extend(options.to, to) : to;
  5079. className = className || 'ng-inline-animate';
  5080. options.tempClasses = mergeClasses(options.tempClasses, className);
  5081. return $$animateQueue.push(element, 'animate', options);
  5082. }
  5083. };
  5084. }];
  5085. }];
  5086. var $$AnimateAsyncRunFactoryProvider = function() {
  5087. this.$get = ['$$rAF', function($$rAF) {
  5088. var waitQueue = [];
  5089. function waitForTick(fn) {
  5090. waitQueue.push(fn);
  5091. if (waitQueue.length > 1) return;
  5092. $$rAF(function() {
  5093. for (var i = 0; i < waitQueue.length; i++) {
  5094. waitQueue[i]();
  5095. }
  5096. waitQueue = [];
  5097. });
  5098. }
  5099. return function() {
  5100. var passed = false;
  5101. waitForTick(function() {
  5102. passed = true;
  5103. });
  5104. return function(callback) {
  5105. passed ? callback() : waitForTick(callback);
  5106. };
  5107. };
  5108. }];
  5109. };
  5110. var $$AnimateRunnerFactoryProvider = function() {
  5111. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$document', '$timeout',
  5112. function($q, $sniffer, $$animateAsyncRun, $document, $timeout) {
  5113. var INITIAL_STATE = 0;
  5114. var DONE_PENDING_STATE = 1;
  5115. var DONE_COMPLETE_STATE = 2;
  5116. AnimateRunner.chain = function(chain, callback) {
  5117. var index = 0;
  5118. next();
  5119. function next() {
  5120. if (index === chain.length) {
  5121. callback(true);
  5122. return;
  5123. }
  5124. chain[index](function(response) {
  5125. if (response === false) {
  5126. callback(false);
  5127. return;
  5128. }
  5129. index++;
  5130. next();
  5131. });
  5132. }
  5133. };
  5134. AnimateRunner.all = function(runners, callback) {
  5135. var count = 0;
  5136. var status = true;
  5137. forEach(runners, function(runner) {
  5138. runner.done(onProgress);
  5139. });
  5140. function onProgress(response) {
  5141. status = status && response;
  5142. if (++count === runners.length) {
  5143. callback(status);
  5144. }
  5145. }
  5146. };
  5147. function AnimateRunner(host) {
  5148. this.setHost(host);
  5149. var rafTick = $$animateAsyncRun();
  5150. var timeoutTick = function(fn) {
  5151. $timeout(fn, 0, false);
  5152. };
  5153. this._doneCallbacks = [];
  5154. this._tick = function(fn) {
  5155. var doc = $document[0];
  5156. // the document may not be ready or attached
  5157. // to the module for some internal tests
  5158. if (doc && doc.hidden) {
  5159. timeoutTick(fn);
  5160. } else {
  5161. rafTick(fn);
  5162. }
  5163. };
  5164. this._state = 0;
  5165. }
  5166. AnimateRunner.prototype = {
  5167. setHost: function(host) {
  5168. this.host = host || {};
  5169. },
  5170. done: function(fn) {
  5171. if (this._state === DONE_COMPLETE_STATE) {
  5172. fn();
  5173. } else {
  5174. this._doneCallbacks.push(fn);
  5175. }
  5176. },
  5177. progress: noop,
  5178. getPromise: function() {
  5179. if (!this.promise) {
  5180. var self = this;
  5181. this.promise = $q(function(resolve, reject) {
  5182. self.done(function(status) {
  5183. status === false ? reject() : resolve();
  5184. });
  5185. });
  5186. }
  5187. return this.promise;
  5188. },
  5189. then: function(resolveHandler, rejectHandler) {
  5190. return this.getPromise().then(resolveHandler, rejectHandler);
  5191. },
  5192. 'catch': function(handler) {
  5193. return this.getPromise()['catch'](handler);
  5194. },
  5195. 'finally': function(handler) {
  5196. return this.getPromise()['finally'](handler);
  5197. },
  5198. pause: function() {
  5199. if (this.host.pause) {
  5200. this.host.pause();
  5201. }
  5202. },
  5203. resume: function() {
  5204. if (this.host.resume) {
  5205. this.host.resume();
  5206. }
  5207. },
  5208. end: function() {
  5209. if (this.host.end) {
  5210. this.host.end();
  5211. }
  5212. this._resolve(true);
  5213. },
  5214. cancel: function() {
  5215. if (this.host.cancel) {
  5216. this.host.cancel();
  5217. }
  5218. this._resolve(false);
  5219. },
  5220. complete: function(response) {
  5221. var self = this;
  5222. if (self._state === INITIAL_STATE) {
  5223. self._state = DONE_PENDING_STATE;
  5224. self._tick(function() {
  5225. self._resolve(response);
  5226. });
  5227. }
  5228. },
  5229. _resolve: function(response) {
  5230. if (this._state !== DONE_COMPLETE_STATE) {
  5231. forEach(this._doneCallbacks, function(fn) {
  5232. fn(response);
  5233. });
  5234. this._doneCallbacks.length = 0;
  5235. this._state = DONE_COMPLETE_STATE;
  5236. }
  5237. }
  5238. };
  5239. return AnimateRunner;
  5240. }];
  5241. };
  5242. /**
  5243. * @ngdoc service
  5244. * @name $animateCss
  5245. * @kind object
  5246. *
  5247. * @description
  5248. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5249. * then the `$animateCss` service will actually perform animations.
  5250. *
  5251. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5252. */
  5253. var $CoreAnimateCssProvider = function() {
  5254. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5255. return function(element, initialOptions) {
  5256. // all of the animation functions should create
  5257. // a copy of the options data, however, if a
  5258. // parent service has already created a copy then
  5259. // we should stick to using that
  5260. var options = initialOptions || {};
  5261. if (!options.$$prepared) {
  5262. options = copy(options);
  5263. }
  5264. // there is no point in applying the styles since
  5265. // there is no animation that goes on at all in
  5266. // this version of $animateCss.
  5267. if (options.cleanupStyles) {
  5268. options.from = options.to = null;
  5269. }
  5270. if (options.from) {
  5271. element.css(options.from);
  5272. options.from = null;
  5273. }
  5274. /* jshint newcap: false */
  5275. var closed, runner = new $$AnimateRunner();
  5276. return {
  5277. start: run,
  5278. end: run
  5279. };
  5280. function run() {
  5281. $$rAF(function() {
  5282. applyAnimationContents();
  5283. if (!closed) {
  5284. runner.complete();
  5285. }
  5286. closed = true;
  5287. });
  5288. return runner;
  5289. }
  5290. function applyAnimationContents() {
  5291. if (options.addClass) {
  5292. element.addClass(options.addClass);
  5293. options.addClass = null;
  5294. }
  5295. if (options.removeClass) {
  5296. element.removeClass(options.removeClass);
  5297. options.removeClass = null;
  5298. }
  5299. if (options.to) {
  5300. element.css(options.to);
  5301. options.to = null;
  5302. }
  5303. }
  5304. };
  5305. }];
  5306. };
  5307. /* global stripHash: true */
  5308. /**
  5309. * ! This is a private undocumented service !
  5310. *
  5311. * @name $browser
  5312. * @requires $log
  5313. * @description
  5314. * This object has two goals:
  5315. *
  5316. * - hide all the global state in the browser caused by the window object
  5317. * - abstract away all the browser specific features and inconsistencies
  5318. *
  5319. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5320. * service, which can be used for convenient testing of the application without the interaction with
  5321. * the real browser apis.
  5322. */
  5323. /**
  5324. * @param {object} window The global window object.
  5325. * @param {object} document jQuery wrapped document.
  5326. * @param {object} $log window.console or an object with the same interface.
  5327. * @param {object} $sniffer $sniffer service
  5328. */
  5329. function Browser(window, document, $log, $sniffer) {
  5330. var self = this,
  5331. location = window.location,
  5332. history = window.history,
  5333. setTimeout = window.setTimeout,
  5334. clearTimeout = window.clearTimeout,
  5335. pendingDeferIds = {};
  5336. self.isMock = false;
  5337. var outstandingRequestCount = 0;
  5338. var outstandingRequestCallbacks = [];
  5339. // TODO(vojta): remove this temporary api
  5340. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5341. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5342. /**
  5343. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5344. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5345. */
  5346. function completeOutstandingRequest(fn) {
  5347. try {
  5348. fn.apply(null, sliceArgs(arguments, 1));
  5349. } finally {
  5350. outstandingRequestCount--;
  5351. if (outstandingRequestCount === 0) {
  5352. while (outstandingRequestCallbacks.length) {
  5353. try {
  5354. outstandingRequestCallbacks.pop()();
  5355. } catch (e) {
  5356. $log.error(e);
  5357. }
  5358. }
  5359. }
  5360. }
  5361. }
  5362. function getHash(url) {
  5363. var index = url.indexOf('#');
  5364. return index === -1 ? '' : url.substr(index);
  5365. }
  5366. /**
  5367. * @private
  5368. * Note: this method is used only by scenario runner
  5369. * TODO(vojta): prefix this method with $$ ?
  5370. * @param {function()} callback Function that will be called when no outstanding request
  5371. */
  5372. self.notifyWhenNoOutstandingRequests = function(callback) {
  5373. if (outstandingRequestCount === 0) {
  5374. callback();
  5375. } else {
  5376. outstandingRequestCallbacks.push(callback);
  5377. }
  5378. };
  5379. //////////////////////////////////////////////////////////////
  5380. // URL API
  5381. //////////////////////////////////////////////////////////////
  5382. var cachedState, lastHistoryState,
  5383. lastBrowserUrl = location.href,
  5384. baseElement = document.find('base'),
  5385. pendingLocation = null,
  5386. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5387. try {
  5388. return history.state;
  5389. } catch (e) {
  5390. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5391. }
  5392. };
  5393. cacheState();
  5394. lastHistoryState = cachedState;
  5395. /**
  5396. * @name $browser#url
  5397. *
  5398. * @description
  5399. * GETTER:
  5400. * Without any argument, this method just returns current value of location.href.
  5401. *
  5402. * SETTER:
  5403. * With at least one argument, this method sets url to new value.
  5404. * If html5 history api supported, pushState/replaceState is used, otherwise
  5405. * location.href/location.replace is used.
  5406. * Returns its own instance to allow chaining
  5407. *
  5408. * NOTE: this api is intended for use only by the $location service. Please use the
  5409. * {@link ng.$location $location service} to change url.
  5410. *
  5411. * @param {string} url New url (when used as setter)
  5412. * @param {boolean=} replace Should new url replace current history record?
  5413. * @param {object=} state object to use with pushState/replaceState
  5414. */
  5415. self.url = function(url, replace, state) {
  5416. // In modern browsers `history.state` is `null` by default; treating it separately
  5417. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5418. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5419. if (isUndefined(state)) {
  5420. state = null;
  5421. }
  5422. // Android Browser BFCache causes location, history reference to become stale.
  5423. if (location !== window.location) location = window.location;
  5424. if (history !== window.history) history = window.history;
  5425. // setter
  5426. if (url) {
  5427. var sameState = lastHistoryState === state;
  5428. // Don't change anything if previous and current URLs and states match. This also prevents
  5429. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5430. // See https://github.com/angular/angular.js/commit/ffb2701
  5431. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5432. return self;
  5433. }
  5434. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5435. lastBrowserUrl = url;
  5436. lastHistoryState = state;
  5437. // Don't use history API if only the hash changed
  5438. // due to a bug in IE10/IE11 which leads
  5439. // to not firing a `hashchange` nor `popstate` event
  5440. // in some cases (see #9143).
  5441. if ($sniffer.history && (!sameBase || !sameState)) {
  5442. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5443. cacheState();
  5444. // Do the assignment again so that those two variables are referentially identical.
  5445. lastHistoryState = cachedState;
  5446. } else {
  5447. if (!sameBase) {
  5448. pendingLocation = url;
  5449. }
  5450. if (replace) {
  5451. location.replace(url);
  5452. } else if (!sameBase) {
  5453. location.href = url;
  5454. } else {
  5455. location.hash = getHash(url);
  5456. }
  5457. if (location.href !== url) {
  5458. pendingLocation = url;
  5459. }
  5460. }
  5461. if (pendingLocation) {
  5462. pendingLocation = url;
  5463. }
  5464. return self;
  5465. // getter
  5466. } else {
  5467. // - pendingLocation is needed as browsers don't allow to read out
  5468. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5469. // https://openradar.appspot.com/22186109).
  5470. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5471. return pendingLocation || location.href.replace(/%27/g,"'");
  5472. }
  5473. };
  5474. /**
  5475. * @name $browser#state
  5476. *
  5477. * @description
  5478. * This method is a getter.
  5479. *
  5480. * Return history.state or null if history.state is undefined.
  5481. *
  5482. * @returns {object} state
  5483. */
  5484. self.state = function() {
  5485. return cachedState;
  5486. };
  5487. var urlChangeListeners = [],
  5488. urlChangeInit = false;
  5489. function cacheStateAndFireUrlChange() {
  5490. pendingLocation = null;
  5491. cacheState();
  5492. fireUrlChange();
  5493. }
  5494. // This variable should be used *only* inside the cacheState function.
  5495. var lastCachedState = null;
  5496. function cacheState() {
  5497. // This should be the only place in $browser where `history.state` is read.
  5498. cachedState = getCurrentState();
  5499. cachedState = isUndefined(cachedState) ? null : cachedState;
  5500. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5501. if (equals(cachedState, lastCachedState)) {
  5502. cachedState = lastCachedState;
  5503. }
  5504. lastCachedState = cachedState;
  5505. }
  5506. function fireUrlChange() {
  5507. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5508. return;
  5509. }
  5510. lastBrowserUrl = self.url();
  5511. lastHistoryState = cachedState;
  5512. forEach(urlChangeListeners, function(listener) {
  5513. listener(self.url(), cachedState);
  5514. });
  5515. }
  5516. /**
  5517. * @name $browser#onUrlChange
  5518. *
  5519. * @description
  5520. * Register callback function that will be called, when url changes.
  5521. *
  5522. * It's only called when the url is changed from outside of angular:
  5523. * - user types different url into address bar
  5524. * - user clicks on history (forward/back) button
  5525. * - user clicks on a link
  5526. *
  5527. * It's not called when url is changed by $browser.url() method
  5528. *
  5529. * The listener gets called with new url as parameter.
  5530. *
  5531. * NOTE: this api is intended for use only by the $location service. Please use the
  5532. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5533. *
  5534. * @param {function(string)} listener Listener function to be called when url changes.
  5535. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5536. */
  5537. self.onUrlChange = function(callback) {
  5538. // TODO(vojta): refactor to use node's syntax for events
  5539. if (!urlChangeInit) {
  5540. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5541. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5542. // changed by push/replaceState
  5543. // html5 history api - popstate event
  5544. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5545. // hashchange event
  5546. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5547. urlChangeInit = true;
  5548. }
  5549. urlChangeListeners.push(callback);
  5550. return callback;
  5551. };
  5552. /**
  5553. * @private
  5554. * Remove popstate and hashchange handler from window.
  5555. *
  5556. * NOTE: this api is intended for use only by $rootScope.
  5557. */
  5558. self.$$applicationDestroyed = function() {
  5559. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5560. };
  5561. /**
  5562. * Checks whether the url has changed outside of Angular.
  5563. * Needs to be exported to be able to check for changes that have been done in sync,
  5564. * as hashchange/popstate events fire in async.
  5565. */
  5566. self.$$checkUrlChange = fireUrlChange;
  5567. //////////////////////////////////////////////////////////////
  5568. // Misc API
  5569. //////////////////////////////////////////////////////////////
  5570. /**
  5571. * @name $browser#baseHref
  5572. *
  5573. * @description
  5574. * Returns current <base href>
  5575. * (always relative - without domain)
  5576. *
  5577. * @returns {string} The current base href
  5578. */
  5579. self.baseHref = function() {
  5580. var href = baseElement.attr('href');
  5581. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5582. };
  5583. /**
  5584. * @name $browser#defer
  5585. * @param {function()} fn A function, who's execution should be deferred.
  5586. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5587. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5588. *
  5589. * @description
  5590. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5591. *
  5592. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5593. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5594. * via `$browser.defer.flush()`.
  5595. *
  5596. */
  5597. self.defer = function(fn, delay) {
  5598. var timeoutId;
  5599. outstandingRequestCount++;
  5600. timeoutId = setTimeout(function() {
  5601. delete pendingDeferIds[timeoutId];
  5602. completeOutstandingRequest(fn);
  5603. }, delay || 0);
  5604. pendingDeferIds[timeoutId] = true;
  5605. return timeoutId;
  5606. };
  5607. /**
  5608. * @name $browser#defer.cancel
  5609. *
  5610. * @description
  5611. * Cancels a deferred task identified with `deferId`.
  5612. *
  5613. * @param {*} deferId Token returned by the `$browser.defer` function.
  5614. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5615. * canceled.
  5616. */
  5617. self.defer.cancel = function(deferId) {
  5618. if (pendingDeferIds[deferId]) {
  5619. delete pendingDeferIds[deferId];
  5620. clearTimeout(deferId);
  5621. completeOutstandingRequest(noop);
  5622. return true;
  5623. }
  5624. return false;
  5625. };
  5626. }
  5627. function $BrowserProvider() {
  5628. this.$get = ['$window', '$log', '$sniffer', '$document',
  5629. function($window, $log, $sniffer, $document) {
  5630. return new Browser($window, $document, $log, $sniffer);
  5631. }];
  5632. }
  5633. /**
  5634. * @ngdoc service
  5635. * @name $cacheFactory
  5636. *
  5637. * @description
  5638. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5639. * them.
  5640. *
  5641. * ```js
  5642. *
  5643. * var cache = $cacheFactory('cacheId');
  5644. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5645. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5646. *
  5647. * cache.put("key", "value");
  5648. * cache.put("another key", "another value");
  5649. *
  5650. * // We've specified no options on creation
  5651. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5652. *
  5653. * ```
  5654. *
  5655. *
  5656. * @param {string} cacheId Name or id of the newly created cache.
  5657. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5658. *
  5659. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5660. *
  5661. * @returns {object} Newly created cache object with the following set of methods:
  5662. *
  5663. * - `{object}` `info()` — Returns id, size, and options of cache.
  5664. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5665. * it.
  5666. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5667. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5668. * - `{void}` `removeAll()` — Removes all cached values.
  5669. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5670. *
  5671. * @example
  5672. <example module="cacheExampleApp">
  5673. <file name="index.html">
  5674. <div ng-controller="CacheController">
  5675. <input ng-model="newCacheKey" placeholder="Key">
  5676. <input ng-model="newCacheValue" placeholder="Value">
  5677. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5678. <p ng-if="keys.length">Cached Values</p>
  5679. <div ng-repeat="key in keys">
  5680. <span ng-bind="key"></span>
  5681. <span>: </span>
  5682. <b ng-bind="cache.get(key)"></b>
  5683. </div>
  5684. <p>Cache Info</p>
  5685. <div ng-repeat="(key, value) in cache.info()">
  5686. <span ng-bind="key"></span>
  5687. <span>: </span>
  5688. <b ng-bind="value"></b>
  5689. </div>
  5690. </div>
  5691. </file>
  5692. <file name="script.js">
  5693. angular.module('cacheExampleApp', []).
  5694. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5695. $scope.keys = [];
  5696. $scope.cache = $cacheFactory('cacheId');
  5697. $scope.put = function(key, value) {
  5698. if (angular.isUndefined($scope.cache.get(key))) {
  5699. $scope.keys.push(key);
  5700. }
  5701. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5702. };
  5703. }]);
  5704. </file>
  5705. <file name="style.css">
  5706. p {
  5707. margin: 10px 0 3px;
  5708. }
  5709. </file>
  5710. </example>
  5711. */
  5712. function $CacheFactoryProvider() {
  5713. this.$get = function() {
  5714. var caches = {};
  5715. function cacheFactory(cacheId, options) {
  5716. if (cacheId in caches) {
  5717. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5718. }
  5719. var size = 0,
  5720. stats = extend({}, options, {id: cacheId}),
  5721. data = createMap(),
  5722. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5723. lruHash = createMap(),
  5724. freshEnd = null,
  5725. staleEnd = null;
  5726. /**
  5727. * @ngdoc type
  5728. * @name $cacheFactory.Cache
  5729. *
  5730. * @description
  5731. * A cache object used to store and retrieve data, primarily used by
  5732. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5733. * templates and other data.
  5734. *
  5735. * ```js
  5736. * angular.module('superCache')
  5737. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5738. * return $cacheFactory('super-cache');
  5739. * }]);
  5740. * ```
  5741. *
  5742. * Example test:
  5743. *
  5744. * ```js
  5745. * it('should behave like a cache', inject(function(superCache) {
  5746. * superCache.put('key', 'value');
  5747. * superCache.put('another key', 'another value');
  5748. *
  5749. * expect(superCache.info()).toEqual({
  5750. * id: 'super-cache',
  5751. * size: 2
  5752. * });
  5753. *
  5754. * superCache.remove('another key');
  5755. * expect(superCache.get('another key')).toBeUndefined();
  5756. *
  5757. * superCache.removeAll();
  5758. * expect(superCache.info()).toEqual({
  5759. * id: 'super-cache',
  5760. * size: 0
  5761. * });
  5762. * }));
  5763. * ```
  5764. */
  5765. return caches[cacheId] = {
  5766. /**
  5767. * @ngdoc method
  5768. * @name $cacheFactory.Cache#put
  5769. * @kind function
  5770. *
  5771. * @description
  5772. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5773. * retrieved later, and incrementing the size of the cache if the key was not already
  5774. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5775. * entries from the set.
  5776. *
  5777. * It will not insert undefined values into the cache.
  5778. *
  5779. * @param {string} key the key under which the cached data is stored.
  5780. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5781. * will not be stored.
  5782. * @returns {*} the value stored.
  5783. */
  5784. put: function(key, value) {
  5785. if (isUndefined(value)) return;
  5786. if (capacity < Number.MAX_VALUE) {
  5787. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5788. refresh(lruEntry);
  5789. }
  5790. if (!(key in data)) size++;
  5791. data[key] = value;
  5792. if (size > capacity) {
  5793. this.remove(staleEnd.key);
  5794. }
  5795. return value;
  5796. },
  5797. /**
  5798. * @ngdoc method
  5799. * @name $cacheFactory.Cache#get
  5800. * @kind function
  5801. *
  5802. * @description
  5803. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5804. *
  5805. * @param {string} key the key of the data to be retrieved
  5806. * @returns {*} the value stored.
  5807. */
  5808. get: function(key) {
  5809. if (capacity < Number.MAX_VALUE) {
  5810. var lruEntry = lruHash[key];
  5811. if (!lruEntry) return;
  5812. refresh(lruEntry);
  5813. }
  5814. return data[key];
  5815. },
  5816. /**
  5817. * @ngdoc method
  5818. * @name $cacheFactory.Cache#remove
  5819. * @kind function
  5820. *
  5821. * @description
  5822. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5823. *
  5824. * @param {string} key the key of the entry to be removed
  5825. */
  5826. remove: function(key) {
  5827. if (capacity < Number.MAX_VALUE) {
  5828. var lruEntry = lruHash[key];
  5829. if (!lruEntry) return;
  5830. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5831. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5832. link(lruEntry.n,lruEntry.p);
  5833. delete lruHash[key];
  5834. }
  5835. if (!(key in data)) return;
  5836. delete data[key];
  5837. size--;
  5838. },
  5839. /**
  5840. * @ngdoc method
  5841. * @name $cacheFactory.Cache#removeAll
  5842. * @kind function
  5843. *
  5844. * @description
  5845. * Clears the cache object of any entries.
  5846. */
  5847. removeAll: function() {
  5848. data = createMap();
  5849. size = 0;
  5850. lruHash = createMap();
  5851. freshEnd = staleEnd = null;
  5852. },
  5853. /**
  5854. * @ngdoc method
  5855. * @name $cacheFactory.Cache#destroy
  5856. * @kind function
  5857. *
  5858. * @description
  5859. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5860. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5861. */
  5862. destroy: function() {
  5863. data = null;
  5864. stats = null;
  5865. lruHash = null;
  5866. delete caches[cacheId];
  5867. },
  5868. /**
  5869. * @ngdoc method
  5870. * @name $cacheFactory.Cache#info
  5871. * @kind function
  5872. *
  5873. * @description
  5874. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5875. *
  5876. * @returns {object} an object with the following properties:
  5877. * <ul>
  5878. * <li>**id**: the id of the cache instance</li>
  5879. * <li>**size**: the number of entries kept in the cache instance</li>
  5880. * <li>**...**: any additional properties from the options object when creating the
  5881. * cache.</li>
  5882. * </ul>
  5883. */
  5884. info: function() {
  5885. return extend({}, stats, {size: size});
  5886. }
  5887. };
  5888. /**
  5889. * makes the `entry` the freshEnd of the LRU linked list
  5890. */
  5891. function refresh(entry) {
  5892. if (entry != freshEnd) {
  5893. if (!staleEnd) {
  5894. staleEnd = entry;
  5895. } else if (staleEnd == entry) {
  5896. staleEnd = entry.n;
  5897. }
  5898. link(entry.n, entry.p);
  5899. link(entry, freshEnd);
  5900. freshEnd = entry;
  5901. freshEnd.n = null;
  5902. }
  5903. }
  5904. /**
  5905. * bidirectionally links two entries of the LRU linked list
  5906. */
  5907. function link(nextEntry, prevEntry) {
  5908. if (nextEntry != prevEntry) {
  5909. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5910. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5911. }
  5912. }
  5913. }
  5914. /**
  5915. * @ngdoc method
  5916. * @name $cacheFactory#info
  5917. *
  5918. * @description
  5919. * Get information about all the caches that have been created
  5920. *
  5921. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5922. */
  5923. cacheFactory.info = function() {
  5924. var info = {};
  5925. forEach(caches, function(cache, cacheId) {
  5926. info[cacheId] = cache.info();
  5927. });
  5928. return info;
  5929. };
  5930. /**
  5931. * @ngdoc method
  5932. * @name $cacheFactory#get
  5933. *
  5934. * @description
  5935. * Get access to a cache object by the `cacheId` used when it was created.
  5936. *
  5937. * @param {string} cacheId Name or id of a cache to access.
  5938. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5939. */
  5940. cacheFactory.get = function(cacheId) {
  5941. return caches[cacheId];
  5942. };
  5943. return cacheFactory;
  5944. };
  5945. }
  5946. /**
  5947. * @ngdoc service
  5948. * @name $templateCache
  5949. *
  5950. * @description
  5951. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5952. * can load templates directly into the cache in a `script` tag, or by consuming the
  5953. * `$templateCache` service directly.
  5954. *
  5955. * Adding via the `script` tag:
  5956. *
  5957. * ```html
  5958. * <script type="text/ng-template" id="templateId.html">
  5959. * <p>This is the content of the template</p>
  5960. * </script>
  5961. * ```
  5962. *
  5963. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5964. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5965. * element with ng-app attribute), otherwise the template will be ignored.
  5966. *
  5967. * Adding via the `$templateCache` service:
  5968. *
  5969. * ```js
  5970. * var myApp = angular.module('myApp', []);
  5971. * myApp.run(function($templateCache) {
  5972. * $templateCache.put('templateId.html', 'This is the content of the template');
  5973. * });
  5974. * ```
  5975. *
  5976. * To retrieve the template later, simply use it in your HTML:
  5977. * ```html
  5978. * <div ng-include=" 'templateId.html' "></div>
  5979. * ```
  5980. *
  5981. * or get it via Javascript:
  5982. * ```js
  5983. * $templateCache.get('templateId.html')
  5984. * ```
  5985. *
  5986. * See {@link ng.$cacheFactory $cacheFactory}.
  5987. *
  5988. */
  5989. function $TemplateCacheProvider() {
  5990. this.$get = ['$cacheFactory', function($cacheFactory) {
  5991. return $cacheFactory('templates');
  5992. }];
  5993. }
  5994. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5995. * Any commits to this file should be reviewed with security in mind. *
  5996. * Changes to this file can potentially create security vulnerabilities. *
  5997. * An approval from 2 Core members with history of modifying *
  5998. * this file is required. *
  5999. * *
  6000. * Does the change somehow allow for arbitrary javascript to be executed? *
  6001. * Or allows for someone to change the prototype of built-in objects? *
  6002. * Or gives undesired access to variables likes document or window? *
  6003. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6004. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6005. *
  6006. * DOM-related variables:
  6007. *
  6008. * - "node" - DOM Node
  6009. * - "element" - DOM Element or Node
  6010. * - "$node" or "$element" - jqLite-wrapped node or element
  6011. *
  6012. *
  6013. * Compiler related stuff:
  6014. *
  6015. * - "linkFn" - linking fn of a single directive
  6016. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6017. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6018. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6019. */
  6020. /**
  6021. * @ngdoc service
  6022. * @name $compile
  6023. * @kind function
  6024. *
  6025. * @description
  6026. * Compiles an HTML string or DOM into a template and produces a template function, which
  6027. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6028. *
  6029. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6030. * {@link ng.$compileProvider#directive directives}.
  6031. *
  6032. * <div class="alert alert-warning">
  6033. * **Note:** This document is an in-depth reference of all directive options.
  6034. * For a gentle introduction to directives with examples of common use cases,
  6035. * see the {@link guide/directive directive guide}.
  6036. * </div>
  6037. *
  6038. * ## Comprehensive Directive API
  6039. *
  6040. * There are many different options for a directive.
  6041. *
  6042. * The difference resides in the return value of the factory function.
  6043. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6044. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6045. * the default values).
  6046. *
  6047. * <div class="alert alert-success">
  6048. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6049. * </div>
  6050. *
  6051. * Here's an example directive declared with a Directive Definition Object:
  6052. *
  6053. * ```js
  6054. * var myModule = angular.module(...);
  6055. *
  6056. * myModule.directive('directiveName', function factory(injectables) {
  6057. * var directiveDefinitionObject = {
  6058. * priority: 0,
  6059. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6060. * // or
  6061. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6062. * transclude: false,
  6063. * restrict: 'A',
  6064. * templateNamespace: 'html',
  6065. * scope: false,
  6066. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6067. * controllerAs: 'stringIdentifier',
  6068. * bindToController: false,
  6069. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6070. * compile: function compile(tElement, tAttrs, transclude) {
  6071. * return {
  6072. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  6073. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  6074. * }
  6075. * // or
  6076. * // return function postLink( ... ) { ... }
  6077. * },
  6078. * // or
  6079. * // link: {
  6080. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  6081. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  6082. * // }
  6083. * // or
  6084. * // link: function postLink( ... ) { ... }
  6085. * };
  6086. * return directiveDefinitionObject;
  6087. * });
  6088. * ```
  6089. *
  6090. * <div class="alert alert-warning">
  6091. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6092. * </div>
  6093. *
  6094. * Therefore the above can be simplified as:
  6095. *
  6096. * ```js
  6097. * var myModule = angular.module(...);
  6098. *
  6099. * myModule.directive('directiveName', function factory(injectables) {
  6100. * var directiveDefinitionObject = {
  6101. * link: function postLink(scope, iElement, iAttrs) { ... }
  6102. * };
  6103. * return directiveDefinitionObject;
  6104. * // or
  6105. * // return function postLink(scope, iElement, iAttrs) { ... }
  6106. * });
  6107. * ```
  6108. *
  6109. * ### Life-cycle hooks
  6110. * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the
  6111. * directive:
  6112. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6113. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6114. * this element). This is a good place to put initialization code for your controller.
  6115. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6116. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6117. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6118. * component such as cloning the bound value to prevent accidental mutation of the outer value.
  6119. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6120. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6121. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6122. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6123. * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6124. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6125. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6126. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6127. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6128. * components will have their `$onDestroy()` hook called before child components.
  6129. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6130. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6131. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6132. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6133. * suspended until that occurs.
  6134. *
  6135. * #### Comparison with Angular 2 life-cycle hooks
  6136. * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are
  6137. * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:
  6138. *
  6139. * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.
  6140. * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6141. * In Angular 2 you can only define hooks on the prototype of the Component class.
  6142. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to
  6143. * `ngDoCheck` in Angular 2
  6144. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6145. * propagated throughout the application.
  6146. * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6147. * error or do nothing depending upon the state of `enableProdMode()`.
  6148. *
  6149. * #### Life-cycle hook examples
  6150. *
  6151. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6152. * has not changed.
  6153. *
  6154. * <example name="doCheckDateExample" module="do-check-module">
  6155. * <file name="app.js">
  6156. * angular.module('do-check-module', [])
  6157. * .component('app', {
  6158. * template:
  6159. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6160. * 'Date: {{ $ctrl.date }}' +
  6161. * '<test date="$ctrl.date"></test>',
  6162. * controller: function() {
  6163. * this.date = new Date();
  6164. * this.month = this.date.getMonth();
  6165. * this.updateDate = function() {
  6166. * this.date.setMonth(this.month);
  6167. * };
  6168. * }
  6169. * })
  6170. * .component('test', {
  6171. * bindings: { date: '<' },
  6172. * template:
  6173. * '<pre>{{ $ctrl.log | json }}</pre>',
  6174. * controller: function() {
  6175. * var previousValue;
  6176. * this.log = [];
  6177. * this.$doCheck = function() {
  6178. * var currentValue = this.date && this.date.valueOf();
  6179. * if (previousValue !== currentValue) {
  6180. * this.log.push('doCheck: date mutated: ' + this.date);
  6181. * previousValue = currentValue;
  6182. * }
  6183. * };
  6184. * }
  6185. * });
  6186. * </file>
  6187. * <file name="index.html">
  6188. * <app></app>
  6189. * </file>
  6190. * </example>
  6191. *
  6192. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6193. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6194. * arrays or objects can have a negative impact on your application performance)
  6195. *
  6196. * <example name="doCheckArrayExample" module="do-check-module">
  6197. * <file name="index.html">
  6198. * <div ng-init="items = []">
  6199. * <button ng-click="items.push(items.length)">Add Item</button>
  6200. * <button ng-click="items = []">Reset Items</button>
  6201. * <pre>{{ items }}</pre>
  6202. * <test items="items"></test>
  6203. * </div>
  6204. * </file>
  6205. * <file name="app.js">
  6206. * angular.module('do-check-module', [])
  6207. * .component('test', {
  6208. * bindings: { items: '<' },
  6209. * template:
  6210. * '<pre>{{ $ctrl.log | json }}</pre>',
  6211. * controller: function() {
  6212. * this.log = [];
  6213. *
  6214. * this.$doCheck = function() {
  6215. * if (this.items_ref !== this.items) {
  6216. * this.log.push('doCheck: items changed');
  6217. * this.items_ref = this.items;
  6218. * }
  6219. * if (!angular.equals(this.items_clone, this.items)) {
  6220. * this.log.push('doCheck: items mutated');
  6221. * this.items_clone = angular.copy(this.items);
  6222. * }
  6223. * };
  6224. * }
  6225. * });
  6226. * </file>
  6227. * </example>
  6228. *
  6229. *
  6230. * ### Directive Definition Object
  6231. *
  6232. * The directive definition object provides instructions to the {@link ng.$compile
  6233. * compiler}. The attributes are:
  6234. *
  6235. * #### `multiElement`
  6236. * When this property is set to true, the HTML compiler will collect DOM nodes between
  6237. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6238. * together as the directive elements. It is recommended that this feature be used on directives
  6239. * which are not strictly behavioral (such as {@link ngClick}), and which
  6240. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6241. *
  6242. * #### `priority`
  6243. * When there are multiple directives defined on a single DOM element, sometimes it
  6244. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6245. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6246. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6247. * are also run in priority order, but post-link functions are run in reverse order. The order
  6248. * of directives with the same priority is undefined. The default priority is `0`.
  6249. *
  6250. * #### `terminal`
  6251. * If set to true then the current `priority` will be the last set of directives
  6252. * which will execute (any directives at the current priority will still execute
  6253. * as the order of execution on same `priority` is undefined). Note that expressions
  6254. * and other directives used in the directive's template will also be excluded from execution.
  6255. *
  6256. * #### `scope`
  6257. * The scope property can be `true`, an object or a falsy value:
  6258. *
  6259. * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
  6260. *
  6261. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6262. * the directive's element. If multiple directives on the same element request a new scope,
  6263. * only one new scope is created. The new scope rule does not apply for the root of the template
  6264. * since the root of the template always gets a new scope.
  6265. *
  6266. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  6267. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  6268. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  6269. * data in the parent scope.
  6270. *
  6271. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6272. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6273. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6274. * is bound to the parent scope, via matching attributes on the directive's element:
  6275. *
  6276. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6277. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6278. * attribute name is assumed to be the same as the local name. Given `<my-component
  6279. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6280. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6281. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6282. * scope. The `name` is read from the parent scope (not the directive's scope).
  6283. *
  6284. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6285. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6286. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6287. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6288. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6289. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6290. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6291. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6292. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6293. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6294. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6295. * method is used for tracking changes, and the equality check is based on object identity.
  6296. * However, if an object literal or an array literal is passed as the binding expression, the
  6297. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6298. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6299. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6300. *
  6301. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6302. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6303. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6304. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6305. *
  6306. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6307. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6308. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6309. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6310. * two caveats:
  6311. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6312. * sets the same value. That means if your bound value is an object, changes to its properties
  6313. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6314. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6315. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6316. * to the value has changed. In most cases, this should not be of concern, but can be important
  6317. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6318. * If you now change a property of the object in your parent scope, the change will not be
  6319. * propagated to the isolated scope, because the identity of the object on the parent scope
  6320. * has not changed. Instead you must assign a new object.
  6321. *
  6322. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6323. * back to the parent. However, it does not make this completely impossible.
  6324. *
  6325. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6326. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6327. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6328. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6329. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6330. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6331. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6332. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6333. *
  6334. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6335. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6336. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6337. *
  6338. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6339. * * **child scope** + **no scope** => Both directives will share one single child scope
  6340. * * **child scope** + **child scope** => Both directives will share one single child scope
  6341. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6342. * its parent's scope
  6343. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6344. * be applied to the same element.
  6345. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6346. * cannot be applied to the same element.
  6347. *
  6348. *
  6349. * #### `bindToController`
  6350. * This property is used to bind scope properties directly to the controller. It can be either
  6351. * `true` or an object hash with the same format as the `scope` property. Additionally, a controller
  6352. * alias must be set, either by using `controllerAs: 'myAlias'` or by specifying the alias in the controller
  6353. * definition: `controller: 'myCtrl as myAlias'`.
  6354. *
  6355. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6356. * allow a component to have its properties bound to the controller, rather than to scope.
  6357. *
  6358. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6359. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6360. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6361. * initialized.
  6362. *
  6363. * <div class="alert alert-warning">
  6364. * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
  6365. * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
  6366. * code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6367. * </div>
  6368. *
  6369. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6370. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6371. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6372. * scope (useful for component directives).
  6373. *
  6374. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6375. *
  6376. *
  6377. * #### `controller`
  6378. * Controller constructor function. The controller is instantiated before the
  6379. * pre-linking phase and can be accessed by other directives (see
  6380. * `require` attribute). This allows the directives to communicate with each other and augment
  6381. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6382. *
  6383. * * `$scope` - Current scope associated with the element
  6384. * * `$element` - Current element
  6385. * * `$attrs` - Current attributes object for the element
  6386. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6387. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6388. * * `scope`: (optional) override the scope.
  6389. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6390. * * `futureParentElement` (optional):
  6391. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6392. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6393. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6394. * and when the `cloneLinkinFn` is passed,
  6395. * as those elements need to created and cloned in a special way when they are defined outside their
  6396. * usual containers (e.g. like `<svg>`).
  6397. * * See also the `directive.templateNamespace` property.
  6398. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6399. * then the default translusion is provided.
  6400. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6401. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6402. *
  6403. * #### `require`
  6404. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6405. * `require` property can be a string, an array or an object:
  6406. * * a **string** containing the name of the directive to pass to the linking function
  6407. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6408. * linking function will be an array of controllers in the same order as the names in the `require` property
  6409. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6410. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6411. * controllers.
  6412. *
  6413. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6414. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6415. * have been constructed but before `$onInit` is called.
  6416. * If the name of the required controller is the same as the local name (the key), the name can be
  6417. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6418. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6419. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6420. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6421. * controller, in which case error checking is skipped). The name can be prefixed with:
  6422. *
  6423. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6424. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6425. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6426. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6427. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6428. * `null` to the `link` fn if not found.
  6429. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6430. * `null` to the `link` fn if not found.
  6431. *
  6432. *
  6433. * #### `controllerAs`
  6434. * Identifier name for a reference to the controller in the directive's scope.
  6435. * This allows the controller to be referenced from the directive template. This is especially
  6436. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6437. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6438. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6439. *
  6440. *
  6441. * #### `restrict`
  6442. * String of subset of `EACM` which restricts the directive to a specific directive
  6443. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6444. *
  6445. * * `E` - Element name (default): `<my-directive></my-directive>`
  6446. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6447. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6448. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6449. *
  6450. *
  6451. * #### `templateNamespace`
  6452. * String representing the document type used by the markup in the template.
  6453. * AngularJS needs this information as those elements need to be created and cloned
  6454. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6455. *
  6456. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6457. * top-level elements such as `<svg>` or `<math>`.
  6458. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6459. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6460. *
  6461. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6462. *
  6463. * #### `template`
  6464. * HTML markup that may:
  6465. * * Replace the contents of the directive's element (default).
  6466. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6467. * * Wrap the contents of the directive's element (if `transclude` is true).
  6468. *
  6469. * Value may be:
  6470. *
  6471. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6472. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6473. * function api below) and returns a string value.
  6474. *
  6475. *
  6476. * #### `templateUrl`
  6477. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6478. *
  6479. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6480. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6481. * sibling and parent elements as though this element had not contained any directives.
  6482. *
  6483. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6484. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6485. * case when only one deeply nested directive has `templateUrl`.
  6486. *
  6487. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6488. *
  6489. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6490. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6491. * a string value representing the url. In either case, the template URL is passed through {@link
  6492. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6493. *
  6494. *
  6495. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6496. * specify what the template should replace. Defaults to `false`.
  6497. *
  6498. * * `true` - the template will replace the directive's element.
  6499. * * `false` - the template will replace the contents of the directive's element.
  6500. *
  6501. * The replacement process migrates all of the attributes / classes from the old element to the new
  6502. * one. See the {@link guide/directive#template-expanding-directive
  6503. * Directives Guide} for an example.
  6504. *
  6505. * There are very few scenarios where element replacement is required for the application function,
  6506. * the main one being reusable custom components that are used within SVG contexts
  6507. * (because SVG doesn't work with custom elements in the DOM tree).
  6508. *
  6509. * #### `transclude`
  6510. * Extract the contents of the element where the directive appears and make it available to the directive.
  6511. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6512. * {@link $compile#transclusion Transclusion} section below.
  6513. *
  6514. *
  6515. * #### `compile`
  6516. *
  6517. * ```js
  6518. * function compile(tElement, tAttrs, transclude) { ... }
  6519. * ```
  6520. *
  6521. * The compile function deals with transforming the template DOM. Since most directives do not do
  6522. * template transformation, it is not used often. The compile function takes the following arguments:
  6523. *
  6524. * * `tElement` - template element - The element where the directive has been declared. It is
  6525. * safe to do template transformation on the element and child elements only.
  6526. *
  6527. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6528. * between all directive compile functions.
  6529. *
  6530. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6531. *
  6532. * <div class="alert alert-warning">
  6533. * **Note:** The template instance and the link instance may be different objects if the template has
  6534. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6535. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6536. * should be done in a linking function rather than in a compile function.
  6537. * </div>
  6538. * <div class="alert alert-warning">
  6539. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6540. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6541. * stack overflow errors.
  6542. *
  6543. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6544. * a directive's template instead of relying on automatic template compilation via `template` or
  6545. * `templateUrl` declaration or manual compilation inside the compile function.
  6546. * </div>
  6547. *
  6548. * <div class="alert alert-danger">
  6549. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6550. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6551. * to the link function instead.
  6552. * </div>
  6553. * A compile function can have a return value which can be either a function or an object.
  6554. *
  6555. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6556. * `link` property of the config object when the compile function is empty.
  6557. *
  6558. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6559. * control when a linking function should be called during the linking phase. See info about
  6560. * pre-linking and post-linking functions below.
  6561. *
  6562. *
  6563. * #### `link`
  6564. * This property is used only if the `compile` property is not defined.
  6565. *
  6566. * ```js
  6567. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6568. * ```
  6569. *
  6570. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6571. * executed after the template has been cloned. This is where most of the directive logic will be
  6572. * put.
  6573. *
  6574. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6575. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6576. *
  6577. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6578. * manipulate the children of the element only in `postLink` function since the children have
  6579. * already been linked.
  6580. *
  6581. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6582. * between all directive linking functions.
  6583. *
  6584. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6585. * among all directives, which allows the directives to use the controllers as a communication
  6586. * channel. The exact value depends on the directive's `require` property:
  6587. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6588. * * `string`: the controller instance
  6589. * * `array`: array of controller instances
  6590. *
  6591. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6592. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6593. *
  6594. * Note that you can also require the directive's own controller - it will be made available like
  6595. * any other controller.
  6596. *
  6597. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6598. * This is the same as the `$transclude` parameter of directive controllers,
  6599. * see {@link ng.$compile#-controller- the controller section for details}.
  6600. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6601. *
  6602. * #### Pre-linking function
  6603. *
  6604. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6605. * compiler linking function will fail to locate the correct elements for linking.
  6606. *
  6607. * #### Post-linking function
  6608. *
  6609. * Executed after the child elements are linked.
  6610. *
  6611. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6612. * and linked since they are waiting for their template to load asynchronously and their own
  6613. * compilation and linking has been suspended until that occurs.
  6614. *
  6615. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6616. * for their async templates to be resolved.
  6617. *
  6618. *
  6619. * ### Transclusion
  6620. *
  6621. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6622. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6623. * scope from where they were taken.
  6624. *
  6625. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6626. * original contents of a directive's element into a specified place in the template of the directive.
  6627. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6628. * content has access to the properties on the scope from which it was taken, even if the directive
  6629. * has isolated scope.
  6630. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6631. *
  6632. * This makes it possible for the widget to have private state for its template, while the transcluded
  6633. * content has access to its originating scope.
  6634. *
  6635. * <div class="alert alert-warning">
  6636. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6637. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6638. * Testing Transclusion Directives}.
  6639. * </div>
  6640. *
  6641. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  6642. * directive's element, the entire element or multiple parts of the element contents:
  6643. *
  6644. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  6645. * * `'element'` - transclude the whole of the directive's element including any directives on this
  6646. * element that defined at a lower priority than this directive. When used, the `template`
  6647. * property is ignored.
  6648. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  6649. *
  6650. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  6651. *
  6652. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  6653. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  6654. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  6655. *
  6656. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6657. *
  6658. * If the element selector is prefixed with a `?` then that slot is optional.
  6659. *
  6660. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  6661. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  6662. *
  6663. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  6664. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  6665. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  6666. * injectable into the directive's controller.
  6667. *
  6668. *
  6669. * #### Transclusion Functions
  6670. *
  6671. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6672. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6673. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6674. *
  6675. * <div class="alert alert-info">
  6676. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6677. * ngTransclude will deal with it for us.
  6678. * </div>
  6679. *
  6680. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6681. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6682. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6683. *
  6684. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6685. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6686. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  6687. *
  6688. * <div class="alert alert-info">
  6689. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  6690. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6691. * </div>
  6692. *
  6693. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6694. * attach function**:
  6695. *
  6696. * ```js
  6697. * var transcludedContent, transclusionScope;
  6698. *
  6699. * $transclude(function(clone, scope) {
  6700. * element.append(clone);
  6701. * transcludedContent = clone;
  6702. * transclusionScope = scope;
  6703. * });
  6704. * ```
  6705. *
  6706. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6707. * associated transclusion scope:
  6708. *
  6709. * ```js
  6710. * transcludedContent.remove();
  6711. * transclusionScope.$destroy();
  6712. * ```
  6713. *
  6714. * <div class="alert alert-info">
  6715. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6716. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6717. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6718. * </div>
  6719. *
  6720. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6721. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  6722. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6723. *
  6724. *
  6725. * #### Transclusion Scopes
  6726. *
  6727. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6728. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6729. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6730. * was taken.
  6731. *
  6732. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6733. * like this:
  6734. *
  6735. * ```html
  6736. * <div ng-app>
  6737. * <div isolate>
  6738. * <div transclusion>
  6739. * </div>
  6740. * </div>
  6741. * </div>
  6742. * ```
  6743. *
  6744. * The `$parent` scope hierarchy will look like this:
  6745. *
  6746. ```
  6747. - $rootScope
  6748. - isolate
  6749. - transclusion
  6750. ```
  6751. *
  6752. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6753. *
  6754. ```
  6755. - $rootScope
  6756. - transclusion
  6757. - isolate
  6758. ```
  6759. *
  6760. *
  6761. * ### Attributes
  6762. *
  6763. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6764. * `link()` or `compile()` functions. It has a variety of uses.
  6765. *
  6766. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  6767. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  6768. * to the attributes.
  6769. *
  6770. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6771. * object which allows the directives to use the attributes object as inter directive
  6772. * communication.
  6773. *
  6774. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6775. * allowing other directives to read the interpolated value.
  6776. *
  6777. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6778. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6779. * the only way to easily get the actual value because during the linking phase the interpolation
  6780. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6781. *
  6782. * ```js
  6783. * function linkingFn(scope, elm, attrs, ctrl) {
  6784. * // get the attribute value
  6785. * console.log(attrs.ngModel);
  6786. *
  6787. * // change the attribute
  6788. * attrs.$set('ngModel', 'new value');
  6789. *
  6790. * // observe changes to interpolated attribute
  6791. * attrs.$observe('ngModel', function(value) {
  6792. * console.log('ngModel has changed value to ' + value);
  6793. * });
  6794. * }
  6795. * ```
  6796. *
  6797. * ## Example
  6798. *
  6799. * <div class="alert alert-warning">
  6800. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6801. * to illustrate how `$compile` works.
  6802. * </div>
  6803. *
  6804. <example module="compileExample">
  6805. <file name="index.html">
  6806. <script>
  6807. angular.module('compileExample', [], function($compileProvider) {
  6808. // configure new 'compile' directive by passing a directive
  6809. // factory function. The factory function injects the '$compile'
  6810. $compileProvider.directive('compile', function($compile) {
  6811. // directive factory creates a link function
  6812. return function(scope, element, attrs) {
  6813. scope.$watch(
  6814. function(scope) {
  6815. // watch the 'compile' expression for changes
  6816. return scope.$eval(attrs.compile);
  6817. },
  6818. function(value) {
  6819. // when the 'compile' expression changes
  6820. // assign it into the current DOM
  6821. element.html(value);
  6822. // compile the new DOM and link it to the current
  6823. // scope.
  6824. // NOTE: we only compile .childNodes so that
  6825. // we don't get into infinite loop compiling ourselves
  6826. $compile(element.contents())(scope);
  6827. }
  6828. );
  6829. };
  6830. });
  6831. })
  6832. .controller('GreeterController', ['$scope', function($scope) {
  6833. $scope.name = 'Angular';
  6834. $scope.html = 'Hello {{name}}';
  6835. }]);
  6836. </script>
  6837. <div ng-controller="GreeterController">
  6838. <input ng-model="name"> <br/>
  6839. <textarea ng-model="html"></textarea> <br/>
  6840. <div compile="html"></div>
  6841. </div>
  6842. </file>
  6843. <file name="protractor.js" type="protractor">
  6844. it('should auto compile', function() {
  6845. var textarea = $('textarea');
  6846. var output = $('div[compile]');
  6847. // The initial state reads 'Hello Angular'.
  6848. expect(output.getText()).toBe('Hello Angular');
  6849. textarea.clear();
  6850. textarea.sendKeys('{{name}}!');
  6851. expect(output.getText()).toBe('Angular!');
  6852. });
  6853. </file>
  6854. </example>
  6855. *
  6856. *
  6857. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6858. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6859. *
  6860. * <div class="alert alert-danger">
  6861. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6862. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6863. * `parentBoundTranscludeFn` to the link function instead.
  6864. * </div>
  6865. *
  6866. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6867. * root element(s), not their children)
  6868. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6869. * (a DOM element/tree) to a scope. Where:
  6870. *
  6871. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6872. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6873. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6874. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6875. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6876. *
  6877. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6878. * * `scope` - is the current scope with which the linking function is working with.
  6879. *
  6880. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6881. * keys may be used to control linking behavior:
  6882. *
  6883. * * `parentBoundTranscludeFn` - the transclude function made available to
  6884. * directives; if given, it will be passed through to the link functions of
  6885. * directives found in `element` during compilation.
  6886. * * `transcludeControllers` - an object hash with keys that map controller names
  6887. * to a hash with the key `instance`, which maps to the controller instance;
  6888. * if given, it will make the controllers available to directives on the compileNode:
  6889. * ```
  6890. * {
  6891. * parent: {
  6892. * instance: parentControllerInstance
  6893. * }
  6894. * }
  6895. * ```
  6896. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6897. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6898. * elements (e.g. SVG elements). See also the directive.controller property.
  6899. *
  6900. * Calling the linking function returns the element of the template. It is either the original
  6901. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6902. *
  6903. * After linking the view is not updated until after a call to $digest which typically is done by
  6904. * Angular automatically.
  6905. *
  6906. * If you need access to the bound view, there are two ways to do it:
  6907. *
  6908. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6909. * before you send them to the compiler and keep this reference around.
  6910. * ```js
  6911. * var element = $compile('<p>{{total}}</p>')(scope);
  6912. * ```
  6913. *
  6914. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6915. * example would not point to the clone, but rather to the original template that was cloned. In
  6916. * this case, you can access the clone via the cloneAttachFn:
  6917. * ```js
  6918. * var templateElement = angular.element('<p>{{total}}</p>'),
  6919. * scope = ....;
  6920. *
  6921. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6922. * //attach the clone to DOM document at the right place
  6923. * });
  6924. *
  6925. * //now we have reference to the cloned DOM via `clonedElement`
  6926. * ```
  6927. *
  6928. *
  6929. * For information on how the compiler works, see the
  6930. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6931. */
  6932. var $compileMinErr = minErr('$compile');
  6933. function UNINITIALIZED_VALUE() {}
  6934. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  6935. /**
  6936. * @ngdoc provider
  6937. * @name $compileProvider
  6938. *
  6939. * @description
  6940. */
  6941. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6942. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6943. var hasDirectives = {},
  6944. Suffix = 'Directive',
  6945. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6946. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6947. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6948. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6949. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6950. // The assumption is that future DOM event attribute names will begin with
  6951. // 'on' and be composed of only English letters.
  6952. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6953. var bindingCache = createMap();
  6954. function parseIsolateBindings(scope, directiveName, isController) {
  6955. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
  6956. var bindings = createMap();
  6957. forEach(scope, function(definition, scopeName) {
  6958. if (definition in bindingCache) {
  6959. bindings[scopeName] = bindingCache[definition];
  6960. return;
  6961. }
  6962. var match = definition.match(LOCAL_REGEXP);
  6963. if (!match) {
  6964. throw $compileMinErr('iscp',
  6965. "Invalid {3} for directive '{0}'." +
  6966. " Definition: {... {1}: '{2}' ...}",
  6967. directiveName, scopeName, definition,
  6968. (isController ? "controller bindings definition" :
  6969. "isolate scope definition"));
  6970. }
  6971. bindings[scopeName] = {
  6972. mode: match[1][0],
  6973. collection: match[2] === '*',
  6974. optional: match[3] === '?',
  6975. attrName: match[4] || scopeName
  6976. };
  6977. if (match[4]) {
  6978. bindingCache[definition] = bindings[scopeName];
  6979. }
  6980. });
  6981. return bindings;
  6982. }
  6983. function parseDirectiveBindings(directive, directiveName) {
  6984. var bindings = {
  6985. isolateScope: null,
  6986. bindToController: null
  6987. };
  6988. if (isObject(directive.scope)) {
  6989. if (directive.bindToController === true) {
  6990. bindings.bindToController = parseIsolateBindings(directive.scope,
  6991. directiveName, true);
  6992. bindings.isolateScope = {};
  6993. } else {
  6994. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6995. directiveName, false);
  6996. }
  6997. }
  6998. if (isObject(directive.bindToController)) {
  6999. bindings.bindToController =
  7000. parseIsolateBindings(directive.bindToController, directiveName, true);
  7001. }
  7002. if (isObject(bindings.bindToController)) {
  7003. var controller = directive.controller;
  7004. var controllerAs = directive.controllerAs;
  7005. if (!controller) {
  7006. // There is no controller, there may or may not be a controllerAs property
  7007. throw $compileMinErr('noctrl',
  7008. "Cannot bind to controller without directive '{0}'s controller.",
  7009. directiveName);
  7010. } else if (!identifierForController(controller, controllerAs)) {
  7011. // There is a controller, but no identifier or controllerAs property
  7012. throw $compileMinErr('noident',
  7013. "Cannot bind to controller without identifier for directive '{0}'.",
  7014. directiveName);
  7015. }
  7016. }
  7017. return bindings;
  7018. }
  7019. function assertValidDirectiveName(name) {
  7020. var letter = name.charAt(0);
  7021. if (!letter || letter !== lowercase(letter)) {
  7022. throw $compileMinErr('baddir', "Directive/Component name '{0}' is invalid. The first character must be a lowercase letter", name);
  7023. }
  7024. if (name !== name.trim()) {
  7025. throw $compileMinErr('baddir',
  7026. "Directive/Component name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  7027. name);
  7028. }
  7029. }
  7030. function getDirectiveRequire(directive) {
  7031. var require = directive.require || (directive.controller && directive.name);
  7032. if (!isArray(require) && isObject(require)) {
  7033. forEach(require, function(value, key) {
  7034. var match = value.match(REQUIRE_PREFIX_REGEXP);
  7035. var name = value.substring(match[0].length);
  7036. if (!name) require[key] = match[0] + key;
  7037. });
  7038. }
  7039. return require;
  7040. }
  7041. /**
  7042. * @ngdoc method
  7043. * @name $compileProvider#directive
  7044. * @kind function
  7045. *
  7046. * @description
  7047. * Register a new directive with the compiler.
  7048. *
  7049. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  7050. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  7051. * names and the values are the factories.
  7052. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  7053. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  7054. * @returns {ng.$compileProvider} Self for chaining.
  7055. */
  7056. this.directive = function registerDirective(name, directiveFactory) {
  7057. assertNotHasOwnProperty(name, 'directive');
  7058. if (isString(name)) {
  7059. assertValidDirectiveName(name);
  7060. assertArg(directiveFactory, 'directiveFactory');
  7061. if (!hasDirectives.hasOwnProperty(name)) {
  7062. hasDirectives[name] = [];
  7063. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  7064. function($injector, $exceptionHandler) {
  7065. var directives = [];
  7066. forEach(hasDirectives[name], function(directiveFactory, index) {
  7067. try {
  7068. var directive = $injector.invoke(directiveFactory);
  7069. if (isFunction(directive)) {
  7070. directive = { compile: valueFn(directive) };
  7071. } else if (!directive.compile && directive.link) {
  7072. directive.compile = valueFn(directive.link);
  7073. }
  7074. directive.priority = directive.priority || 0;
  7075. directive.index = index;
  7076. directive.name = directive.name || name;
  7077. directive.require = getDirectiveRequire(directive);
  7078. directive.restrict = directive.restrict || 'EA';
  7079. directive.$$moduleName = directiveFactory.$$moduleName;
  7080. directives.push(directive);
  7081. } catch (e) {
  7082. $exceptionHandler(e);
  7083. }
  7084. });
  7085. return directives;
  7086. }]);
  7087. }
  7088. hasDirectives[name].push(directiveFactory);
  7089. } else {
  7090. forEach(name, reverseParams(registerDirective));
  7091. }
  7092. return this;
  7093. };
  7094. /**
  7095. * @ngdoc method
  7096. * @name $compileProvider#component
  7097. * @module ng
  7098. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  7099. * @param {Object} options Component definition object (a simplified
  7100. * {@link ng.$compile#directive-definition-object directive definition object}),
  7101. * with the following properties (all optional):
  7102. *
  7103. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  7104. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  7105. * registered controller} if passed as a string. An empty `noop` function by default.
  7106. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  7107. * If present, the controller will be published to scope under the `controllerAs` name.
  7108. * If not present, this will default to be `$ctrl`.
  7109. * - `template` – `{string=|function()=}` – html template as a string or a function that
  7110. * returns an html template as a string which should be used as the contents of this component.
  7111. * Empty string by default.
  7112. *
  7113. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  7114. * the following locals:
  7115. *
  7116. * - `$element` - Current element
  7117. * - `$attrs` - Current attributes object for the element
  7118. *
  7119. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  7120. * template that should be used as the contents of this component.
  7121. *
  7122. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  7123. * the following locals:
  7124. *
  7125. * - `$element` - Current element
  7126. * - `$attrs` - Current attributes object for the element
  7127. *
  7128. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  7129. * Component properties are always bound to the component controller and not to the scope.
  7130. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  7131. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  7132. * Disabled by default.
  7133. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  7134. * this component's controller. The object keys specify the property names under which the required
  7135. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  7136. * - `$...` – additional properties to attach to the directive factory function and the controller
  7137. * constructor function. (This is used by the component router to annotate)
  7138. *
  7139. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  7140. * @description
  7141. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  7142. * type of directive, which represents a self-contained UI component in your application. Such components
  7143. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  7144. *
  7145. * Component definitions are very simple and do not require as much configuration as defining general
  7146. * directives. Component definitions usually consist only of a template and a controller backing it.
  7147. *
  7148. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  7149. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  7150. *
  7151. * Here are a few examples of how you would usually define components:
  7152. *
  7153. * ```js
  7154. * var myMod = angular.module(...);
  7155. * myMod.component('myComp', {
  7156. * template: '<div>My name is {{$ctrl.name}}</div>',
  7157. * controller: function() {
  7158. * this.name = 'shahar';
  7159. * }
  7160. * });
  7161. *
  7162. * myMod.component('myComp', {
  7163. * template: '<div>My name is {{$ctrl.name}}</div>',
  7164. * bindings: {name: '@'}
  7165. * });
  7166. *
  7167. * myMod.component('myComp', {
  7168. * templateUrl: 'views/my-comp.html',
  7169. * controller: 'MyCtrl',
  7170. * controllerAs: 'ctrl',
  7171. * bindings: {name: '@'}
  7172. * });
  7173. *
  7174. * ```
  7175. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  7176. *
  7177. * <br />
  7178. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  7179. */
  7180. this.component = function registerComponent(name, options) {
  7181. var controller = options.controller || function() {};
  7182. function factory($injector) {
  7183. function makeInjectable(fn) {
  7184. if (isFunction(fn) || isArray(fn)) {
  7185. return function(tElement, tAttrs) {
  7186. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  7187. };
  7188. } else {
  7189. return fn;
  7190. }
  7191. }
  7192. var template = (!options.template && !options.templateUrl ? '' : options.template);
  7193. var ddo = {
  7194. controller: controller,
  7195. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  7196. template: makeInjectable(template),
  7197. templateUrl: makeInjectable(options.templateUrl),
  7198. transclude: options.transclude,
  7199. scope: {},
  7200. bindToController: options.bindings || {},
  7201. restrict: 'E',
  7202. require: options.require
  7203. };
  7204. // Copy annotations (starting with $) over to the DDO
  7205. forEach(options, function(val, key) {
  7206. if (key.charAt(0) === '$') ddo[key] = val;
  7207. });
  7208. return ddo;
  7209. }
  7210. // TODO(pete) remove the following `forEach` before we release 1.6.0
  7211. // The component-router@0.2.0 looks for the annotations on the controller constructor
  7212. // Nothing in Angular looks for annotations on the factory function but we can't remove
  7213. // it from 1.5.x yet.
  7214. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  7215. // These could be used by libraries such as the new component router
  7216. forEach(options, function(val, key) {
  7217. if (key.charAt(0) === '$') {
  7218. factory[key] = val;
  7219. // Don't try to copy over annotations to named controller
  7220. if (isFunction(controller)) controller[key] = val;
  7221. }
  7222. });
  7223. factory.$inject = ['$injector'];
  7224. return this.directive(name, factory);
  7225. };
  7226. /**
  7227. * @ngdoc method
  7228. * @name $compileProvider#aHrefSanitizationWhitelist
  7229. * @kind function
  7230. *
  7231. * @description
  7232. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7233. * urls during a[href] sanitization.
  7234. *
  7235. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  7236. *
  7237. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  7238. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  7239. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7240. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7241. *
  7242. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7243. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7244. * chaining otherwise.
  7245. */
  7246. this.aHrefSanitizationWhitelist = function(regexp) {
  7247. if (isDefined(regexp)) {
  7248. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  7249. return this;
  7250. } else {
  7251. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  7252. }
  7253. };
  7254. /**
  7255. * @ngdoc method
  7256. * @name $compileProvider#imgSrcSanitizationWhitelist
  7257. * @kind function
  7258. *
  7259. * @description
  7260. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7261. * urls during img[src] sanitization.
  7262. *
  7263. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  7264. *
  7265. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7266. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7267. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7268. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7269. *
  7270. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7271. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7272. * chaining otherwise.
  7273. */
  7274. this.imgSrcSanitizationWhitelist = function(regexp) {
  7275. if (isDefined(regexp)) {
  7276. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7277. return this;
  7278. } else {
  7279. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7280. }
  7281. };
  7282. /**
  7283. * @ngdoc method
  7284. * @name $compileProvider#debugInfoEnabled
  7285. *
  7286. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7287. * current debugInfoEnabled state
  7288. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7289. *
  7290. * @kind function
  7291. *
  7292. * @description
  7293. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7294. * binding information and a reference to the current scope on to DOM elements.
  7295. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7296. * * `ng-binding` CSS class
  7297. * * `$binding` data property containing an array of the binding expressions
  7298. *
  7299. * You may want to disable this in production for a significant performance boost. See
  7300. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7301. *
  7302. * The default value is true.
  7303. */
  7304. var debugInfoEnabled = true;
  7305. this.debugInfoEnabled = function(enabled) {
  7306. if (isDefined(enabled)) {
  7307. debugInfoEnabled = enabled;
  7308. return this;
  7309. }
  7310. return debugInfoEnabled;
  7311. };
  7312. var TTL = 10;
  7313. /**
  7314. * @ngdoc method
  7315. * @name $compileProvider#onChangesTtl
  7316. * @description
  7317. *
  7318. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7319. * assuming that the model is unstable.
  7320. *
  7321. * The current default is 10 iterations.
  7322. *
  7323. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7324. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7325. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7326. * the `$onChanges` hook execution.
  7327. *
  7328. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7329. *
  7330. * @param {number} limit The number of `$onChanges` hook iterations.
  7331. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7332. */
  7333. this.onChangesTtl = function(value) {
  7334. if (arguments.length) {
  7335. TTL = value;
  7336. return this;
  7337. }
  7338. return TTL;
  7339. };
  7340. this.$get = [
  7341. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7342. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7343. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7344. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7345. var SIMPLE_ATTR_NAME = /^\w/;
  7346. var specialAttrHolder = window.document.createElement('div');
  7347. var onChangesTtl = TTL;
  7348. // The onChanges hooks should all be run together in a single digest
  7349. // When changes occur, the call to trigger their hooks will be added to this queue
  7350. var onChangesQueue;
  7351. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7352. function flushOnChangesQueue() {
  7353. try {
  7354. if (!(--onChangesTtl)) {
  7355. // We have hit the TTL limit so reset everything
  7356. onChangesQueue = undefined;
  7357. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7358. }
  7359. // We must run this hook in an apply since the $$postDigest runs outside apply
  7360. $rootScope.$apply(function() {
  7361. var errors = [];
  7362. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7363. try {
  7364. onChangesQueue[i]();
  7365. } catch (e) {
  7366. errors.push(e);
  7367. }
  7368. }
  7369. // Reset the queue to trigger a new schedule next time there is a change
  7370. onChangesQueue = undefined;
  7371. if (errors.length) {
  7372. throw errors;
  7373. }
  7374. });
  7375. } finally {
  7376. onChangesTtl++;
  7377. }
  7378. }
  7379. function Attributes(element, attributesToCopy) {
  7380. if (attributesToCopy) {
  7381. var keys = Object.keys(attributesToCopy);
  7382. var i, l, key;
  7383. for (i = 0, l = keys.length; i < l; i++) {
  7384. key = keys[i];
  7385. this[key] = attributesToCopy[key];
  7386. }
  7387. } else {
  7388. this.$attr = {};
  7389. }
  7390. this.$$element = element;
  7391. }
  7392. Attributes.prototype = {
  7393. /**
  7394. * @ngdoc method
  7395. * @name $compile.directive.Attributes#$normalize
  7396. * @kind function
  7397. *
  7398. * @description
  7399. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7400. * `data-`) to its normalized, camelCase form.
  7401. *
  7402. * Also there is special case for Moz prefix starting with upper case letter.
  7403. *
  7404. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7405. *
  7406. * @param {string} name Name to normalize
  7407. */
  7408. $normalize: directiveNormalize,
  7409. /**
  7410. * @ngdoc method
  7411. * @name $compile.directive.Attributes#$addClass
  7412. * @kind function
  7413. *
  7414. * @description
  7415. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7416. * are enabled then an animation will be triggered for the class addition.
  7417. *
  7418. * @param {string} classVal The className value that will be added to the element
  7419. */
  7420. $addClass: function(classVal) {
  7421. if (classVal && classVal.length > 0) {
  7422. $animate.addClass(this.$$element, classVal);
  7423. }
  7424. },
  7425. /**
  7426. * @ngdoc method
  7427. * @name $compile.directive.Attributes#$removeClass
  7428. * @kind function
  7429. *
  7430. * @description
  7431. * Removes the CSS class value specified by the classVal parameter from the element. If
  7432. * animations are enabled then an animation will be triggered for the class removal.
  7433. *
  7434. * @param {string} classVal The className value that will be removed from the element
  7435. */
  7436. $removeClass: function(classVal) {
  7437. if (classVal && classVal.length > 0) {
  7438. $animate.removeClass(this.$$element, classVal);
  7439. }
  7440. },
  7441. /**
  7442. * @ngdoc method
  7443. * @name $compile.directive.Attributes#$updateClass
  7444. * @kind function
  7445. *
  7446. * @description
  7447. * Adds and removes the appropriate CSS class values to the element based on the difference
  7448. * between the new and old CSS class values (specified as newClasses and oldClasses).
  7449. *
  7450. * @param {string} newClasses The current CSS className value
  7451. * @param {string} oldClasses The former CSS className value
  7452. */
  7453. $updateClass: function(newClasses, oldClasses) {
  7454. var toAdd = tokenDifference(newClasses, oldClasses);
  7455. if (toAdd && toAdd.length) {
  7456. $animate.addClass(this.$$element, toAdd);
  7457. }
  7458. var toRemove = tokenDifference(oldClasses, newClasses);
  7459. if (toRemove && toRemove.length) {
  7460. $animate.removeClass(this.$$element, toRemove);
  7461. }
  7462. },
  7463. /**
  7464. * Set a normalized attribute on the element in a way such that all directives
  7465. * can share the attribute. This function properly handles boolean attributes.
  7466. * @param {string} key Normalized key. (ie ngAttribute)
  7467. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  7468. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  7469. * Defaults to true.
  7470. * @param {string=} attrName Optional none normalized name. Defaults to key.
  7471. */
  7472. $set: function(key, value, writeAttr, attrName) {
  7473. // TODO: decide whether or not to throw an error if "class"
  7474. //is set through this function since it may cause $updateClass to
  7475. //become unstable.
  7476. var node = this.$$element[0],
  7477. booleanKey = getBooleanAttrName(node, key),
  7478. aliasedKey = getAliasedAttrName(key),
  7479. observer = key,
  7480. nodeName;
  7481. if (booleanKey) {
  7482. this.$$element.prop(key, value);
  7483. attrName = booleanKey;
  7484. } else if (aliasedKey) {
  7485. this[aliasedKey] = value;
  7486. observer = aliasedKey;
  7487. }
  7488. this[key] = value;
  7489. // translate normalized key to actual key
  7490. if (attrName) {
  7491. this.$attr[key] = attrName;
  7492. } else {
  7493. attrName = this.$attr[key];
  7494. if (!attrName) {
  7495. this.$attr[key] = attrName = snake_case(key, '-');
  7496. }
  7497. }
  7498. nodeName = nodeName_(this.$$element);
  7499. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  7500. (nodeName === 'img' && key === 'src')) {
  7501. // sanitize a[href] and img[src] values
  7502. this[key] = value = $$sanitizeUri(value, key === 'src');
  7503. } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
  7504. // sanitize img[srcset] values
  7505. var result = "";
  7506. // first check if there are spaces because it's not the same pattern
  7507. var trimmedSrcset = trim(value);
  7508. // ( 999x ,| 999w ,| ,|, )
  7509. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  7510. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  7511. // split srcset into tuple of uri and descriptor except for the last item
  7512. var rawUris = trimmedSrcset.split(pattern);
  7513. // for each tuples
  7514. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  7515. for (var i = 0; i < nbrUrisWith2parts; i++) {
  7516. var innerIdx = i * 2;
  7517. // sanitize the uri
  7518. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  7519. // add the descriptor
  7520. result += (" " + trim(rawUris[innerIdx + 1]));
  7521. }
  7522. // split the last item into uri and descriptor
  7523. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  7524. // sanitize the last uri
  7525. result += $$sanitizeUri(trim(lastTuple[0]), true);
  7526. // and add the last descriptor if any
  7527. if (lastTuple.length === 2) {
  7528. result += (" " + trim(lastTuple[1]));
  7529. }
  7530. this[key] = value = result;
  7531. }
  7532. if (writeAttr !== false) {
  7533. if (value === null || isUndefined(value)) {
  7534. this.$$element.removeAttr(attrName);
  7535. } else {
  7536. if (SIMPLE_ATTR_NAME.test(attrName)) {
  7537. this.$$element.attr(attrName, value);
  7538. } else {
  7539. setSpecialAttr(this.$$element[0], attrName, value);
  7540. }
  7541. }
  7542. }
  7543. // fire observers
  7544. var $$observers = this.$$observers;
  7545. $$observers && forEach($$observers[observer], function(fn) {
  7546. try {
  7547. fn(value);
  7548. } catch (e) {
  7549. $exceptionHandler(e);
  7550. }
  7551. });
  7552. },
  7553. /**
  7554. * @ngdoc method
  7555. * @name $compile.directive.Attributes#$observe
  7556. * @kind function
  7557. *
  7558. * @description
  7559. * Observes an interpolated attribute.
  7560. *
  7561. * The observer function will be invoked once during the next `$digest` following
  7562. * compilation. The observer is then invoked whenever the interpolated value
  7563. * changes.
  7564. *
  7565. * @param {string} key Normalized key. (ie ngAttribute) .
  7566. * @param {function(interpolatedValue)} fn Function that will be called whenever
  7567. the interpolated value of the attribute changes.
  7568. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  7569. * guide} for more info.
  7570. * @returns {function()} Returns a deregistration function for this observer.
  7571. */
  7572. $observe: function(key, fn) {
  7573. var attrs = this,
  7574. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  7575. listeners = ($$observers[key] || ($$observers[key] = []));
  7576. listeners.push(fn);
  7577. $rootScope.$evalAsync(function() {
  7578. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  7579. // no one registered attribute interpolation function, so lets call it manually
  7580. fn(attrs[key]);
  7581. }
  7582. });
  7583. return function() {
  7584. arrayRemove(listeners, fn);
  7585. };
  7586. }
  7587. };
  7588. function setSpecialAttr(element, attrName, value) {
  7589. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  7590. // so we have to jump through some hoops to get such an attribute
  7591. // https://github.com/angular/angular.js/pull/13318
  7592. specialAttrHolder.innerHTML = "<span " + attrName + ">";
  7593. var attributes = specialAttrHolder.firstChild.attributes;
  7594. var attribute = attributes[0];
  7595. // We have to remove the attribute from its container element before we can add it to the destination element
  7596. attributes.removeNamedItem(attribute.name);
  7597. attribute.value = value;
  7598. element.attributes.setNamedItem(attribute);
  7599. }
  7600. function safeAddClass($element, className) {
  7601. try {
  7602. $element.addClass(className);
  7603. } catch (e) {
  7604. // ignore, since it means that we are trying to set class on
  7605. // SVG element, where class name is read-only.
  7606. }
  7607. }
  7608. var startSymbol = $interpolate.startSymbol(),
  7609. endSymbol = $interpolate.endSymbol(),
  7610. denormalizeTemplate = (startSymbol == '{{' && endSymbol == '}}')
  7611. ? identity
  7612. : function denormalizeTemplate(template) {
  7613. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  7614. },
  7615. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  7616. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  7617. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  7618. var bindings = $element.data('$binding') || [];
  7619. if (isArray(binding)) {
  7620. bindings = bindings.concat(binding);
  7621. } else {
  7622. bindings.push(binding);
  7623. }
  7624. $element.data('$binding', bindings);
  7625. } : noop;
  7626. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  7627. safeAddClass($element, 'ng-binding');
  7628. } : noop;
  7629. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  7630. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  7631. $element.data(dataName, scope);
  7632. } : noop;
  7633. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  7634. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  7635. } : noop;
  7636. compile.$$createComment = function(directiveName, comment) {
  7637. var content = '';
  7638. if (debugInfoEnabled) {
  7639. content = ' ' + (directiveName || '') + ': ';
  7640. if (comment) content += comment + ' ';
  7641. }
  7642. return window.document.createComment(content);
  7643. };
  7644. return compile;
  7645. //================================
  7646. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  7647. previousCompileContext) {
  7648. if (!($compileNodes instanceof jqLite)) {
  7649. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  7650. // modify it.
  7651. $compileNodes = jqLite($compileNodes);
  7652. }
  7653. var NOT_EMPTY = /\S+/;
  7654. // We can not compile top level text elements since text nodes can be merged and we will
  7655. // not be able to attach scope data to them, so we will wrap them in <span>
  7656. for (var i = 0, len = $compileNodes.length; i < len; i++) {
  7657. var domNode = $compileNodes[i];
  7658. if (domNode.nodeType === NODE_TYPE_TEXT && domNode.nodeValue.match(NOT_EMPTY) /* non-empty */) {
  7659. jqLiteWrapNode(domNode, $compileNodes[i] = window.document.createElement('span'));
  7660. }
  7661. }
  7662. var compositeLinkFn =
  7663. compileNodes($compileNodes, transcludeFn, $compileNodes,
  7664. maxPriority, ignoreDirective, previousCompileContext);
  7665. compile.$$addScopeClass($compileNodes);
  7666. var namespace = null;
  7667. return function publicLinkFn(scope, cloneConnectFn, options) {
  7668. assertArg(scope, 'scope');
  7669. if (previousCompileContext && previousCompileContext.needsNewScope) {
  7670. // A parent directive did a replace and a directive on this element asked
  7671. // for transclusion, which caused us to lose a layer of element on which
  7672. // we could hold the new transclusion scope, so we will create it manually
  7673. // here.
  7674. scope = scope.$parent.$new();
  7675. }
  7676. options = options || {};
  7677. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  7678. transcludeControllers = options.transcludeControllers,
  7679. futureParentElement = options.futureParentElement;
  7680. // When `parentBoundTranscludeFn` is passed, it is a
  7681. // `controllersBoundTransclude` function (it was previously passed
  7682. // as `transclude` to directive.link) so we must unwrap it to get
  7683. // its `boundTranscludeFn`
  7684. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  7685. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  7686. }
  7687. if (!namespace) {
  7688. namespace = detectNamespaceForChildElements(futureParentElement);
  7689. }
  7690. var $linkNode;
  7691. if (namespace !== 'html') {
  7692. // When using a directive with replace:true and templateUrl the $compileNodes
  7693. // (or a child element inside of them)
  7694. // might change, so we need to recreate the namespace adapted compileNodes
  7695. // for call to the link function.
  7696. // Note: This will already clone the nodes...
  7697. $linkNode = jqLite(
  7698. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  7699. );
  7700. } else if (cloneConnectFn) {
  7701. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  7702. // and sometimes changes the structure of the DOM.
  7703. $linkNode = JQLitePrototype.clone.call($compileNodes);
  7704. } else {
  7705. $linkNode = $compileNodes;
  7706. }
  7707. if (transcludeControllers) {
  7708. for (var controllerName in transcludeControllers) {
  7709. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  7710. }
  7711. }
  7712. compile.$$addScopeInfo($linkNode, scope);
  7713. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  7714. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  7715. return $linkNode;
  7716. };
  7717. }
  7718. function detectNamespaceForChildElements(parentElement) {
  7719. // TODO: Make this detect MathML as well...
  7720. var node = parentElement && parentElement[0];
  7721. if (!node) {
  7722. return 'html';
  7723. } else {
  7724. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  7725. }
  7726. }
  7727. /**
  7728. * Compile function matches each node in nodeList against the directives. Once all directives
  7729. * for a particular node are collected their compile functions are executed. The compile
  7730. * functions return values - the linking functions - are combined into a composite linking
  7731. * function, which is the a linking function for the node.
  7732. *
  7733. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  7734. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7735. * scope argument is auto-generated to the new child of the transcluded parent scope.
  7736. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  7737. * the rootElement must be set the jqLite collection of the compile root. This is
  7738. * needed so that the jqLite collection items can be replaced with widgets.
  7739. * @param {number=} maxPriority Max directive priority.
  7740. * @returns {Function} A composite linking function of all of the matched directives or null.
  7741. */
  7742. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  7743. previousCompileContext) {
  7744. var linkFns = [],
  7745. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  7746. for (var i = 0; i < nodeList.length; i++) {
  7747. attrs = new Attributes();
  7748. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  7749. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  7750. ignoreDirective);
  7751. nodeLinkFn = (directives.length)
  7752. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  7753. null, [], [], previousCompileContext)
  7754. : null;
  7755. if (nodeLinkFn && nodeLinkFn.scope) {
  7756. compile.$$addScopeClass(attrs.$$element);
  7757. }
  7758. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  7759. !(childNodes = nodeList[i].childNodes) ||
  7760. !childNodes.length)
  7761. ? null
  7762. : compileNodes(childNodes,
  7763. nodeLinkFn ? (
  7764. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  7765. && nodeLinkFn.transclude) : transcludeFn);
  7766. if (nodeLinkFn || childLinkFn) {
  7767. linkFns.push(i, nodeLinkFn, childLinkFn);
  7768. linkFnFound = true;
  7769. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  7770. }
  7771. //use the previous context only for the first element in the virtual group
  7772. previousCompileContext = null;
  7773. }
  7774. // return a linking function if we have found anything, null otherwise
  7775. return linkFnFound ? compositeLinkFn : null;
  7776. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  7777. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  7778. var stableNodeList;
  7779. if (nodeLinkFnFound) {
  7780. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  7781. // offsets don't get screwed up
  7782. var nodeListLength = nodeList.length;
  7783. stableNodeList = new Array(nodeListLength);
  7784. // create a sparse array by only copying the elements which have a linkFn
  7785. for (i = 0; i < linkFns.length; i+=3) {
  7786. idx = linkFns[i];
  7787. stableNodeList[idx] = nodeList[idx];
  7788. }
  7789. } else {
  7790. stableNodeList = nodeList;
  7791. }
  7792. for (i = 0, ii = linkFns.length; i < ii;) {
  7793. node = stableNodeList[linkFns[i++]];
  7794. nodeLinkFn = linkFns[i++];
  7795. childLinkFn = linkFns[i++];
  7796. if (nodeLinkFn) {
  7797. if (nodeLinkFn.scope) {
  7798. childScope = scope.$new();
  7799. compile.$$addScopeInfo(jqLite(node), childScope);
  7800. } else {
  7801. childScope = scope;
  7802. }
  7803. if (nodeLinkFn.transcludeOnThisElement) {
  7804. childBoundTranscludeFn = createBoundTranscludeFn(
  7805. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  7806. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  7807. childBoundTranscludeFn = parentBoundTranscludeFn;
  7808. } else if (!parentBoundTranscludeFn && transcludeFn) {
  7809. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  7810. } else {
  7811. childBoundTranscludeFn = null;
  7812. }
  7813. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  7814. } else if (childLinkFn) {
  7815. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  7816. }
  7817. }
  7818. }
  7819. }
  7820. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  7821. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  7822. if (!transcludedScope) {
  7823. transcludedScope = scope.$new(false, containingScope);
  7824. transcludedScope.$$transcluded = true;
  7825. }
  7826. return transcludeFn(transcludedScope, cloneFn, {
  7827. parentBoundTranscludeFn: previousBoundTranscludeFn,
  7828. transcludeControllers: controllers,
  7829. futureParentElement: futureParentElement
  7830. });
  7831. }
  7832. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  7833. // so that they are available inside the `controllersBoundTransclude` function
  7834. var boundSlots = boundTranscludeFn.$$slots = createMap();
  7835. for (var slotName in transcludeFn.$$slots) {
  7836. if (transcludeFn.$$slots[slotName]) {
  7837. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  7838. } else {
  7839. boundSlots[slotName] = null;
  7840. }
  7841. }
  7842. return boundTranscludeFn;
  7843. }
  7844. /**
  7845. * Looks for directives on the given node and adds them to the directive collection which is
  7846. * sorted.
  7847. *
  7848. * @param node Node to search.
  7849. * @param directives An array to which the directives are added to. This array is sorted before
  7850. * the function returns.
  7851. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  7852. * @param {number=} maxPriority Max directive priority.
  7853. */
  7854. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  7855. var nodeType = node.nodeType,
  7856. attrsMap = attrs.$attr,
  7857. match,
  7858. className;
  7859. switch (nodeType) {
  7860. case NODE_TYPE_ELEMENT: /* Element */
  7861. // use the node name: <directive>
  7862. addDirective(directives,
  7863. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  7864. // iterate over the attributes
  7865. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  7866. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  7867. var attrStartName = false;
  7868. var attrEndName = false;
  7869. attr = nAttrs[j];
  7870. name = attr.name;
  7871. value = trim(attr.value);
  7872. // support ngAttr attribute binding
  7873. ngAttrName = directiveNormalize(name);
  7874. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  7875. name = name.replace(PREFIX_REGEXP, '')
  7876. .substr(8).replace(/_(.)/g, function(match, letter) {
  7877. return letter.toUpperCase();
  7878. });
  7879. }
  7880. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  7881. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  7882. attrStartName = name;
  7883. attrEndName = name.substr(0, name.length - 5) + 'end';
  7884. name = name.substr(0, name.length - 6);
  7885. }
  7886. nName = directiveNormalize(name.toLowerCase());
  7887. attrsMap[nName] = name;
  7888. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  7889. attrs[nName] = value;
  7890. if (getBooleanAttrName(node, nName)) {
  7891. attrs[nName] = true; // presence means true
  7892. }
  7893. }
  7894. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  7895. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  7896. attrEndName);
  7897. }
  7898. // use class as directive
  7899. className = node.className;
  7900. if (isObject(className)) {
  7901. // Maybe SVGAnimatedString
  7902. className = className.animVal;
  7903. }
  7904. if (isString(className) && className !== '') {
  7905. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  7906. nName = directiveNormalize(match[2]);
  7907. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  7908. attrs[nName] = trim(match[3]);
  7909. }
  7910. className = className.substr(match.index + match[0].length);
  7911. }
  7912. }
  7913. break;
  7914. case NODE_TYPE_TEXT: /* Text Node */
  7915. if (msie === 11) {
  7916. // Workaround for #11781
  7917. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  7918. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  7919. node.parentNode.removeChild(node.nextSibling);
  7920. }
  7921. }
  7922. addTextInterpolateDirective(directives, node.nodeValue);
  7923. break;
  7924. case NODE_TYPE_COMMENT: /* Comment */
  7925. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  7926. break;
  7927. }
  7928. directives.sort(byPriority);
  7929. return directives;
  7930. }
  7931. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  7932. // function created because of performance, try/catch disables
  7933. // the optimization of the whole function #14848
  7934. try {
  7935. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  7936. if (match) {
  7937. var nName = directiveNormalize(match[1]);
  7938. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  7939. attrs[nName] = trim(match[2]);
  7940. }
  7941. }
  7942. } catch (e) {
  7943. // turns out that under some circumstances IE9 throws errors when one attempts to read
  7944. // comment's node value.
  7945. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  7946. }
  7947. }
  7948. /**
  7949. * Given a node with an directive-start it collects all of the siblings until it finds
  7950. * directive-end.
  7951. * @param node
  7952. * @param attrStart
  7953. * @param attrEnd
  7954. * @returns {*}
  7955. */
  7956. function groupScan(node, attrStart, attrEnd) {
  7957. var nodes = [];
  7958. var depth = 0;
  7959. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  7960. do {
  7961. if (!node) {
  7962. throw $compileMinErr('uterdir',
  7963. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  7964. attrStart, attrEnd);
  7965. }
  7966. if (node.nodeType == NODE_TYPE_ELEMENT) {
  7967. if (node.hasAttribute(attrStart)) depth++;
  7968. if (node.hasAttribute(attrEnd)) depth--;
  7969. }
  7970. nodes.push(node);
  7971. node = node.nextSibling;
  7972. } while (depth > 0);
  7973. } else {
  7974. nodes.push(node);
  7975. }
  7976. return jqLite(nodes);
  7977. }
  7978. /**
  7979. * Wrapper for linking function which converts normal linking function into a grouped
  7980. * linking function.
  7981. * @param linkFn
  7982. * @param attrStart
  7983. * @param attrEnd
  7984. * @returns {Function}
  7985. */
  7986. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  7987. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  7988. element = groupScan(element[0], attrStart, attrEnd);
  7989. return linkFn(scope, element, attrs, controllers, transcludeFn);
  7990. };
  7991. }
  7992. /**
  7993. * A function generator that is used to support both eager and lazy compilation
  7994. * linking function.
  7995. * @param eager
  7996. * @param $compileNodes
  7997. * @param transcludeFn
  7998. * @param maxPriority
  7999. * @param ignoreDirective
  8000. * @param previousCompileContext
  8001. * @returns {Function}
  8002. */
  8003. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  8004. var compiled;
  8005. if (eager) {
  8006. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8007. }
  8008. return function lazyCompilation() {
  8009. if (!compiled) {
  8010. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8011. // Null out all of these references in order to make them eligible for garbage collection
  8012. // since this is a potentially long lived closure
  8013. $compileNodes = transcludeFn = previousCompileContext = null;
  8014. }
  8015. return compiled.apply(this, arguments);
  8016. };
  8017. }
  8018. /**
  8019. * Once the directives have been collected, their compile functions are executed. This method
  8020. * is responsible for inlining directive templates as well as terminating the application
  8021. * of the directives if the terminal directive has been reached.
  8022. *
  8023. * @param {Array} directives Array of collected directives to execute their compile function.
  8024. * this needs to be pre-sorted by priority order.
  8025. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  8026. * @param {Object} templateAttrs The shared attribute function
  8027. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8028. * scope argument is auto-generated to the new
  8029. * child of the transcluded parent scope.
  8030. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  8031. * argument has the root jqLite array so that we can replace nodes
  8032. * on it.
  8033. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  8034. * compiling the transclusion.
  8035. * @param {Array.<Function>} preLinkFns
  8036. * @param {Array.<Function>} postLinkFns
  8037. * @param {Object} previousCompileContext Context used for previous compilation of the current
  8038. * node
  8039. * @returns {Function} linkFn
  8040. */
  8041. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  8042. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  8043. previousCompileContext) {
  8044. previousCompileContext = previousCompileContext || {};
  8045. var terminalPriority = -Number.MAX_VALUE,
  8046. newScopeDirective = previousCompileContext.newScopeDirective,
  8047. controllerDirectives = previousCompileContext.controllerDirectives,
  8048. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  8049. templateDirective = previousCompileContext.templateDirective,
  8050. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  8051. hasTranscludeDirective = false,
  8052. hasTemplate = false,
  8053. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  8054. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  8055. directive,
  8056. directiveName,
  8057. $template,
  8058. replaceDirective = originalReplaceDirective,
  8059. childTranscludeFn = transcludeFn,
  8060. linkFn,
  8061. didScanForMultipleTransclusion = false,
  8062. mightHaveMultipleTransclusionError = false,
  8063. directiveValue;
  8064. // executes all directives on the current element
  8065. for (var i = 0, ii = directives.length; i < ii; i++) {
  8066. directive = directives[i];
  8067. var attrStart = directive.$$start;
  8068. var attrEnd = directive.$$end;
  8069. // collect multiblock sections
  8070. if (attrStart) {
  8071. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  8072. }
  8073. $template = undefined;
  8074. if (terminalPriority > directive.priority) {
  8075. break; // prevent further processing of directives
  8076. }
  8077. if (directiveValue = directive.scope) {
  8078. // skip the check for directives with async templates, we'll check the derived sync
  8079. // directive when the template arrives
  8080. if (!directive.templateUrl) {
  8081. if (isObject(directiveValue)) {
  8082. // This directive is trying to add an isolated scope.
  8083. // Check that there is no scope of any kind already
  8084. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  8085. directive, $compileNode);
  8086. newIsolateScopeDirective = directive;
  8087. } else {
  8088. // This directive is trying to add a child scope.
  8089. // Check that there is no isolated scope already
  8090. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  8091. $compileNode);
  8092. }
  8093. }
  8094. newScopeDirective = newScopeDirective || directive;
  8095. }
  8096. directiveName = directive.name;
  8097. // If we encounter a condition that can result in transclusion on the directive,
  8098. // then scan ahead in the remaining directives for others that may cause a multiple
  8099. // transclusion error to be thrown during the compilation process. If a matching directive
  8100. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  8101. // compile the `transclude` function rather than doing it lazily in order to throw
  8102. // exceptions at the correct time
  8103. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  8104. || (directive.transclude && !directive.$$tlb))) {
  8105. var candidateDirective;
  8106. for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
  8107. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  8108. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  8109. mightHaveMultipleTransclusionError = true;
  8110. break;
  8111. }
  8112. }
  8113. didScanForMultipleTransclusion = true;
  8114. }
  8115. if (!directive.templateUrl && directive.controller) {
  8116. directiveValue = directive.controller;
  8117. controllerDirectives = controllerDirectives || createMap();
  8118. assertNoDuplicate("'" + directiveName + "' controller",
  8119. controllerDirectives[directiveName], directive, $compileNode);
  8120. controllerDirectives[directiveName] = directive;
  8121. }
  8122. if (directiveValue = directive.transclude) {
  8123. hasTranscludeDirective = true;
  8124. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  8125. // This option should only be used by directives that know how to safely handle element transclusion,
  8126. // where the transcluded nodes are added or replaced after linking.
  8127. if (!directive.$$tlb) {
  8128. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  8129. nonTlbTranscludeDirective = directive;
  8130. }
  8131. if (directiveValue == 'element') {
  8132. hasElementTranscludeDirective = true;
  8133. terminalPriority = directive.priority;
  8134. $template = $compileNode;
  8135. $compileNode = templateAttrs.$$element =
  8136. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  8137. compileNode = $compileNode[0];
  8138. replaceWith(jqCollection, sliceArgs($template), compileNode);
  8139. // Support: Chrome < 50
  8140. // https://github.com/angular/angular.js/issues/14041
  8141. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  8142. // in the `replaceWith` function is improperly garbage collected despite still
  8143. // being referenced by the `parentNode` property of all of the child nodes. By adding
  8144. // a reference to the fragment via a different property, we can avoid that incorrect
  8145. // behavior.
  8146. // TODO: remove this line after Chrome 50 has been released
  8147. $template[0].$$parentNode = $template[0].parentNode;
  8148. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  8149. replaceDirective && replaceDirective.name, {
  8150. // Don't pass in:
  8151. // - controllerDirectives - otherwise we'll create duplicates controllers
  8152. // - newIsolateScopeDirective or templateDirective - combining templates with
  8153. // element transclusion doesn't make sense.
  8154. //
  8155. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  8156. // on the same element more than once.
  8157. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8158. });
  8159. } else {
  8160. var slots = createMap();
  8161. $template = jqLite(jqLiteClone(compileNode)).contents();
  8162. if (isObject(directiveValue)) {
  8163. // We have transclusion slots,
  8164. // collect them up, compile them and store their transclusion functions
  8165. $template = [];
  8166. var slotMap = createMap();
  8167. var filledSlots = createMap();
  8168. // Parse the element selectors
  8169. forEach(directiveValue, function(elementSelector, slotName) {
  8170. // If an element selector starts with a ? then it is optional
  8171. var optional = (elementSelector.charAt(0) === '?');
  8172. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  8173. slotMap[elementSelector] = slotName;
  8174. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  8175. // Later when calling boundTransclusion functions with a slot name we only error if the
  8176. // slot is `undefined`
  8177. slots[slotName] = null;
  8178. // filledSlots contains `true` for all slots that are either optional or have been
  8179. // filled. This is used to check that we have not missed any required slots
  8180. filledSlots[slotName] = optional;
  8181. });
  8182. // Add the matching elements into their slot
  8183. forEach($compileNode.contents(), function(node) {
  8184. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  8185. if (slotName) {
  8186. filledSlots[slotName] = true;
  8187. slots[slotName] = slots[slotName] || [];
  8188. slots[slotName].push(node);
  8189. } else {
  8190. $template.push(node);
  8191. }
  8192. });
  8193. // Check for required slots that were not filled
  8194. forEach(filledSlots, function(filled, slotName) {
  8195. if (!filled) {
  8196. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  8197. }
  8198. });
  8199. for (var slotName in slots) {
  8200. if (slots[slotName]) {
  8201. // Only define a transclusion function if the slot was filled
  8202. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  8203. }
  8204. }
  8205. }
  8206. $compileNode.empty(); // clear contents
  8207. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  8208. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  8209. childTranscludeFn.$$slots = slots;
  8210. }
  8211. }
  8212. if (directive.template) {
  8213. hasTemplate = true;
  8214. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8215. templateDirective = directive;
  8216. directiveValue = (isFunction(directive.template))
  8217. ? directive.template($compileNode, templateAttrs)
  8218. : directive.template;
  8219. directiveValue = denormalizeTemplate(directiveValue);
  8220. if (directive.replace) {
  8221. replaceDirective = directive;
  8222. if (jqLiteIsTextNode(directiveValue)) {
  8223. $template = [];
  8224. } else {
  8225. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  8226. }
  8227. compileNode = $template[0];
  8228. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8229. throw $compileMinErr('tplrt',
  8230. "Template for directive '{0}' must have exactly one root element. {1}",
  8231. directiveName, '');
  8232. }
  8233. replaceWith(jqCollection, $compileNode, compileNode);
  8234. var newTemplateAttrs = {$attr: {}};
  8235. // combine directives from the original node and from the template:
  8236. // - take the array of directives for this element
  8237. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  8238. // - collect directives from the template and sort them by priority
  8239. // - combine directives as: processed + template + unprocessed
  8240. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  8241. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  8242. if (newIsolateScopeDirective || newScopeDirective) {
  8243. // The original directive caused the current element to be replaced but this element
  8244. // also needs to have a new scope, so we need to tell the template directives
  8245. // that they would need to get their scope from further up, if they require transclusion
  8246. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  8247. }
  8248. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  8249. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  8250. ii = directives.length;
  8251. } else {
  8252. $compileNode.html(directiveValue);
  8253. }
  8254. }
  8255. if (directive.templateUrl) {
  8256. hasTemplate = true;
  8257. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8258. templateDirective = directive;
  8259. if (directive.replace) {
  8260. replaceDirective = directive;
  8261. }
  8262. /* jshint -W021 */
  8263. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  8264. /* jshint +W021 */
  8265. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  8266. controllerDirectives: controllerDirectives,
  8267. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  8268. newIsolateScopeDirective: newIsolateScopeDirective,
  8269. templateDirective: templateDirective,
  8270. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8271. });
  8272. ii = directives.length;
  8273. } else if (directive.compile) {
  8274. try {
  8275. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  8276. var context = directive.$$originalDirective || directive;
  8277. if (isFunction(linkFn)) {
  8278. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  8279. } else if (linkFn) {
  8280. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  8281. }
  8282. } catch (e) {
  8283. $exceptionHandler(e, startingTag($compileNode));
  8284. }
  8285. }
  8286. if (directive.terminal) {
  8287. nodeLinkFn.terminal = true;
  8288. terminalPriority = Math.max(terminalPriority, directive.priority);
  8289. }
  8290. }
  8291. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8292. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8293. nodeLinkFn.templateOnThisElement = hasTemplate;
  8294. nodeLinkFn.transclude = childTranscludeFn;
  8295. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8296. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8297. return nodeLinkFn;
  8298. ////////////////////
  8299. function addLinkFns(pre, post, attrStart, attrEnd) {
  8300. if (pre) {
  8301. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8302. pre.require = directive.require;
  8303. pre.directiveName = directiveName;
  8304. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8305. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8306. }
  8307. preLinkFns.push(pre);
  8308. }
  8309. if (post) {
  8310. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8311. post.require = directive.require;
  8312. post.directiveName = directiveName;
  8313. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8314. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8315. }
  8316. postLinkFns.push(post);
  8317. }
  8318. }
  8319. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8320. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8321. attrs, scopeBindingInfo;
  8322. if (compileNode === linkNode) {
  8323. attrs = templateAttrs;
  8324. $element = templateAttrs.$$element;
  8325. } else {
  8326. $element = jqLite(linkNode);
  8327. attrs = new Attributes($element, templateAttrs);
  8328. }
  8329. controllerScope = scope;
  8330. if (newIsolateScopeDirective) {
  8331. isolateScope = scope.$new(true);
  8332. } else if (newScopeDirective) {
  8333. controllerScope = scope.$parent;
  8334. }
  8335. if (boundTranscludeFn) {
  8336. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8337. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8338. transcludeFn = controllersBoundTransclude;
  8339. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8340. // expose the slots on the `$transclude` function
  8341. transcludeFn.isSlotFilled = function(slotName) {
  8342. return !!boundTranscludeFn.$$slots[slotName];
  8343. };
  8344. }
  8345. if (controllerDirectives) {
  8346. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8347. }
  8348. if (newIsolateScopeDirective) {
  8349. // Initialize isolate scope bindings for new isolate scope directive.
  8350. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8351. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8352. compile.$$addScopeClass($element, true);
  8353. isolateScope.$$isolateBindings =
  8354. newIsolateScopeDirective.$$isolateBindings;
  8355. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  8356. isolateScope.$$isolateBindings,
  8357. newIsolateScopeDirective);
  8358. if (scopeBindingInfo.removeWatches) {
  8359. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  8360. }
  8361. }
  8362. // Initialize bindToController bindings
  8363. for (var name in elementControllers) {
  8364. var controllerDirective = controllerDirectives[name];
  8365. var controller = elementControllers[name];
  8366. var bindings = controllerDirective.$$bindings.bindToController;
  8367. if (controller.identifier && bindings) {
  8368. controller.bindingInfo =
  8369. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8370. } else {
  8371. controller.bindingInfo = {};
  8372. }
  8373. var controllerResult = controller();
  8374. if (controllerResult !== controller.instance) {
  8375. // If the controller constructor has a return value, overwrite the instance
  8376. // from setupControllers
  8377. controller.instance = controllerResult;
  8378. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8379. controller.bindingInfo.removeWatches && controller.bindingInfo.removeWatches();
  8380. controller.bindingInfo =
  8381. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8382. }
  8383. }
  8384. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8385. forEach(controllerDirectives, function(controllerDirective, name) {
  8386. var require = controllerDirective.require;
  8387. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8388. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8389. }
  8390. });
  8391. // Handle the init and destroy lifecycle hooks on all controllers that have them
  8392. forEach(elementControllers, function(controller) {
  8393. var controllerInstance = controller.instance;
  8394. if (isFunction(controllerInstance.$onChanges)) {
  8395. try {
  8396. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  8397. } catch (e) {
  8398. $exceptionHandler(e);
  8399. }
  8400. }
  8401. if (isFunction(controllerInstance.$onInit)) {
  8402. try {
  8403. controllerInstance.$onInit();
  8404. } catch (e) {
  8405. $exceptionHandler(e);
  8406. }
  8407. }
  8408. if (isFunction(controllerInstance.$doCheck)) {
  8409. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  8410. controllerInstance.$doCheck();
  8411. }
  8412. if (isFunction(controllerInstance.$onDestroy)) {
  8413. controllerScope.$on('$destroy', function callOnDestroyHook() {
  8414. controllerInstance.$onDestroy();
  8415. });
  8416. }
  8417. });
  8418. // PRELINKING
  8419. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  8420. linkFn = preLinkFns[i];
  8421. invokeLinkFn(linkFn,
  8422. linkFn.isolateScope ? isolateScope : scope,
  8423. $element,
  8424. attrs,
  8425. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8426. transcludeFn
  8427. );
  8428. }
  8429. // RECURSION
  8430. // We only pass the isolate scope, if the isolate directive has a template,
  8431. // otherwise the child elements do not belong to the isolate directive.
  8432. var scopeToChild = scope;
  8433. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  8434. scopeToChild = isolateScope;
  8435. }
  8436. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  8437. // POSTLINKING
  8438. for (i = postLinkFns.length - 1; i >= 0; i--) {
  8439. linkFn = postLinkFns[i];
  8440. invokeLinkFn(linkFn,
  8441. linkFn.isolateScope ? isolateScope : scope,
  8442. $element,
  8443. attrs,
  8444. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8445. transcludeFn
  8446. );
  8447. }
  8448. // Trigger $postLink lifecycle hooks
  8449. forEach(elementControllers, function(controller) {
  8450. var controllerInstance = controller.instance;
  8451. if (isFunction(controllerInstance.$postLink)) {
  8452. controllerInstance.$postLink();
  8453. }
  8454. });
  8455. // This is the function that is injected as `$transclude`.
  8456. // Note: all arguments are optional!
  8457. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  8458. var transcludeControllers;
  8459. // No scope passed in:
  8460. if (!isScope(scope)) {
  8461. slotName = futureParentElement;
  8462. futureParentElement = cloneAttachFn;
  8463. cloneAttachFn = scope;
  8464. scope = undefined;
  8465. }
  8466. if (hasElementTranscludeDirective) {
  8467. transcludeControllers = elementControllers;
  8468. }
  8469. if (!futureParentElement) {
  8470. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  8471. }
  8472. if (slotName) {
  8473. // slotTranscludeFn can be one of three things:
  8474. // * a transclude function - a filled slot
  8475. // * `null` - an optional slot that was not filled
  8476. // * `undefined` - a slot that was not declared (i.e. invalid)
  8477. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  8478. if (slotTranscludeFn) {
  8479. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8480. } else if (isUndefined(slotTranscludeFn)) {
  8481. throw $compileMinErr('noslot',
  8482. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  8483. 'Element: {1}',
  8484. slotName, startingTag($element));
  8485. }
  8486. } else {
  8487. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8488. }
  8489. }
  8490. }
  8491. }
  8492. function getControllers(directiveName, require, $element, elementControllers) {
  8493. var value;
  8494. if (isString(require)) {
  8495. var match = require.match(REQUIRE_PREFIX_REGEXP);
  8496. var name = require.substring(match[0].length);
  8497. var inheritType = match[1] || match[3];
  8498. var optional = match[2] === '?';
  8499. //If only parents then start at the parent element
  8500. if (inheritType === '^^') {
  8501. $element = $element.parent();
  8502. //Otherwise attempt getting the controller from elementControllers in case
  8503. //the element is transcluded (and has no data) and to avoid .data if possible
  8504. } else {
  8505. value = elementControllers && elementControllers[name];
  8506. value = value && value.instance;
  8507. }
  8508. if (!value) {
  8509. var dataName = '$' + name + 'Controller';
  8510. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  8511. }
  8512. if (!value && !optional) {
  8513. throw $compileMinErr('ctreq',
  8514. "Controller '{0}', required by directive '{1}', can't be found!",
  8515. name, directiveName);
  8516. }
  8517. } else if (isArray(require)) {
  8518. value = [];
  8519. for (var i = 0, ii = require.length; i < ii; i++) {
  8520. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  8521. }
  8522. } else if (isObject(require)) {
  8523. value = {};
  8524. forEach(require, function(controller, property) {
  8525. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  8526. });
  8527. }
  8528. return value || null;
  8529. }
  8530. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  8531. var elementControllers = createMap();
  8532. for (var controllerKey in controllerDirectives) {
  8533. var directive = controllerDirectives[controllerKey];
  8534. var locals = {
  8535. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  8536. $element: $element,
  8537. $attrs: attrs,
  8538. $transclude: transcludeFn
  8539. };
  8540. var controller = directive.controller;
  8541. if (controller == '@') {
  8542. controller = attrs[directive.name];
  8543. }
  8544. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  8545. // For directives with element transclusion the element is a comment.
  8546. // In this case .data will not attach any data.
  8547. // Instead, we save the controllers for the element in a local hash and attach to .data
  8548. // later, once we have the actual element.
  8549. elementControllers[directive.name] = controllerInstance;
  8550. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  8551. }
  8552. return elementControllers;
  8553. }
  8554. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  8555. // or child scope created. For instance:
  8556. // * if the directive has been pulled into a template because another directive with a higher priority
  8557. // asked for element transclusion
  8558. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  8559. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  8560. function markDirectiveScope(directives, isolateScope, newScope) {
  8561. for (var j = 0, jj = directives.length; j < jj; j++) {
  8562. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  8563. }
  8564. }
  8565. /**
  8566. * looks up the directive and decorates it with exception handling and proper parameters. We
  8567. * call this the boundDirective.
  8568. *
  8569. * @param {string} name name of the directive to look up.
  8570. * @param {string} location The directive must be found in specific format.
  8571. * String containing any of theses characters:
  8572. *
  8573. * * `E`: element name
  8574. * * `A': attribute
  8575. * * `C`: class
  8576. * * `M`: comment
  8577. * @returns {boolean} true if directive was added.
  8578. */
  8579. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  8580. endAttrName) {
  8581. if (name === ignoreDirective) return null;
  8582. var match = null;
  8583. if (hasDirectives.hasOwnProperty(name)) {
  8584. for (var directive, directives = $injector.get(name + Suffix),
  8585. i = 0, ii = directives.length; i < ii; i++) {
  8586. try {
  8587. directive = directives[i];
  8588. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  8589. directive.restrict.indexOf(location) != -1) {
  8590. if (startAttrName) {
  8591. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  8592. }
  8593. if (!directive.$$bindings) {
  8594. var bindings = directive.$$bindings =
  8595. parseDirectiveBindings(directive, directive.name);
  8596. if (isObject(bindings.isolateScope)) {
  8597. directive.$$isolateBindings = bindings.isolateScope;
  8598. }
  8599. }
  8600. tDirectives.push(directive);
  8601. match = directive;
  8602. }
  8603. } catch (e) { $exceptionHandler(e); }
  8604. }
  8605. }
  8606. return match;
  8607. }
  8608. /**
  8609. * looks up the directive and returns true if it is a multi-element directive,
  8610. * and therefore requires DOM nodes between -start and -end markers to be grouped
  8611. * together.
  8612. *
  8613. * @param {string} name name of the directive to look up.
  8614. * @returns true if directive was registered as multi-element.
  8615. */
  8616. function directiveIsMultiElement(name) {
  8617. if (hasDirectives.hasOwnProperty(name)) {
  8618. for (var directive, directives = $injector.get(name + Suffix),
  8619. i = 0, ii = directives.length; i < ii; i++) {
  8620. directive = directives[i];
  8621. if (directive.multiElement) {
  8622. return true;
  8623. }
  8624. }
  8625. }
  8626. return false;
  8627. }
  8628. /**
  8629. * When the element is replaced with HTML template then the new attributes
  8630. * on the template need to be merged with the existing attributes in the DOM.
  8631. * The desired effect is to have both of the attributes present.
  8632. *
  8633. * @param {object} dst destination attributes (original DOM)
  8634. * @param {object} src source attributes (from the directive template)
  8635. */
  8636. function mergeTemplateAttributes(dst, src) {
  8637. var srcAttr = src.$attr,
  8638. dstAttr = dst.$attr,
  8639. $element = dst.$$element;
  8640. // reapply the old attributes to the new element
  8641. forEach(dst, function(value, key) {
  8642. if (key.charAt(0) != '$') {
  8643. if (src[key] && src[key] !== value) {
  8644. value += (key === 'style' ? ';' : ' ') + src[key];
  8645. }
  8646. dst.$set(key, value, true, srcAttr[key]);
  8647. }
  8648. });
  8649. // copy the new attributes on the old attrs object
  8650. forEach(src, function(value, key) {
  8651. // Check if we already set this attribute in the loop above.
  8652. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  8653. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  8654. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  8655. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  8656. dst[key] = value;
  8657. if (key !== 'class' && key !== 'style') {
  8658. dstAttr[key] = srcAttr[key];
  8659. }
  8660. }
  8661. });
  8662. }
  8663. function compileTemplateUrl(directives, $compileNode, tAttrs,
  8664. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  8665. var linkQueue = [],
  8666. afterTemplateNodeLinkFn,
  8667. afterTemplateChildLinkFn,
  8668. beforeTemplateCompileNode = $compileNode[0],
  8669. origAsyncDirective = directives.shift(),
  8670. derivedSyncDirective = inherit(origAsyncDirective, {
  8671. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  8672. }),
  8673. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  8674. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  8675. : origAsyncDirective.templateUrl,
  8676. templateNamespace = origAsyncDirective.templateNamespace;
  8677. $compileNode.empty();
  8678. $templateRequest(templateUrl)
  8679. .then(function(content) {
  8680. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  8681. content = denormalizeTemplate(content);
  8682. if (origAsyncDirective.replace) {
  8683. if (jqLiteIsTextNode(content)) {
  8684. $template = [];
  8685. } else {
  8686. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  8687. }
  8688. compileNode = $template[0];
  8689. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8690. throw $compileMinErr('tplrt',
  8691. "Template for directive '{0}' must have exactly one root element. {1}",
  8692. origAsyncDirective.name, templateUrl);
  8693. }
  8694. tempTemplateAttrs = {$attr: {}};
  8695. replaceWith($rootElement, $compileNode, compileNode);
  8696. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  8697. if (isObject(origAsyncDirective.scope)) {
  8698. // the original directive that caused the template to be loaded async required
  8699. // an isolate scope
  8700. markDirectiveScope(templateDirectives, true);
  8701. }
  8702. directives = templateDirectives.concat(directives);
  8703. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  8704. } else {
  8705. compileNode = beforeTemplateCompileNode;
  8706. $compileNode.html(content);
  8707. }
  8708. directives.unshift(derivedSyncDirective);
  8709. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  8710. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  8711. previousCompileContext);
  8712. forEach($rootElement, function(node, i) {
  8713. if (node == compileNode) {
  8714. $rootElement[i] = $compileNode[0];
  8715. }
  8716. });
  8717. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  8718. while (linkQueue.length) {
  8719. var scope = linkQueue.shift(),
  8720. beforeTemplateLinkNode = linkQueue.shift(),
  8721. linkRootElement = linkQueue.shift(),
  8722. boundTranscludeFn = linkQueue.shift(),
  8723. linkNode = $compileNode[0];
  8724. if (scope.$$destroyed) continue;
  8725. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  8726. var oldClasses = beforeTemplateLinkNode.className;
  8727. if (!(previousCompileContext.hasElementTranscludeDirective &&
  8728. origAsyncDirective.replace)) {
  8729. // it was cloned therefore we have to clone as well.
  8730. linkNode = jqLiteClone(compileNode);
  8731. }
  8732. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  8733. // Copy in CSS classes from original node
  8734. safeAddClass(jqLite(linkNode), oldClasses);
  8735. }
  8736. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8737. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8738. } else {
  8739. childBoundTranscludeFn = boundTranscludeFn;
  8740. }
  8741. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  8742. childBoundTranscludeFn);
  8743. }
  8744. linkQueue = null;
  8745. });
  8746. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  8747. var childBoundTranscludeFn = boundTranscludeFn;
  8748. if (scope.$$destroyed) return;
  8749. if (linkQueue) {
  8750. linkQueue.push(scope,
  8751. node,
  8752. rootElement,
  8753. childBoundTranscludeFn);
  8754. } else {
  8755. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8756. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8757. }
  8758. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  8759. }
  8760. };
  8761. }
  8762. /**
  8763. * Sorting function for bound directives.
  8764. */
  8765. function byPriority(a, b) {
  8766. var diff = b.priority - a.priority;
  8767. if (diff !== 0) return diff;
  8768. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  8769. return a.index - b.index;
  8770. }
  8771. function assertNoDuplicate(what, previousDirective, directive, element) {
  8772. function wrapModuleNameIfDefined(moduleName) {
  8773. return moduleName ?
  8774. (' (module: ' + moduleName + ')') :
  8775. '';
  8776. }
  8777. if (previousDirective) {
  8778. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  8779. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  8780. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  8781. }
  8782. }
  8783. function addTextInterpolateDirective(directives, text) {
  8784. var interpolateFn = $interpolate(text, true);
  8785. if (interpolateFn) {
  8786. directives.push({
  8787. priority: 0,
  8788. compile: function textInterpolateCompileFn(templateNode) {
  8789. var templateNodeParent = templateNode.parent(),
  8790. hasCompileParent = !!templateNodeParent.length;
  8791. // When transcluding a template that has bindings in the root
  8792. // we don't have a parent and thus need to add the class during linking fn.
  8793. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  8794. return function textInterpolateLinkFn(scope, node) {
  8795. var parent = node.parent();
  8796. if (!hasCompileParent) compile.$$addBindingClass(parent);
  8797. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  8798. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  8799. node[0].nodeValue = value;
  8800. });
  8801. };
  8802. }
  8803. });
  8804. }
  8805. }
  8806. function wrapTemplate(type, template) {
  8807. type = lowercase(type || 'html');
  8808. switch (type) {
  8809. case 'svg':
  8810. case 'math':
  8811. var wrapper = window.document.createElement('div');
  8812. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  8813. return wrapper.childNodes[0].childNodes;
  8814. default:
  8815. return template;
  8816. }
  8817. }
  8818. function getTrustedContext(node, attrNormalizedName) {
  8819. if (attrNormalizedName == "srcdoc") {
  8820. return $sce.HTML;
  8821. }
  8822. var tag = nodeName_(node);
  8823. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  8824. if (attrNormalizedName == "xlinkHref" ||
  8825. (tag == "form" && attrNormalizedName == "action") ||
  8826. (tag != "img" && (attrNormalizedName == "src" ||
  8827. attrNormalizedName == "ngSrc"))) {
  8828. return $sce.RESOURCE_URL;
  8829. }
  8830. }
  8831. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  8832. var trustedContext = getTrustedContext(node, name);
  8833. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  8834. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  8835. // no interpolation found -> ignore
  8836. if (!interpolateFn) return;
  8837. if (name === "multiple" && nodeName_(node) === "select") {
  8838. throw $compileMinErr("selmulti",
  8839. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  8840. startingTag(node));
  8841. }
  8842. directives.push({
  8843. priority: 100,
  8844. compile: function() {
  8845. return {
  8846. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  8847. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  8848. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  8849. throw $compileMinErr('nodomevents',
  8850. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  8851. "ng- versions (such as ng-click instead of onclick) instead.");
  8852. }
  8853. // If the attribute has changed since last $interpolate()ed
  8854. var newValue = attr[name];
  8855. if (newValue !== value) {
  8856. // we need to interpolate again since the attribute value has been updated
  8857. // (e.g. by another directive's compile function)
  8858. // ensure unset/empty values make interpolateFn falsy
  8859. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  8860. value = newValue;
  8861. }
  8862. // if attribute was updated so that there is no interpolation going on we don't want to
  8863. // register any observers
  8864. if (!interpolateFn) return;
  8865. // initialize attr object so that it's ready in case we need the value for isolate
  8866. // scope initialization, otherwise the value would not be available from isolate
  8867. // directive's linking fn during linking phase
  8868. attr[name] = interpolateFn(scope);
  8869. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  8870. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  8871. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  8872. //special case for class attribute addition + removal
  8873. //so that class changes can tap into the animation
  8874. //hooks provided by the $animate service. Be sure to
  8875. //skip animations when the first digest occurs (when
  8876. //both the new and the old values are the same) since
  8877. //the CSS classes are the non-interpolated values
  8878. if (name === 'class' && newValue != oldValue) {
  8879. attr.$updateClass(newValue, oldValue);
  8880. } else {
  8881. attr.$set(name, newValue);
  8882. }
  8883. });
  8884. }
  8885. };
  8886. }
  8887. });
  8888. }
  8889. /**
  8890. * This is a special jqLite.replaceWith, which can replace items which
  8891. * have no parents, provided that the containing jqLite collection is provided.
  8892. *
  8893. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  8894. * in the root of the tree.
  8895. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  8896. * the shell, but replace its DOM node reference.
  8897. * @param {Node} newNode The new DOM node.
  8898. */
  8899. function replaceWith($rootElement, elementsToRemove, newNode) {
  8900. var firstElementToRemove = elementsToRemove[0],
  8901. removeCount = elementsToRemove.length,
  8902. parent = firstElementToRemove.parentNode,
  8903. i, ii;
  8904. if ($rootElement) {
  8905. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  8906. if ($rootElement[i] == firstElementToRemove) {
  8907. $rootElement[i++] = newNode;
  8908. for (var j = i, j2 = j + removeCount - 1,
  8909. jj = $rootElement.length;
  8910. j < jj; j++, j2++) {
  8911. if (j2 < jj) {
  8912. $rootElement[j] = $rootElement[j2];
  8913. } else {
  8914. delete $rootElement[j];
  8915. }
  8916. }
  8917. $rootElement.length -= removeCount - 1;
  8918. // If the replaced element is also the jQuery .context then replace it
  8919. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  8920. // http://api.jquery.com/context/
  8921. if ($rootElement.context === firstElementToRemove) {
  8922. $rootElement.context = newNode;
  8923. }
  8924. break;
  8925. }
  8926. }
  8927. }
  8928. if (parent) {
  8929. parent.replaceChild(newNode, firstElementToRemove);
  8930. }
  8931. // Append all the `elementsToRemove` to a fragment. This will...
  8932. // - remove them from the DOM
  8933. // - allow them to still be traversed with .nextSibling
  8934. // - allow a single fragment.qSA to fetch all elements being removed
  8935. var fragment = window.document.createDocumentFragment();
  8936. for (i = 0; i < removeCount; i++) {
  8937. fragment.appendChild(elementsToRemove[i]);
  8938. }
  8939. if (jqLite.hasData(firstElementToRemove)) {
  8940. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  8941. // data here because there's no public interface in jQuery to do that and copying over
  8942. // event listeners (which is the main use of private data) wouldn't work anyway.
  8943. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  8944. // Remove $destroy event listeners from `firstElementToRemove`
  8945. jqLite(firstElementToRemove).off('$destroy');
  8946. }
  8947. // Cleanup any data/listeners on the elements and children.
  8948. // This includes invoking the $destroy event on any elements with listeners.
  8949. jqLite.cleanData(fragment.querySelectorAll('*'));
  8950. // Update the jqLite collection to only contain the `newNode`
  8951. for (i = 1; i < removeCount; i++) {
  8952. delete elementsToRemove[i];
  8953. }
  8954. elementsToRemove[0] = newNode;
  8955. elementsToRemove.length = 1;
  8956. }
  8957. function cloneAndAnnotateFn(fn, annotation) {
  8958. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  8959. }
  8960. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  8961. try {
  8962. linkFn(scope, $element, attrs, controllers, transcludeFn);
  8963. } catch (e) {
  8964. $exceptionHandler(e, startingTag($element));
  8965. }
  8966. }
  8967. // Set up $watches for isolate scope and controller bindings. This process
  8968. // only occurs for isolate scopes and new scopes with controllerAs.
  8969. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  8970. var removeWatchCollection = [];
  8971. var initialChanges = {};
  8972. var changes;
  8973. forEach(bindings, function initializeBinding(definition, scopeName) {
  8974. var attrName = definition.attrName,
  8975. optional = definition.optional,
  8976. mode = definition.mode, // @, =, <, or &
  8977. lastValue,
  8978. parentGet, parentSet, compare, removeWatch;
  8979. switch (mode) {
  8980. case '@':
  8981. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  8982. destination[scopeName] = attrs[attrName] = void 0;
  8983. }
  8984. attrs.$observe(attrName, function(value) {
  8985. if (isString(value) || isBoolean(value)) {
  8986. var oldValue = destination[scopeName];
  8987. recordChanges(scopeName, value, oldValue);
  8988. destination[scopeName] = value;
  8989. }
  8990. });
  8991. attrs.$$observers[attrName].$$scope = scope;
  8992. lastValue = attrs[attrName];
  8993. if (isString(lastValue)) {
  8994. // If the attribute has been provided then we trigger an interpolation to ensure
  8995. // the value is there for use in the link fn
  8996. destination[scopeName] = $interpolate(lastValue)(scope);
  8997. } else if (isBoolean(lastValue)) {
  8998. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  8999. // the value to boolean rather than a string, so we special case this situation
  9000. destination[scopeName] = lastValue;
  9001. }
  9002. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9003. break;
  9004. case '=':
  9005. if (!hasOwnProperty.call(attrs, attrName)) {
  9006. if (optional) break;
  9007. attrs[attrName] = void 0;
  9008. }
  9009. if (optional && !attrs[attrName]) break;
  9010. parentGet = $parse(attrs[attrName]);
  9011. if (parentGet.literal) {
  9012. compare = equals;
  9013. } else {
  9014. compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
  9015. }
  9016. parentSet = parentGet.assign || function() {
  9017. // reset the change, or we will throw this exception on every $digest
  9018. lastValue = destination[scopeName] = parentGet(scope);
  9019. throw $compileMinErr('nonassign',
  9020. "Expression '{0}' in attribute '{1}' used with directive '{2}' is non-assignable!",
  9021. attrs[attrName], attrName, directive.name);
  9022. };
  9023. lastValue = destination[scopeName] = parentGet(scope);
  9024. var parentValueWatch = function parentValueWatch(parentValue) {
  9025. if (!compare(parentValue, destination[scopeName])) {
  9026. // we are out of sync and need to copy
  9027. if (!compare(parentValue, lastValue)) {
  9028. // parent changed and it has precedence
  9029. destination[scopeName] = parentValue;
  9030. } else {
  9031. // if the parent can be assigned then do so
  9032. parentSet(scope, parentValue = destination[scopeName]);
  9033. }
  9034. }
  9035. return lastValue = parentValue;
  9036. };
  9037. parentValueWatch.$stateful = true;
  9038. if (definition.collection) {
  9039. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  9040. } else {
  9041. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  9042. }
  9043. removeWatchCollection.push(removeWatch);
  9044. break;
  9045. case '<':
  9046. if (!hasOwnProperty.call(attrs, attrName)) {
  9047. if (optional) break;
  9048. attrs[attrName] = void 0;
  9049. }
  9050. if (optional && !attrs[attrName]) break;
  9051. parentGet = $parse(attrs[attrName]);
  9052. var initialValue = destination[scopeName] = parentGet(scope);
  9053. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9054. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
  9055. if (oldValue === newValue) {
  9056. if (oldValue === initialValue) return;
  9057. oldValue = initialValue;
  9058. }
  9059. recordChanges(scopeName, newValue, oldValue);
  9060. destination[scopeName] = newValue;
  9061. }, parentGet.literal);
  9062. removeWatchCollection.push(removeWatch);
  9063. break;
  9064. case '&':
  9065. // Don't assign Object.prototype method to scope
  9066. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  9067. // Don't assign noop to destination if expression is not valid
  9068. if (parentGet === noop && optional) break;
  9069. destination[scopeName] = function(locals) {
  9070. return parentGet(scope, locals);
  9071. };
  9072. break;
  9073. }
  9074. });
  9075. function recordChanges(key, currentValue, previousValue) {
  9076. if (isFunction(destination.$onChanges) && currentValue !== previousValue) {
  9077. // If we have not already scheduled the top level onChangesQueue handler then do so now
  9078. if (!onChangesQueue) {
  9079. scope.$$postDigest(flushOnChangesQueue);
  9080. onChangesQueue = [];
  9081. }
  9082. // If we have not already queued a trigger of onChanges for this controller then do so now
  9083. if (!changes) {
  9084. changes = {};
  9085. onChangesQueue.push(triggerOnChangesHook);
  9086. }
  9087. // If the has been a change on this property already then we need to reuse the previous value
  9088. if (changes[key]) {
  9089. previousValue = changes[key].previousValue;
  9090. }
  9091. // Store this change
  9092. changes[key] = new SimpleChange(previousValue, currentValue);
  9093. }
  9094. }
  9095. function triggerOnChangesHook() {
  9096. destination.$onChanges(changes);
  9097. // Now clear the changes so that we schedule onChanges when more changes arrive
  9098. changes = undefined;
  9099. }
  9100. return {
  9101. initialChanges: initialChanges,
  9102. removeWatches: removeWatchCollection.length && function removeWatches() {
  9103. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  9104. removeWatchCollection[i]();
  9105. }
  9106. }
  9107. };
  9108. }
  9109. }];
  9110. }
  9111. function SimpleChange(previous, current) {
  9112. this.previousValue = previous;
  9113. this.currentValue = current;
  9114. }
  9115. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  9116. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  9117. /**
  9118. * Converts all accepted directives format into proper directive name.
  9119. * @param name Name to normalize
  9120. */
  9121. function directiveNormalize(name) {
  9122. return camelCase(name.replace(PREFIX_REGEXP, ''));
  9123. }
  9124. /**
  9125. * @ngdoc type
  9126. * @name $compile.directive.Attributes
  9127. *
  9128. * @description
  9129. * A shared object between directive compile / linking functions which contains normalized DOM
  9130. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  9131. * needed since all of these are treated as equivalent in Angular:
  9132. *
  9133. * ```
  9134. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  9135. * ```
  9136. */
  9137. /**
  9138. * @ngdoc property
  9139. * @name $compile.directive.Attributes#$attr
  9140. *
  9141. * @description
  9142. * A map of DOM element attribute names to the normalized name. This is
  9143. * needed to do reverse lookup from normalized name back to actual name.
  9144. */
  9145. /**
  9146. * @ngdoc method
  9147. * @name $compile.directive.Attributes#$set
  9148. * @kind function
  9149. *
  9150. * @description
  9151. * Set DOM element attribute value.
  9152. *
  9153. *
  9154. * @param {string} name Normalized element attribute name of the property to modify. The name is
  9155. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  9156. * property to the original name.
  9157. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  9158. */
  9159. /**
  9160. * Closure compiler type information
  9161. */
  9162. function nodesetLinkingFn(
  9163. /* angular.Scope */ scope,
  9164. /* NodeList */ nodeList,
  9165. /* Element */ rootElement,
  9166. /* function(Function) */ boundTranscludeFn
  9167. ) {}
  9168. function directiveLinkingFn(
  9169. /* nodesetLinkingFn */ nodesetLinkingFn,
  9170. /* angular.Scope */ scope,
  9171. /* Node */ node,
  9172. /* Element */ rootElement,
  9173. /* function(Function) */ boundTranscludeFn
  9174. ) {}
  9175. function tokenDifference(str1, str2) {
  9176. var values = '',
  9177. tokens1 = str1.split(/\s+/),
  9178. tokens2 = str2.split(/\s+/);
  9179. outer:
  9180. for (var i = 0; i < tokens1.length; i++) {
  9181. var token = tokens1[i];
  9182. for (var j = 0; j < tokens2.length; j++) {
  9183. if (token == tokens2[j]) continue outer;
  9184. }
  9185. values += (values.length > 0 ? ' ' : '') + token;
  9186. }
  9187. return values;
  9188. }
  9189. function removeComments(jqNodes) {
  9190. jqNodes = jqLite(jqNodes);
  9191. var i = jqNodes.length;
  9192. if (i <= 1) {
  9193. return jqNodes;
  9194. }
  9195. while (i--) {
  9196. var node = jqNodes[i];
  9197. if (node.nodeType === NODE_TYPE_COMMENT) {
  9198. splice.call(jqNodes, i, 1);
  9199. }
  9200. }
  9201. return jqNodes;
  9202. }
  9203. var $controllerMinErr = minErr('$controller');
  9204. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  9205. function identifierForController(controller, ident) {
  9206. if (ident && isString(ident)) return ident;
  9207. if (isString(controller)) {
  9208. var match = CNTRL_REG.exec(controller);
  9209. if (match) return match[3];
  9210. }
  9211. }
  9212. /**
  9213. * @ngdoc provider
  9214. * @name $controllerProvider
  9215. * @description
  9216. * The {@link ng.$controller $controller service} is used by Angular to create new
  9217. * controllers.
  9218. *
  9219. * This provider allows controller registration via the
  9220. * {@link ng.$controllerProvider#register register} method.
  9221. */
  9222. function $ControllerProvider() {
  9223. var controllers = {},
  9224. globals = false;
  9225. /**
  9226. * @ngdoc method
  9227. * @name $controllerProvider#has
  9228. * @param {string} name Controller name to check.
  9229. */
  9230. this.has = function(name) {
  9231. return controllers.hasOwnProperty(name);
  9232. };
  9233. /**
  9234. * @ngdoc method
  9235. * @name $controllerProvider#register
  9236. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  9237. * the names and the values are the constructors.
  9238. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  9239. * annotations in the array notation).
  9240. */
  9241. this.register = function(name, constructor) {
  9242. assertNotHasOwnProperty(name, 'controller');
  9243. if (isObject(name)) {
  9244. extend(controllers, name);
  9245. } else {
  9246. controllers[name] = constructor;
  9247. }
  9248. };
  9249. /**
  9250. * @ngdoc method
  9251. * @name $controllerProvider#allowGlobals
  9252. * @description If called, allows `$controller` to find controller constructors on `window`
  9253. */
  9254. this.allowGlobals = function() {
  9255. globals = true;
  9256. };
  9257. this.$get = ['$injector', '$window', function($injector, $window) {
  9258. /**
  9259. * @ngdoc service
  9260. * @name $controller
  9261. * @requires $injector
  9262. *
  9263. * @param {Function|string} constructor If called with a function then it's considered to be the
  9264. * controller constructor function. Otherwise it's considered to be a string which is used
  9265. * to retrieve the controller constructor using the following steps:
  9266. *
  9267. * * check if a controller with given name is registered via `$controllerProvider`
  9268. * * check if evaluating the string on the current scope returns a constructor
  9269. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  9270. * `window` object (not recommended)
  9271. *
  9272. * The string can use the `controller as property` syntax, where the controller instance is published
  9273. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  9274. * to work correctly.
  9275. *
  9276. * @param {Object} locals Injection locals for Controller.
  9277. * @return {Object} Instance of given controller.
  9278. *
  9279. * @description
  9280. * `$controller` service is responsible for instantiating controllers.
  9281. *
  9282. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  9283. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  9284. */
  9285. return function $controller(expression, locals, later, ident) {
  9286. // PRIVATE API:
  9287. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  9288. // If true, $controller will allocate the object with the correct
  9289. // prototype chain, but will not invoke the controller until a returned
  9290. // callback is invoked.
  9291. // param `ident` --- An optional label which overrides the label parsed from the controller
  9292. // expression, if any.
  9293. var instance, match, constructor, identifier;
  9294. later = later === true;
  9295. if (ident && isString(ident)) {
  9296. identifier = ident;
  9297. }
  9298. if (isString(expression)) {
  9299. match = expression.match(CNTRL_REG);
  9300. if (!match) {
  9301. throw $controllerMinErr('ctrlfmt',
  9302. "Badly formed controller string '{0}'. " +
  9303. "Must match `__name__ as __id__` or `__name__`.", expression);
  9304. }
  9305. constructor = match[1],
  9306. identifier = identifier || match[3];
  9307. expression = controllers.hasOwnProperty(constructor)
  9308. ? controllers[constructor]
  9309. : getter(locals.$scope, constructor, true) ||
  9310. (globals ? getter($window, constructor, true) : undefined);
  9311. assertArgFn(expression, constructor, true);
  9312. }
  9313. if (later) {
  9314. // Instantiate controller later:
  9315. // This machinery is used to create an instance of the object before calling the
  9316. // controller's constructor itself.
  9317. //
  9318. // This allows properties to be added to the controller before the constructor is
  9319. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9320. //
  9321. // This feature is not intended for use by applications, and is thus not documented
  9322. // publicly.
  9323. // Object creation: http://jsperf.com/create-constructor/2
  9324. var controllerPrototype = (isArray(expression) ?
  9325. expression[expression.length - 1] : expression).prototype;
  9326. instance = Object.create(controllerPrototype || null);
  9327. if (identifier) {
  9328. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9329. }
  9330. var instantiate;
  9331. return instantiate = extend(function $controllerInit() {
  9332. var result = $injector.invoke(expression, instance, locals, constructor);
  9333. if (result !== instance && (isObject(result) || isFunction(result))) {
  9334. instance = result;
  9335. if (identifier) {
  9336. // If result changed, re-assign controllerAs value to scope.
  9337. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9338. }
  9339. }
  9340. return instance;
  9341. }, {
  9342. instance: instance,
  9343. identifier: identifier
  9344. });
  9345. }
  9346. instance = $injector.instantiate(expression, locals, constructor);
  9347. if (identifier) {
  9348. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9349. }
  9350. return instance;
  9351. };
  9352. function addIdentifier(locals, identifier, instance, name) {
  9353. if (!(locals && isObject(locals.$scope))) {
  9354. throw minErr('$controller')('noscp',
  9355. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  9356. name, identifier);
  9357. }
  9358. locals.$scope[identifier] = instance;
  9359. }
  9360. }];
  9361. }
  9362. /**
  9363. * @ngdoc service
  9364. * @name $document
  9365. * @requires $window
  9366. *
  9367. * @description
  9368. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  9369. *
  9370. * @example
  9371. <example module="documentExample">
  9372. <file name="index.html">
  9373. <div ng-controller="ExampleController">
  9374. <p>$document title: <b ng-bind="title"></b></p>
  9375. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  9376. </div>
  9377. </file>
  9378. <file name="script.js">
  9379. angular.module('documentExample', [])
  9380. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  9381. $scope.title = $document[0].title;
  9382. $scope.windowTitle = angular.element(window.document)[0].title;
  9383. }]);
  9384. </file>
  9385. </example>
  9386. */
  9387. function $DocumentProvider() {
  9388. this.$get = ['$window', function(window) {
  9389. return jqLite(window.document);
  9390. }];
  9391. }
  9392. /**
  9393. * @ngdoc service
  9394. * @name $exceptionHandler
  9395. * @requires ng.$log
  9396. *
  9397. * @description
  9398. * Any uncaught exception in angular expressions is delegated to this service.
  9399. * The default implementation simply delegates to `$log.error` which logs it into
  9400. * the browser console.
  9401. *
  9402. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  9403. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  9404. *
  9405. * ## Example:
  9406. *
  9407. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  9408. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  9409. * of `$log.error()`.
  9410. *
  9411. * ```js
  9412. * angular.
  9413. * module('exceptionOverwrite', []).
  9414. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  9415. * return function myExceptionHandler(exception, cause) {
  9416. * logErrorsToBackend(exception, cause);
  9417. * $log.warn(exception, cause);
  9418. * };
  9419. * }]);
  9420. * ```
  9421. *
  9422. * <hr />
  9423. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  9424. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  9425. * (unless executed during a digest).
  9426. *
  9427. * If you wish, you can manually delegate exceptions, e.g.
  9428. * `try { ... } catch(e) { $exceptionHandler(e); }`
  9429. *
  9430. * @param {Error} exception Exception associated with the error.
  9431. * @param {string=} cause Optional information about the context in which
  9432. * the error was thrown.
  9433. *
  9434. */
  9435. function $ExceptionHandlerProvider() {
  9436. this.$get = ['$log', function($log) {
  9437. return function(exception, cause) {
  9438. $log.error.apply($log, arguments);
  9439. };
  9440. }];
  9441. }
  9442. var $$ForceReflowProvider = function() {
  9443. this.$get = ['$document', function($document) {
  9444. return function(domNode) {
  9445. //the line below will force the browser to perform a repaint so
  9446. //that all the animated elements within the animation frame will
  9447. //be properly updated and drawn on screen. This is required to
  9448. //ensure that the preparation animation is properly flushed so that
  9449. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  9450. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  9451. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  9452. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  9453. if (domNode) {
  9454. if (!domNode.nodeType && domNode instanceof jqLite) {
  9455. domNode = domNode[0];
  9456. }
  9457. } else {
  9458. domNode = $document[0].body;
  9459. }
  9460. return domNode.offsetWidth + 1;
  9461. };
  9462. }];
  9463. };
  9464. var APPLICATION_JSON = 'application/json';
  9465. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  9466. var JSON_START = /^\[|^\{(?!\{)/;
  9467. var JSON_ENDS = {
  9468. '[': /]$/,
  9469. '{': /}$/
  9470. };
  9471. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  9472. var $httpMinErr = minErr('$http');
  9473. var $httpMinErrLegacyFn = function(method) {
  9474. return function() {
  9475. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  9476. };
  9477. };
  9478. function serializeValue(v) {
  9479. if (isObject(v)) {
  9480. return isDate(v) ? v.toISOString() : toJson(v);
  9481. }
  9482. return v;
  9483. }
  9484. function $HttpParamSerializerProvider() {
  9485. /**
  9486. * @ngdoc service
  9487. * @name $httpParamSerializer
  9488. * @description
  9489. *
  9490. * Default {@link $http `$http`} params serializer that converts objects to strings
  9491. * according to the following rules:
  9492. *
  9493. * * `{'foo': 'bar'}` results in `foo=bar`
  9494. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  9495. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  9496. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  9497. *
  9498. * Note that serializer will sort the request parameters alphabetically.
  9499. * */
  9500. this.$get = function() {
  9501. return function ngParamSerializer(params) {
  9502. if (!params) return '';
  9503. var parts = [];
  9504. forEachSorted(params, function(value, key) {
  9505. if (value === null || isUndefined(value)) return;
  9506. if (isArray(value)) {
  9507. forEach(value, function(v) {
  9508. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  9509. });
  9510. } else {
  9511. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  9512. }
  9513. });
  9514. return parts.join('&');
  9515. };
  9516. };
  9517. }
  9518. function $HttpParamSerializerJQLikeProvider() {
  9519. /**
  9520. * @ngdoc service
  9521. * @name $httpParamSerializerJQLike
  9522. * @description
  9523. *
  9524. * Alternative {@link $http `$http`} params serializer that follows
  9525. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  9526. * The serializer will also sort the params alphabetically.
  9527. *
  9528. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  9529. *
  9530. * ```js
  9531. * $http({
  9532. * url: myUrl,
  9533. * method: 'GET',
  9534. * params: myParams,
  9535. * paramSerializer: '$httpParamSerializerJQLike'
  9536. * });
  9537. * ```
  9538. *
  9539. * It is also possible to set it as the default `paramSerializer` in the
  9540. * {@link $httpProvider#defaults `$httpProvider`}.
  9541. *
  9542. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  9543. * form data for submission:
  9544. *
  9545. * ```js
  9546. * .controller(function($http, $httpParamSerializerJQLike) {
  9547. * //...
  9548. *
  9549. * $http({
  9550. * url: myUrl,
  9551. * method: 'POST',
  9552. * data: $httpParamSerializerJQLike(myData),
  9553. * headers: {
  9554. * 'Content-Type': 'application/x-www-form-urlencoded'
  9555. * }
  9556. * });
  9557. *
  9558. * });
  9559. * ```
  9560. *
  9561. * */
  9562. this.$get = function() {
  9563. return function jQueryLikeParamSerializer(params) {
  9564. if (!params) return '';
  9565. var parts = [];
  9566. serialize(params, '', true);
  9567. return parts.join('&');
  9568. function serialize(toSerialize, prefix, topLevel) {
  9569. if (toSerialize === null || isUndefined(toSerialize)) return;
  9570. if (isArray(toSerialize)) {
  9571. forEach(toSerialize, function(value, index) {
  9572. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  9573. });
  9574. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  9575. forEachSorted(toSerialize, function(value, key) {
  9576. serialize(value, prefix +
  9577. (topLevel ? '' : '[') +
  9578. key +
  9579. (topLevel ? '' : ']'));
  9580. });
  9581. } else {
  9582. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  9583. }
  9584. }
  9585. };
  9586. };
  9587. }
  9588. function defaultHttpResponseTransform(data, headers) {
  9589. if (isString(data)) {
  9590. // Strip json vulnerability protection prefix and trim whitespace
  9591. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  9592. if (tempData) {
  9593. var contentType = headers('Content-Type');
  9594. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  9595. data = fromJson(tempData);
  9596. }
  9597. }
  9598. }
  9599. return data;
  9600. }
  9601. function isJsonLike(str) {
  9602. var jsonStart = str.match(JSON_START);
  9603. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  9604. }
  9605. /**
  9606. * Parse headers into key value object
  9607. *
  9608. * @param {string} headers Raw headers as a string
  9609. * @returns {Object} Parsed headers as key value object
  9610. */
  9611. function parseHeaders(headers) {
  9612. var parsed = createMap(), i;
  9613. function fillInParsed(key, val) {
  9614. if (key) {
  9615. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  9616. }
  9617. }
  9618. if (isString(headers)) {
  9619. forEach(headers.split('\n'), function(line) {
  9620. i = line.indexOf(':');
  9621. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  9622. });
  9623. } else if (isObject(headers)) {
  9624. forEach(headers, function(headerVal, headerKey) {
  9625. fillInParsed(lowercase(headerKey), trim(headerVal));
  9626. });
  9627. }
  9628. return parsed;
  9629. }
  9630. /**
  9631. * Returns a function that provides access to parsed headers.
  9632. *
  9633. * Headers are lazy parsed when first requested.
  9634. * @see parseHeaders
  9635. *
  9636. * @param {(string|Object)} headers Headers to provide access to.
  9637. * @returns {function(string=)} Returns a getter function which if called with:
  9638. *
  9639. * - if called with single an argument returns a single header value or null
  9640. * - if called with no arguments returns an object containing all headers.
  9641. */
  9642. function headersGetter(headers) {
  9643. var headersObj;
  9644. return function(name) {
  9645. if (!headersObj) headersObj = parseHeaders(headers);
  9646. if (name) {
  9647. var value = headersObj[lowercase(name)];
  9648. if (value === void 0) {
  9649. value = null;
  9650. }
  9651. return value;
  9652. }
  9653. return headersObj;
  9654. };
  9655. }
  9656. /**
  9657. * Chain all given functions
  9658. *
  9659. * This function is used for both request and response transforming
  9660. *
  9661. * @param {*} data Data to transform.
  9662. * @param {function(string=)} headers HTTP headers getter fn.
  9663. * @param {number} status HTTP status code of the response.
  9664. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  9665. * @returns {*} Transformed data.
  9666. */
  9667. function transformData(data, headers, status, fns) {
  9668. if (isFunction(fns)) {
  9669. return fns(data, headers, status);
  9670. }
  9671. forEach(fns, function(fn) {
  9672. data = fn(data, headers, status);
  9673. });
  9674. return data;
  9675. }
  9676. function isSuccess(status) {
  9677. return 200 <= status && status < 300;
  9678. }
  9679. /**
  9680. * @ngdoc provider
  9681. * @name $httpProvider
  9682. * @description
  9683. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  9684. * */
  9685. function $HttpProvider() {
  9686. /**
  9687. * @ngdoc property
  9688. * @name $httpProvider#defaults
  9689. * @description
  9690. *
  9691. * Object containing default values for all {@link ng.$http $http} requests.
  9692. *
  9693. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  9694. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  9695. * by default. See {@link $http#caching $http Caching} for more information.
  9696. *
  9697. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  9698. * Defaults value is `'XSRF-TOKEN'`.
  9699. *
  9700. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  9701. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  9702. *
  9703. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  9704. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  9705. * setting default headers.
  9706. * - **`defaults.headers.common`**
  9707. * - **`defaults.headers.post`**
  9708. * - **`defaults.headers.put`**
  9709. * - **`defaults.headers.patch`**
  9710. *
  9711. *
  9712. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  9713. * used to the prepare string representation of request parameters (specified as an object).
  9714. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  9715. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  9716. *
  9717. **/
  9718. var defaults = this.defaults = {
  9719. // transform incoming response data
  9720. transformResponse: [defaultHttpResponseTransform],
  9721. // transform outgoing request data
  9722. transformRequest: [function(d) {
  9723. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  9724. }],
  9725. // default headers
  9726. headers: {
  9727. common: {
  9728. 'Accept': 'application/json, text/plain, */*'
  9729. },
  9730. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9731. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9732. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  9733. },
  9734. xsrfCookieName: 'XSRF-TOKEN',
  9735. xsrfHeaderName: 'X-XSRF-TOKEN',
  9736. paramSerializer: '$httpParamSerializer'
  9737. };
  9738. var useApplyAsync = false;
  9739. /**
  9740. * @ngdoc method
  9741. * @name $httpProvider#useApplyAsync
  9742. * @description
  9743. *
  9744. * Configure $http service to combine processing of multiple http responses received at around
  9745. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  9746. * significant performance improvement for bigger applications that make many HTTP requests
  9747. * concurrently (common during application bootstrap).
  9748. *
  9749. * Defaults to false. If no value is specified, returns the current configured value.
  9750. *
  9751. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  9752. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  9753. * to load and share the same digest cycle.
  9754. *
  9755. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9756. * otherwise, returns the current configured value.
  9757. **/
  9758. this.useApplyAsync = function(value) {
  9759. if (isDefined(value)) {
  9760. useApplyAsync = !!value;
  9761. return this;
  9762. }
  9763. return useApplyAsync;
  9764. };
  9765. var useLegacyPromise = true;
  9766. /**
  9767. * @ngdoc method
  9768. * @name $httpProvider#useLegacyPromiseExtensions
  9769. * @description
  9770. *
  9771. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  9772. * This should be used to make sure that applications work without these methods.
  9773. *
  9774. * Defaults to true. If no value is specified, returns the current configured value.
  9775. *
  9776. * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
  9777. *
  9778. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9779. * otherwise, returns the current configured value.
  9780. **/
  9781. this.useLegacyPromiseExtensions = function(value) {
  9782. if (isDefined(value)) {
  9783. useLegacyPromise = !!value;
  9784. return this;
  9785. }
  9786. return useLegacyPromise;
  9787. };
  9788. /**
  9789. * @ngdoc property
  9790. * @name $httpProvider#interceptors
  9791. * @description
  9792. *
  9793. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  9794. * pre-processing of request or postprocessing of responses.
  9795. *
  9796. * These service factories are ordered by request, i.e. they are applied in the same order as the
  9797. * array, on request, but reverse order, on response.
  9798. *
  9799. * {@link ng.$http#interceptors Interceptors detailed info}
  9800. **/
  9801. var interceptorFactories = this.interceptors = [];
  9802. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  9803. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  9804. var defaultCache = $cacheFactory('$http');
  9805. /**
  9806. * Make sure that default param serializer is exposed as a function
  9807. */
  9808. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  9809. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  9810. /**
  9811. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  9812. * The reversal is needed so that we can build up the interception chain around the
  9813. * server request.
  9814. */
  9815. var reversedInterceptors = [];
  9816. forEach(interceptorFactories, function(interceptorFactory) {
  9817. reversedInterceptors.unshift(isString(interceptorFactory)
  9818. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  9819. });
  9820. /**
  9821. * @ngdoc service
  9822. * @kind function
  9823. * @name $http
  9824. * @requires ng.$httpBackend
  9825. * @requires $cacheFactory
  9826. * @requires $rootScope
  9827. * @requires $q
  9828. * @requires $injector
  9829. *
  9830. * @description
  9831. * The `$http` service is a core Angular service that facilitates communication with the remote
  9832. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  9833. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  9834. *
  9835. * For unit testing applications that use `$http` service, see
  9836. * {@link ngMock.$httpBackend $httpBackend mock}.
  9837. *
  9838. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  9839. * $resource} service.
  9840. *
  9841. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  9842. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  9843. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  9844. *
  9845. *
  9846. * ## General usage
  9847. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  9848. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  9849. *
  9850. * ```js
  9851. * // Simple GET request example:
  9852. * $http({
  9853. * method: 'GET',
  9854. * url: '/someUrl'
  9855. * }).then(function successCallback(response) {
  9856. * // this callback will be called asynchronously
  9857. * // when the response is available
  9858. * }, function errorCallback(response) {
  9859. * // called asynchronously if an error occurs
  9860. * // or server returns response with an error status.
  9861. * });
  9862. * ```
  9863. *
  9864. * The response object has these properties:
  9865. *
  9866. * - **data** – `{string|Object}` – The response body transformed with the transform
  9867. * functions.
  9868. * - **status** – `{number}` – HTTP status code of the response.
  9869. * - **headers** – `{function([headerName])}` – Header getter function.
  9870. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  9871. * - **statusText** – `{string}` – HTTP status text of the response.
  9872. *
  9873. * A response status code between 200 and 299 is considered a success status and will result in
  9874. * the success callback being called. Any response status code outside of that range is
  9875. * considered an error status and will result in the error callback being called.
  9876. * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
  9877. * aborted, e.g. using a `config.timeout`.
  9878. * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
  9879. * that the outcome (success or error) will be determined by the final response status code.
  9880. *
  9881. *
  9882. * ## Shortcut methods
  9883. *
  9884. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  9885. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  9886. * last argument.
  9887. *
  9888. * ```js
  9889. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  9890. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  9891. * ```
  9892. *
  9893. * Complete list of shortcut methods:
  9894. *
  9895. * - {@link ng.$http#get $http.get}
  9896. * - {@link ng.$http#head $http.head}
  9897. * - {@link ng.$http#post $http.post}
  9898. * - {@link ng.$http#put $http.put}
  9899. * - {@link ng.$http#delete $http.delete}
  9900. * - {@link ng.$http#jsonp $http.jsonp}
  9901. * - {@link ng.$http#patch $http.patch}
  9902. *
  9903. *
  9904. * ## Writing Unit Tests that use $http
  9905. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  9906. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  9907. * request using trained responses.
  9908. *
  9909. * ```
  9910. * $httpBackend.expectGET(...);
  9911. * $http.get(...);
  9912. * $httpBackend.flush();
  9913. * ```
  9914. *
  9915. * ## Deprecation Notice
  9916. * <div class="alert alert-danger">
  9917. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  9918. * Use the standard `then` method instead.
  9919. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  9920. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  9921. * </div>
  9922. *
  9923. * ## Setting HTTP Headers
  9924. *
  9925. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  9926. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  9927. * object, which currently contains this default configuration:
  9928. *
  9929. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  9930. * - `Accept: application/json, text/plain, * / *`
  9931. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  9932. * - `Content-Type: application/json`
  9933. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  9934. * - `Content-Type: application/json`
  9935. *
  9936. * To add or overwrite these defaults, simply add or remove a property from these configuration
  9937. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  9938. * with the lowercased HTTP method name as the key, e.g.
  9939. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  9940. *
  9941. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  9942. * fashion. For example:
  9943. *
  9944. * ```
  9945. * module.run(function($http) {
  9946. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  9947. * });
  9948. * ```
  9949. *
  9950. * In addition, you can supply a `headers` property in the config object passed when
  9951. * calling `$http(config)`, which overrides the defaults without changing them globally.
  9952. *
  9953. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  9954. * Use the `headers` property, setting the desired header to `undefined`. For example:
  9955. *
  9956. * ```js
  9957. * var req = {
  9958. * method: 'POST',
  9959. * url: 'http://example.com',
  9960. * headers: {
  9961. * 'Content-Type': undefined
  9962. * },
  9963. * data: { test: 'test' }
  9964. * }
  9965. *
  9966. * $http(req).then(function(){...}, function(){...});
  9967. * ```
  9968. *
  9969. * ## Transforming Requests and Responses
  9970. *
  9971. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  9972. * and `transformResponse`. These properties can be a single function that returns
  9973. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  9974. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  9975. *
  9976. * <div class="alert alert-warning">
  9977. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  9978. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  9979. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  9980. * function will be reflected on the scope and in any templates where the object is data-bound.
  9981. * To prevent this, transform functions should have no side-effects.
  9982. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  9983. * </div>
  9984. *
  9985. * ### Default Transformations
  9986. *
  9987. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  9988. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  9989. * then these will be applied.
  9990. *
  9991. * You can augment or replace the default transformations by modifying these properties by adding to or
  9992. * replacing the array.
  9993. *
  9994. * Angular provides the following default transformations:
  9995. *
  9996. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  9997. *
  9998. * - If the `data` property of the request configuration object contains an object, serialize it
  9999. * into JSON format.
  10000. *
  10001. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  10002. *
  10003. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  10004. * - If JSON response is detected, deserialize it using a JSON parser.
  10005. *
  10006. *
  10007. * ### Overriding the Default Transformations Per Request
  10008. *
  10009. * If you wish to override the request/response transformations only for a single request then provide
  10010. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  10011. * into `$http`.
  10012. *
  10013. * Note that if you provide these properties on the config object the default transformations will be
  10014. * overwritten. If you wish to augment the default transformations then you must include them in your
  10015. * local transformation array.
  10016. *
  10017. * The following code demonstrates adding a new response transformation to be run after the default response
  10018. * transformations have been run.
  10019. *
  10020. * ```js
  10021. * function appendTransform(defaults, transform) {
  10022. *
  10023. * // We can't guarantee that the default transformation is an array
  10024. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  10025. *
  10026. * // Append the new transformation to the defaults
  10027. * return defaults.concat(transform);
  10028. * }
  10029. *
  10030. * $http({
  10031. * url: '...',
  10032. * method: 'GET',
  10033. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  10034. * return doTransform(value);
  10035. * })
  10036. * });
  10037. * ```
  10038. *
  10039. *
  10040. * ## Caching
  10041. *
  10042. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  10043. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  10044. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  10045. * precedence over the default cache value.
  10046. *
  10047. * In order to:
  10048. * * cache all responses - set the default cache value to TRUE or to a cache object
  10049. * * cache a specific response - set config.cache value to TRUE or to a cache object
  10050. *
  10051. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  10052. * then the default `$cacheFactory("$http")` object is used.
  10053. *
  10054. * The default cache value can be set by updating the
  10055. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  10056. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  10057. *
  10058. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  10059. * the relevant cache object. The next time the same request is made, the response is returned
  10060. * from the cache without sending a request to the server.
  10061. *
  10062. * Take note that:
  10063. *
  10064. * * Only GET and JSONP requests are cached.
  10065. * * The cache key is the request URL including search parameters; headers are not considered.
  10066. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  10067. * * If multiple identical requests are made using the same cache, which is not yet populated,
  10068. * one request will be made to the server and remaining requests will return the same response.
  10069. * * A cache-control header on the response does not affect if or how responses are cached.
  10070. *
  10071. *
  10072. * ## Interceptors
  10073. *
  10074. * Before you start creating interceptors, be sure to understand the
  10075. * {@link ng.$q $q and deferred/promise APIs}.
  10076. *
  10077. * For purposes of global error handling, authentication, or any kind of synchronous or
  10078. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  10079. * able to intercept requests before they are handed to the server and
  10080. * responses before they are handed over to the application code that
  10081. * initiated these requests. The interceptors leverage the {@link ng.$q
  10082. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  10083. *
  10084. * The interceptors are service factories that are registered with the `$httpProvider` by
  10085. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  10086. * injected with dependencies (if specified) and returns the interceptor.
  10087. *
  10088. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  10089. *
  10090. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  10091. * modify the `config` object or create a new one. The function needs to return the `config`
  10092. * object directly, or a promise containing the `config` or a new `config` object.
  10093. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  10094. * resolved with a rejection.
  10095. * * `response`: interceptors get called with http `response` object. The function is free to
  10096. * modify the `response` object or create a new one. The function needs to return the `response`
  10097. * object directly, or as a promise containing the `response` or a new `response` object.
  10098. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  10099. * resolved with a rejection.
  10100. *
  10101. *
  10102. * ```js
  10103. * // register the interceptor as a service
  10104. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  10105. * return {
  10106. * // optional method
  10107. * 'request': function(config) {
  10108. * // do something on success
  10109. * return config;
  10110. * },
  10111. *
  10112. * // optional method
  10113. * 'requestError': function(rejection) {
  10114. * // do something on error
  10115. * if (canRecover(rejection)) {
  10116. * return responseOrNewPromise
  10117. * }
  10118. * return $q.reject(rejection);
  10119. * },
  10120. *
  10121. *
  10122. *
  10123. * // optional method
  10124. * 'response': function(response) {
  10125. * // do something on success
  10126. * return response;
  10127. * },
  10128. *
  10129. * // optional method
  10130. * 'responseError': function(rejection) {
  10131. * // do something on error
  10132. * if (canRecover(rejection)) {
  10133. * return responseOrNewPromise
  10134. * }
  10135. * return $q.reject(rejection);
  10136. * }
  10137. * };
  10138. * });
  10139. *
  10140. * $httpProvider.interceptors.push('myHttpInterceptor');
  10141. *
  10142. *
  10143. * // alternatively, register the interceptor via an anonymous factory
  10144. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  10145. * return {
  10146. * 'request': function(config) {
  10147. * // same as above
  10148. * },
  10149. *
  10150. * 'response': function(response) {
  10151. * // same as above
  10152. * }
  10153. * };
  10154. * });
  10155. * ```
  10156. *
  10157. * ## Security Considerations
  10158. *
  10159. * When designing web applications, consider security threats from:
  10160. *
  10161. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10162. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  10163. *
  10164. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  10165. * pre-configured with strategies that address these issues, but for this to work backend server
  10166. * cooperation is required.
  10167. *
  10168. * ### JSON Vulnerability Protection
  10169. *
  10170. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10171. * allows third party website to turn your JSON resource URL into
  10172. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  10173. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  10174. * Angular will automatically strip the prefix before processing it as JSON.
  10175. *
  10176. * For example if your server needs to return:
  10177. * ```js
  10178. * ['one','two']
  10179. * ```
  10180. *
  10181. * which is vulnerable to attack, your server can return:
  10182. * ```js
  10183. * )]}',
  10184. * ['one','two']
  10185. * ```
  10186. *
  10187. * Angular will strip the prefix, before processing the JSON.
  10188. *
  10189. *
  10190. * ### Cross Site Request Forgery (XSRF) Protection
  10191. *
  10192. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  10193. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  10194. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  10195. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  10196. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  10197. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  10198. * The header will not be set for cross-domain requests.
  10199. *
  10200. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  10201. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  10202. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  10203. * that only JavaScript running on your domain could have sent the request. The token must be
  10204. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  10205. * making up its own tokens). We recommend that the token is a digest of your site's
  10206. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  10207. * for added security.
  10208. *
  10209. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  10210. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  10211. * or the per-request config object.
  10212. *
  10213. * In order to prevent collisions in environments where multiple Angular apps share the
  10214. * same domain or subdomain, we recommend that each application uses unique cookie name.
  10215. *
  10216. * @param {object} config Object describing the request to be made and how it should be
  10217. * processed. The object has following properties:
  10218. *
  10219. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  10220. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  10221. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  10222. * with the `paramSerializer` and appended as GET parameters.
  10223. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  10224. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  10225. * HTTP headers to send to the server. If the return value of a function is null, the
  10226. * header will not be sent. Functions accept a config object as an argument.
  10227. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  10228. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  10229. * The handler will be called in the context of a `$apply` block.
  10230. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  10231. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  10232. * The handler will be called in the context of a `$apply` block.
  10233. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  10234. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  10235. * - **transformRequest** –
  10236. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  10237. * transform function or an array of such functions. The transform function takes the http
  10238. * request body and headers and returns its transformed (typically serialized) version.
  10239. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10240. * Overriding the Default Transformations}
  10241. * - **transformResponse** –
  10242. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  10243. * transform function or an array of such functions. The transform function takes the http
  10244. * response body, headers and status and returns its transformed (typically deserialized) version.
  10245. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10246. * Overriding the Default Transformations}
  10247. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  10248. * prepare the string representation of request parameters (specified as an object).
  10249. * If specified as string, it is interpreted as function registered with the
  10250. * {@link $injector $injector}, which means you can create your own serializer
  10251. * by registering it as a {@link auto.$provide#service service}.
  10252. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  10253. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  10254. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  10255. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  10256. * See {@link $http#caching $http Caching} for more information.
  10257. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  10258. * that should abort the request when resolved.
  10259. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  10260. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  10261. * for more information.
  10262. * - **responseType** - `{string}` - see
  10263. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  10264. *
  10265. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  10266. * when the request succeeds or fails.
  10267. *
  10268. *
  10269. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  10270. * requests. This is primarily meant to be used for debugging purposes.
  10271. *
  10272. *
  10273. * @example
  10274. <example module="httpExample">
  10275. <file name="index.html">
  10276. <div ng-controller="FetchController">
  10277. <select ng-model="method" aria-label="Request method">
  10278. <option>GET</option>
  10279. <option>JSONP</option>
  10280. </select>
  10281. <input type="text" ng-model="url" size="80" aria-label="URL" />
  10282. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  10283. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  10284. <button id="samplejsonpbtn"
  10285. ng-click="updateModel('JSONP',
  10286. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  10287. Sample JSONP
  10288. </button>
  10289. <button id="invalidjsonpbtn"
  10290. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  10291. Invalid JSONP
  10292. </button>
  10293. <pre>http status code: {{status}}</pre>
  10294. <pre>http response data: {{data}}</pre>
  10295. </div>
  10296. </file>
  10297. <file name="script.js">
  10298. angular.module('httpExample', [])
  10299. .controller('FetchController', ['$scope', '$http', '$templateCache',
  10300. function($scope, $http, $templateCache) {
  10301. $scope.method = 'GET';
  10302. $scope.url = 'http-hello.html';
  10303. $scope.fetch = function() {
  10304. $scope.code = null;
  10305. $scope.response = null;
  10306. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  10307. then(function(response) {
  10308. $scope.status = response.status;
  10309. $scope.data = response.data;
  10310. }, function(response) {
  10311. $scope.data = response.data || "Request failed";
  10312. $scope.status = response.status;
  10313. });
  10314. };
  10315. $scope.updateModel = function(method, url) {
  10316. $scope.method = method;
  10317. $scope.url = url;
  10318. };
  10319. }]);
  10320. </file>
  10321. <file name="http-hello.html">
  10322. Hello, $http!
  10323. </file>
  10324. <file name="protractor.js" type="protractor">
  10325. var status = element(by.binding('status'));
  10326. var data = element(by.binding('data'));
  10327. var fetchBtn = element(by.id('fetchbtn'));
  10328. var sampleGetBtn = element(by.id('samplegetbtn'));
  10329. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  10330. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  10331. it('should make an xhr GET request', function() {
  10332. sampleGetBtn.click();
  10333. fetchBtn.click();
  10334. expect(status.getText()).toMatch('200');
  10335. expect(data.getText()).toMatch(/Hello, \$http!/);
  10336. });
  10337. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  10338. // it('should make a JSONP request to angularjs.org', function() {
  10339. // sampleJsonpBtn.click();
  10340. // fetchBtn.click();
  10341. // expect(status.getText()).toMatch('200');
  10342. // expect(data.getText()).toMatch(/Super Hero!/);
  10343. // });
  10344. it('should make JSONP request to invalid URL and invoke the error handler',
  10345. function() {
  10346. invalidJsonpBtn.click();
  10347. fetchBtn.click();
  10348. expect(status.getText()).toMatch('0');
  10349. expect(data.getText()).toMatch('Request failed');
  10350. });
  10351. </file>
  10352. </example>
  10353. */
  10354. function $http(requestConfig) {
  10355. if (!isObject(requestConfig)) {
  10356. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  10357. }
  10358. if (!isString(requestConfig.url)) {
  10359. throw minErr('$http')('badreq', 'Http request configuration url must be a string. Received: {0}', requestConfig.url);
  10360. }
  10361. var config = extend({
  10362. method: 'get',
  10363. transformRequest: defaults.transformRequest,
  10364. transformResponse: defaults.transformResponse,
  10365. paramSerializer: defaults.paramSerializer
  10366. }, requestConfig);
  10367. config.headers = mergeHeaders(requestConfig);
  10368. config.method = uppercase(config.method);
  10369. config.paramSerializer = isString(config.paramSerializer) ?
  10370. $injector.get(config.paramSerializer) : config.paramSerializer;
  10371. var requestInterceptors = [];
  10372. var responseInterceptors = [];
  10373. var promise = $q.when(config);
  10374. // apply interceptors
  10375. forEach(reversedInterceptors, function(interceptor) {
  10376. if (interceptor.request || interceptor.requestError) {
  10377. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  10378. }
  10379. if (interceptor.response || interceptor.responseError) {
  10380. responseInterceptors.push(interceptor.response, interceptor.responseError);
  10381. }
  10382. });
  10383. promise = chainInterceptors(promise, requestInterceptors);
  10384. promise = promise.then(serverRequest);
  10385. promise = chainInterceptors(promise, responseInterceptors);
  10386. if (useLegacyPromise) {
  10387. promise.success = function(fn) {
  10388. assertArgFn(fn, 'fn');
  10389. promise.then(function(response) {
  10390. fn(response.data, response.status, response.headers, config);
  10391. });
  10392. return promise;
  10393. };
  10394. promise.error = function(fn) {
  10395. assertArgFn(fn, 'fn');
  10396. promise.then(null, function(response) {
  10397. fn(response.data, response.status, response.headers, config);
  10398. });
  10399. return promise;
  10400. };
  10401. } else {
  10402. promise.success = $httpMinErrLegacyFn('success');
  10403. promise.error = $httpMinErrLegacyFn('error');
  10404. }
  10405. return promise;
  10406. function chainInterceptors(promise, interceptors) {
  10407. for (var i = 0, ii = interceptors.length; i < ii;) {
  10408. var thenFn = interceptors[i++];
  10409. var rejectFn = interceptors[i++];
  10410. promise = promise.then(thenFn, rejectFn);
  10411. }
  10412. interceptors.length = 0;
  10413. return promise;
  10414. }
  10415. function executeHeaderFns(headers, config) {
  10416. var headerContent, processedHeaders = {};
  10417. forEach(headers, function(headerFn, header) {
  10418. if (isFunction(headerFn)) {
  10419. headerContent = headerFn(config);
  10420. if (headerContent != null) {
  10421. processedHeaders[header] = headerContent;
  10422. }
  10423. } else {
  10424. processedHeaders[header] = headerFn;
  10425. }
  10426. });
  10427. return processedHeaders;
  10428. }
  10429. function mergeHeaders(config) {
  10430. var defHeaders = defaults.headers,
  10431. reqHeaders = extend({}, config.headers),
  10432. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  10433. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  10434. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  10435. defaultHeadersIteration:
  10436. for (defHeaderName in defHeaders) {
  10437. lowercaseDefHeaderName = lowercase(defHeaderName);
  10438. for (reqHeaderName in reqHeaders) {
  10439. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  10440. continue defaultHeadersIteration;
  10441. }
  10442. }
  10443. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  10444. }
  10445. // execute if header value is a function for merged headers
  10446. return executeHeaderFns(reqHeaders, shallowCopy(config));
  10447. }
  10448. function serverRequest(config) {
  10449. var headers = config.headers;
  10450. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  10451. // strip content-type if data is undefined
  10452. if (isUndefined(reqData)) {
  10453. forEach(headers, function(value, header) {
  10454. if (lowercase(header) === 'content-type') {
  10455. delete headers[header];
  10456. }
  10457. });
  10458. }
  10459. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  10460. config.withCredentials = defaults.withCredentials;
  10461. }
  10462. // send request
  10463. return sendReq(config, reqData).then(transformResponse, transformResponse);
  10464. }
  10465. function transformResponse(response) {
  10466. // make a copy since the response must be cacheable
  10467. var resp = extend({}, response);
  10468. resp.data = transformData(response.data, response.headers, response.status,
  10469. config.transformResponse);
  10470. return (isSuccess(response.status))
  10471. ? resp
  10472. : $q.reject(resp);
  10473. }
  10474. }
  10475. $http.pendingRequests = [];
  10476. /**
  10477. * @ngdoc method
  10478. * @name $http#get
  10479. *
  10480. * @description
  10481. * Shortcut method to perform `GET` request.
  10482. *
  10483. * @param {string} url Relative or absolute URL specifying the destination of the request
  10484. * @param {Object=} config Optional configuration object
  10485. * @returns {HttpPromise} Future object
  10486. */
  10487. /**
  10488. * @ngdoc method
  10489. * @name $http#delete
  10490. *
  10491. * @description
  10492. * Shortcut method to perform `DELETE` request.
  10493. *
  10494. * @param {string} url Relative or absolute URL specifying the destination of the request
  10495. * @param {Object=} config Optional configuration object
  10496. * @returns {HttpPromise} Future object
  10497. */
  10498. /**
  10499. * @ngdoc method
  10500. * @name $http#head
  10501. *
  10502. * @description
  10503. * Shortcut method to perform `HEAD` request.
  10504. *
  10505. * @param {string} url Relative or absolute URL specifying the destination of the request
  10506. * @param {Object=} config Optional configuration object
  10507. * @returns {HttpPromise} Future object
  10508. */
  10509. /**
  10510. * @ngdoc method
  10511. * @name $http#jsonp
  10512. *
  10513. * @description
  10514. * Shortcut method to perform `JSONP` request.
  10515. * If you would like to customise where and how the callbacks are stored then try overriding
  10516. * or decorating the {@link $jsonpCallbacks} service.
  10517. *
  10518. * @param {string} url Relative or absolute URL specifying the destination of the request.
  10519. * The name of the callback should be the string `JSON_CALLBACK`.
  10520. * @param {Object=} config Optional configuration object
  10521. * @returns {HttpPromise} Future object
  10522. */
  10523. createShortMethods('get', 'delete', 'head', 'jsonp');
  10524. /**
  10525. * @ngdoc method
  10526. * @name $http#post
  10527. *
  10528. * @description
  10529. * Shortcut method to perform `POST` request.
  10530. *
  10531. * @param {string} url Relative or absolute URL specifying the destination of the request
  10532. * @param {*} data Request content
  10533. * @param {Object=} config Optional configuration object
  10534. * @returns {HttpPromise} Future object
  10535. */
  10536. /**
  10537. * @ngdoc method
  10538. * @name $http#put
  10539. *
  10540. * @description
  10541. * Shortcut method to perform `PUT` request.
  10542. *
  10543. * @param {string} url Relative or absolute URL specifying the destination of the request
  10544. * @param {*} data Request content
  10545. * @param {Object=} config Optional configuration object
  10546. * @returns {HttpPromise} Future object
  10547. */
  10548. /**
  10549. * @ngdoc method
  10550. * @name $http#patch
  10551. *
  10552. * @description
  10553. * Shortcut method to perform `PATCH` request.
  10554. *
  10555. * @param {string} url Relative or absolute URL specifying the destination of the request
  10556. * @param {*} data Request content
  10557. * @param {Object=} config Optional configuration object
  10558. * @returns {HttpPromise} Future object
  10559. */
  10560. createShortMethodsWithData('post', 'put', 'patch');
  10561. /**
  10562. * @ngdoc property
  10563. * @name $http#defaults
  10564. *
  10565. * @description
  10566. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  10567. * default headers, withCredentials as well as request and response transformations.
  10568. *
  10569. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  10570. */
  10571. $http.defaults = defaults;
  10572. return $http;
  10573. function createShortMethods(names) {
  10574. forEach(arguments, function(name) {
  10575. $http[name] = function(url, config) {
  10576. return $http(extend({}, config || {}, {
  10577. method: name,
  10578. url: url
  10579. }));
  10580. };
  10581. });
  10582. }
  10583. function createShortMethodsWithData(name) {
  10584. forEach(arguments, function(name) {
  10585. $http[name] = function(url, data, config) {
  10586. return $http(extend({}, config || {}, {
  10587. method: name,
  10588. url: url,
  10589. data: data
  10590. }));
  10591. };
  10592. });
  10593. }
  10594. /**
  10595. * Makes the request.
  10596. *
  10597. * !!! ACCESSES CLOSURE VARS:
  10598. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  10599. */
  10600. function sendReq(config, reqData) {
  10601. var deferred = $q.defer(),
  10602. promise = deferred.promise,
  10603. cache,
  10604. cachedResp,
  10605. reqHeaders = config.headers,
  10606. url = buildUrl(config.url, config.paramSerializer(config.params));
  10607. $http.pendingRequests.push(config);
  10608. promise.then(removePendingReq, removePendingReq);
  10609. if ((config.cache || defaults.cache) && config.cache !== false &&
  10610. (config.method === 'GET' || config.method === 'JSONP')) {
  10611. cache = isObject(config.cache) ? config.cache
  10612. : isObject(defaults.cache) ? defaults.cache
  10613. : defaultCache;
  10614. }
  10615. if (cache) {
  10616. cachedResp = cache.get(url);
  10617. if (isDefined(cachedResp)) {
  10618. if (isPromiseLike(cachedResp)) {
  10619. // cached request has already been sent, but there is no response yet
  10620. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  10621. } else {
  10622. // serving from cache
  10623. if (isArray(cachedResp)) {
  10624. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  10625. } else {
  10626. resolvePromise(cachedResp, 200, {}, 'OK');
  10627. }
  10628. }
  10629. } else {
  10630. // put the promise for the non-transformed response into cache as a placeholder
  10631. cache.put(url, promise);
  10632. }
  10633. }
  10634. // if we won't have the response in cache, set the xsrf headers and
  10635. // send the request to the backend
  10636. if (isUndefined(cachedResp)) {
  10637. var xsrfValue = urlIsSameOrigin(config.url)
  10638. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  10639. : undefined;
  10640. if (xsrfValue) {
  10641. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  10642. }
  10643. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  10644. config.withCredentials, config.responseType,
  10645. createApplyHandlers(config.eventHandlers),
  10646. createApplyHandlers(config.uploadEventHandlers));
  10647. }
  10648. return promise;
  10649. function createApplyHandlers(eventHandlers) {
  10650. if (eventHandlers) {
  10651. var applyHandlers = {};
  10652. forEach(eventHandlers, function(eventHandler, key) {
  10653. applyHandlers[key] = function(event) {
  10654. if (useApplyAsync) {
  10655. $rootScope.$applyAsync(callEventHandler);
  10656. } else if ($rootScope.$$phase) {
  10657. callEventHandler();
  10658. } else {
  10659. $rootScope.$apply(callEventHandler);
  10660. }
  10661. function callEventHandler() {
  10662. eventHandler(event);
  10663. }
  10664. };
  10665. });
  10666. return applyHandlers;
  10667. }
  10668. }
  10669. /**
  10670. * Callback registered to $httpBackend():
  10671. * - caches the response if desired
  10672. * - resolves the raw $http promise
  10673. * - calls $apply
  10674. */
  10675. function done(status, response, headersString, statusText) {
  10676. if (cache) {
  10677. if (isSuccess(status)) {
  10678. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  10679. } else {
  10680. // remove promise from the cache
  10681. cache.remove(url);
  10682. }
  10683. }
  10684. function resolveHttpPromise() {
  10685. resolvePromise(response, status, headersString, statusText);
  10686. }
  10687. if (useApplyAsync) {
  10688. $rootScope.$applyAsync(resolveHttpPromise);
  10689. } else {
  10690. resolveHttpPromise();
  10691. if (!$rootScope.$$phase) $rootScope.$apply();
  10692. }
  10693. }
  10694. /**
  10695. * Resolves the raw $http promise.
  10696. */
  10697. function resolvePromise(response, status, headers, statusText) {
  10698. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  10699. status = status >= -1 ? status : 0;
  10700. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  10701. data: response,
  10702. status: status,
  10703. headers: headersGetter(headers),
  10704. config: config,
  10705. statusText: statusText
  10706. });
  10707. }
  10708. function resolvePromiseWithResult(result) {
  10709. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  10710. }
  10711. function removePendingReq() {
  10712. var idx = $http.pendingRequests.indexOf(config);
  10713. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  10714. }
  10715. }
  10716. function buildUrl(url, serializedParams) {
  10717. if (serializedParams.length > 0) {
  10718. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  10719. }
  10720. return url;
  10721. }
  10722. }];
  10723. }
  10724. /**
  10725. * @ngdoc service
  10726. * @name $xhrFactory
  10727. *
  10728. * @description
  10729. * Factory function used to create XMLHttpRequest objects.
  10730. *
  10731. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  10732. *
  10733. * ```
  10734. * angular.module('myApp', [])
  10735. * .factory('$xhrFactory', function() {
  10736. * return function createXhr(method, url) {
  10737. * return new window.XMLHttpRequest({mozSystem: true});
  10738. * };
  10739. * });
  10740. * ```
  10741. *
  10742. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  10743. * @param {string} url URL of the request.
  10744. */
  10745. function $xhrFactoryProvider() {
  10746. this.$get = function() {
  10747. return function createXhr() {
  10748. return new window.XMLHttpRequest();
  10749. };
  10750. };
  10751. }
  10752. /**
  10753. * @ngdoc service
  10754. * @name $httpBackend
  10755. * @requires $jsonpCallbacks
  10756. * @requires $document
  10757. * @requires $xhrFactory
  10758. *
  10759. * @description
  10760. * HTTP backend used by the {@link ng.$http service} that delegates to
  10761. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  10762. *
  10763. * You should never need to use this service directly, instead use the higher-level abstractions:
  10764. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  10765. *
  10766. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  10767. * $httpBackend} which can be trained with responses.
  10768. */
  10769. function $HttpBackendProvider() {
  10770. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  10771. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  10772. }];
  10773. }
  10774. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  10775. // TODO(vojta): fix the signature
  10776. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  10777. $browser.$$incOutstandingRequestCount();
  10778. url = url || $browser.url();
  10779. if (lowercase(method) === 'jsonp') {
  10780. var callbackPath = callbacks.createCallback(url);
  10781. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  10782. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  10783. var response = (status === 200) && callbacks.getResponse(callbackPath);
  10784. completeRequest(callback, status, response, "", text);
  10785. callbacks.removeCallback(callbackPath);
  10786. });
  10787. } else {
  10788. var xhr = createXhr(method, url);
  10789. xhr.open(method, url, true);
  10790. forEach(headers, function(value, key) {
  10791. if (isDefined(value)) {
  10792. xhr.setRequestHeader(key, value);
  10793. }
  10794. });
  10795. xhr.onload = function requestLoaded() {
  10796. var statusText = xhr.statusText || '';
  10797. // responseText is the old-school way of retrieving response (supported by IE9)
  10798. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  10799. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  10800. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  10801. var status = xhr.status === 1223 ? 204 : xhr.status;
  10802. // fix status code when it is 0 (0 status is undocumented).
  10803. // Occurs when accessing file resources or on Android 4.1 stock browser
  10804. // while retrieving files from application cache.
  10805. if (status === 0) {
  10806. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  10807. }
  10808. completeRequest(callback,
  10809. status,
  10810. response,
  10811. xhr.getAllResponseHeaders(),
  10812. statusText);
  10813. };
  10814. var requestError = function() {
  10815. // The response is always empty
  10816. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  10817. completeRequest(callback, -1, null, null, '');
  10818. };
  10819. xhr.onerror = requestError;
  10820. xhr.onabort = requestError;
  10821. forEach(eventHandlers, function(value, key) {
  10822. xhr.addEventListener(key, value);
  10823. });
  10824. forEach(uploadEventHandlers, function(value, key) {
  10825. xhr.upload.addEventListener(key, value);
  10826. });
  10827. if (withCredentials) {
  10828. xhr.withCredentials = true;
  10829. }
  10830. if (responseType) {
  10831. try {
  10832. xhr.responseType = responseType;
  10833. } catch (e) {
  10834. // WebKit added support for the json responseType value on 09/03/2013
  10835. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  10836. // known to throw when setting the value "json" as the response type. Other older
  10837. // browsers implementing the responseType
  10838. //
  10839. // The json response type can be ignored if not supported, because JSON payloads are
  10840. // parsed on the client-side regardless.
  10841. if (responseType !== 'json') {
  10842. throw e;
  10843. }
  10844. }
  10845. }
  10846. xhr.send(isUndefined(post) ? null : post);
  10847. }
  10848. if (timeout > 0) {
  10849. var timeoutId = $browserDefer(timeoutRequest, timeout);
  10850. } else if (isPromiseLike(timeout)) {
  10851. timeout.then(timeoutRequest);
  10852. }
  10853. function timeoutRequest() {
  10854. jsonpDone && jsonpDone();
  10855. xhr && xhr.abort();
  10856. }
  10857. function completeRequest(callback, status, response, headersString, statusText) {
  10858. // cancel timeout and subsequent timeout promise resolution
  10859. if (isDefined(timeoutId)) {
  10860. $browserDefer.cancel(timeoutId);
  10861. }
  10862. jsonpDone = xhr = null;
  10863. callback(status, response, headersString, statusText);
  10864. $browser.$$completeOutstandingRequest(noop);
  10865. }
  10866. };
  10867. function jsonpReq(url, callbackPath, done) {
  10868. url = url.replace('JSON_CALLBACK', callbackPath);
  10869. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  10870. // - fetches local scripts via XHR and evals them
  10871. // - adds and immediately removes script elements from the document
  10872. var script = rawDocument.createElement('script'), callback = null;
  10873. script.type = "text/javascript";
  10874. script.src = url;
  10875. script.async = true;
  10876. callback = function(event) {
  10877. removeEventListenerFn(script, "load", callback);
  10878. removeEventListenerFn(script, "error", callback);
  10879. rawDocument.body.removeChild(script);
  10880. script = null;
  10881. var status = -1;
  10882. var text = "unknown";
  10883. if (event) {
  10884. if (event.type === "load" && !callbacks.wasCalled(callbackPath)) {
  10885. event = { type: "error" };
  10886. }
  10887. text = event.type;
  10888. status = event.type === "error" ? 404 : 200;
  10889. }
  10890. if (done) {
  10891. done(status, text);
  10892. }
  10893. };
  10894. addEventListenerFn(script, "load", callback);
  10895. addEventListenerFn(script, "error", callback);
  10896. rawDocument.body.appendChild(script);
  10897. return callback;
  10898. }
  10899. }
  10900. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  10901. $interpolateMinErr.throwNoconcat = function(text) {
  10902. throw $interpolateMinErr('noconcat',
  10903. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  10904. "interpolations that concatenate multiple expressions when a trusted value is " +
  10905. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  10906. };
  10907. $interpolateMinErr.interr = function(text, err) {
  10908. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  10909. };
  10910. /**
  10911. * @ngdoc provider
  10912. * @name $interpolateProvider
  10913. *
  10914. * @description
  10915. *
  10916. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  10917. *
  10918. * <div class="alert alert-danger">
  10919. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  10920. * template within a Python Jinja template (or any other template language). Mixing templating
  10921. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  10922. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  10923. * security bugs!
  10924. * </div>
  10925. *
  10926. * @example
  10927. <example name="custom-interpolation-markup" module="customInterpolationApp">
  10928. <file name="index.html">
  10929. <script>
  10930. var customInterpolationApp = angular.module('customInterpolationApp', []);
  10931. customInterpolationApp.config(function($interpolateProvider) {
  10932. $interpolateProvider.startSymbol('//');
  10933. $interpolateProvider.endSymbol('//');
  10934. });
  10935. customInterpolationApp.controller('DemoController', function() {
  10936. this.label = "This binding is brought you by // interpolation symbols.";
  10937. });
  10938. </script>
  10939. <div ng-controller="DemoController as demo">
  10940. //demo.label//
  10941. </div>
  10942. </file>
  10943. <file name="protractor.js" type="protractor">
  10944. it('should interpolate binding with custom symbols', function() {
  10945. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  10946. });
  10947. </file>
  10948. </example>
  10949. */
  10950. function $InterpolateProvider() {
  10951. var startSymbol = '{{';
  10952. var endSymbol = '}}';
  10953. /**
  10954. * @ngdoc method
  10955. * @name $interpolateProvider#startSymbol
  10956. * @description
  10957. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  10958. *
  10959. * @param {string=} value new value to set the starting symbol to.
  10960. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  10961. */
  10962. this.startSymbol = function(value) {
  10963. if (value) {
  10964. startSymbol = value;
  10965. return this;
  10966. } else {
  10967. return startSymbol;
  10968. }
  10969. };
  10970. /**
  10971. * @ngdoc method
  10972. * @name $interpolateProvider#endSymbol
  10973. * @description
  10974. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  10975. *
  10976. * @param {string=} value new value to set the ending symbol to.
  10977. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  10978. */
  10979. this.endSymbol = function(value) {
  10980. if (value) {
  10981. endSymbol = value;
  10982. return this;
  10983. } else {
  10984. return endSymbol;
  10985. }
  10986. };
  10987. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  10988. var startSymbolLength = startSymbol.length,
  10989. endSymbolLength = endSymbol.length,
  10990. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  10991. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  10992. function escape(ch) {
  10993. return '\\\\\\' + ch;
  10994. }
  10995. function unescapeText(text) {
  10996. return text.replace(escapedStartRegexp, startSymbol).
  10997. replace(escapedEndRegexp, endSymbol);
  10998. }
  10999. function stringify(value) {
  11000. if (value == null) { // null || undefined
  11001. return '';
  11002. }
  11003. switch (typeof value) {
  11004. case 'string':
  11005. break;
  11006. case 'number':
  11007. value = '' + value;
  11008. break;
  11009. default:
  11010. value = toJson(value);
  11011. }
  11012. return value;
  11013. }
  11014. //TODO: this is the same as the constantWatchDelegate in parse.js
  11015. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  11016. var unwatch;
  11017. return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  11018. unwatch();
  11019. return constantInterp(scope);
  11020. }, listener, objectEquality);
  11021. }
  11022. /**
  11023. * @ngdoc service
  11024. * @name $interpolate
  11025. * @kind function
  11026. *
  11027. * @requires $parse
  11028. * @requires $sce
  11029. *
  11030. * @description
  11031. *
  11032. * Compiles a string with markup into an interpolation function. This service is used by the
  11033. * HTML {@link ng.$compile $compile} service for data binding. See
  11034. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  11035. * interpolation markup.
  11036. *
  11037. *
  11038. * ```js
  11039. * var $interpolate = ...; // injected
  11040. * var exp = $interpolate('Hello {{name | uppercase}}!');
  11041. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  11042. * ```
  11043. *
  11044. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  11045. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  11046. * evaluate to a value other than `undefined`.
  11047. *
  11048. * ```js
  11049. * var $interpolate = ...; // injected
  11050. * var context = {greeting: 'Hello', name: undefined };
  11051. *
  11052. * // default "forgiving" mode
  11053. * var exp = $interpolate('{{greeting}} {{name}}!');
  11054. * expect(exp(context)).toEqual('Hello !');
  11055. *
  11056. * // "allOrNothing" mode
  11057. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  11058. * expect(exp(context)).toBeUndefined();
  11059. * context.name = 'Angular';
  11060. * expect(exp(context)).toEqual('Hello Angular!');
  11061. * ```
  11062. *
  11063. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  11064. *
  11065. * #### Escaped Interpolation
  11066. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  11067. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  11068. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  11069. * or binding.
  11070. *
  11071. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  11072. * degree, while also enabling code examples to work without relying on the
  11073. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  11074. *
  11075. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  11076. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  11077. * interpolation start/end markers with their escaped counterparts.**
  11078. *
  11079. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  11080. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  11081. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  11082. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  11083. * this is typically useful only when user-data is used in rendering a template from the server, or
  11084. * when otherwise untrusted data is used by a directive.
  11085. *
  11086. * <example>
  11087. * <file name="index.html">
  11088. * <div ng-init="username='A user'">
  11089. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  11090. * </p>
  11091. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  11092. * application, but fails to accomplish their task, because the server has correctly
  11093. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  11094. * characters.</p>
  11095. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  11096. * from the database by an administrator.</p>
  11097. * </div>
  11098. * </file>
  11099. * </example>
  11100. *
  11101. * @knownIssue
  11102. * It is currently not possible for an interpolated expression to contain the interpolation end
  11103. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  11104. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  11105. *
  11106. * @knownIssue
  11107. * All directives and components must use the standard `{{` `}}` interpolation symbols
  11108. * in their templates. If you change the application interpolation symbols the {@link $compile}
  11109. * service will attempt to denormalize the standard symbols to the custom symbols.
  11110. * The denormalization process is not clever enough to know not to replace instances of the standard
  11111. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  11112. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  11113. *
  11114. * ```
  11115. * <div data-context='{"context":{"id":3,"type":"page"}}">
  11116. * ```
  11117. *
  11118. * The workaround is to ensure that such instances are separated by whitespace:
  11119. * ```
  11120. * <div data-context='{"context":{"id":3,"type":"page"} }">
  11121. * ```
  11122. *
  11123. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  11124. *
  11125. * @param {string} text The text with markup to interpolate.
  11126. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  11127. * embedded expression in order to return an interpolation function. Strings with no
  11128. * embedded expression will return null for the interpolation function.
  11129. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  11130. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  11131. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  11132. * provides Strict Contextual Escaping for details.
  11133. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  11134. * unless all embedded expressions evaluate to a value other than `undefined`.
  11135. * @returns {function(context)} an interpolation function which is used to compute the
  11136. * interpolated string. The function has these parameters:
  11137. *
  11138. * - `context`: evaluation context for all expressions embedded in the interpolated text
  11139. */
  11140. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  11141. // Provide a quick exit and simplified result function for text with no interpolation
  11142. if (!text.length || text.indexOf(startSymbol) === -1) {
  11143. var constantInterp;
  11144. if (!mustHaveExpression) {
  11145. var unescapedText = unescapeText(text);
  11146. constantInterp = valueFn(unescapedText);
  11147. constantInterp.exp = text;
  11148. constantInterp.expressions = [];
  11149. constantInterp.$$watchDelegate = constantWatchDelegate;
  11150. }
  11151. return constantInterp;
  11152. }
  11153. allOrNothing = !!allOrNothing;
  11154. var startIndex,
  11155. endIndex,
  11156. index = 0,
  11157. expressions = [],
  11158. parseFns = [],
  11159. textLength = text.length,
  11160. exp,
  11161. concat = [],
  11162. expressionPositions = [];
  11163. while (index < textLength) {
  11164. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  11165. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  11166. if (index !== startIndex) {
  11167. concat.push(unescapeText(text.substring(index, startIndex)));
  11168. }
  11169. exp = text.substring(startIndex + startSymbolLength, endIndex);
  11170. expressions.push(exp);
  11171. parseFns.push($parse(exp, parseStringifyInterceptor));
  11172. index = endIndex + endSymbolLength;
  11173. expressionPositions.push(concat.length);
  11174. concat.push('');
  11175. } else {
  11176. // we did not find an interpolation, so we have to add the remainder to the separators array
  11177. if (index !== textLength) {
  11178. concat.push(unescapeText(text.substring(index)));
  11179. }
  11180. break;
  11181. }
  11182. }
  11183. // Concatenating expressions makes it hard to reason about whether some combination of
  11184. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  11185. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  11186. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  11187. // make it obvious that you bound the value to some user controlled value. This helps reduce
  11188. // the load when auditing for XSS issues.
  11189. if (trustedContext && concat.length > 1) {
  11190. $interpolateMinErr.throwNoconcat(text);
  11191. }
  11192. if (!mustHaveExpression || expressions.length) {
  11193. var compute = function(values) {
  11194. for (var i = 0, ii = expressions.length; i < ii; i++) {
  11195. if (allOrNothing && isUndefined(values[i])) return;
  11196. concat[expressionPositions[i]] = values[i];
  11197. }
  11198. return concat.join('');
  11199. };
  11200. var getValue = function(value) {
  11201. return trustedContext ?
  11202. $sce.getTrusted(trustedContext, value) :
  11203. $sce.valueOf(value);
  11204. };
  11205. return extend(function interpolationFn(context) {
  11206. var i = 0;
  11207. var ii = expressions.length;
  11208. var values = new Array(ii);
  11209. try {
  11210. for (; i < ii; i++) {
  11211. values[i] = parseFns[i](context);
  11212. }
  11213. return compute(values);
  11214. } catch (err) {
  11215. $exceptionHandler($interpolateMinErr.interr(text, err));
  11216. }
  11217. }, {
  11218. // all of these properties are undocumented for now
  11219. exp: text, //just for compatibility with regular watchers created via $watch
  11220. expressions: expressions,
  11221. $$watchDelegate: function(scope, listener) {
  11222. var lastValue;
  11223. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  11224. var currValue = compute(values);
  11225. if (isFunction(listener)) {
  11226. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  11227. }
  11228. lastValue = currValue;
  11229. });
  11230. }
  11231. });
  11232. }
  11233. function parseStringifyInterceptor(value) {
  11234. try {
  11235. value = getValue(value);
  11236. return allOrNothing && !isDefined(value) ? value : stringify(value);
  11237. } catch (err) {
  11238. $exceptionHandler($interpolateMinErr.interr(text, err));
  11239. }
  11240. }
  11241. }
  11242. /**
  11243. * @ngdoc method
  11244. * @name $interpolate#startSymbol
  11245. * @description
  11246. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  11247. *
  11248. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  11249. * the symbol.
  11250. *
  11251. * @returns {string} start symbol.
  11252. */
  11253. $interpolate.startSymbol = function() {
  11254. return startSymbol;
  11255. };
  11256. /**
  11257. * @ngdoc method
  11258. * @name $interpolate#endSymbol
  11259. * @description
  11260. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11261. *
  11262. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  11263. * the symbol.
  11264. *
  11265. * @returns {string} end symbol.
  11266. */
  11267. $interpolate.endSymbol = function() {
  11268. return endSymbol;
  11269. };
  11270. return $interpolate;
  11271. }];
  11272. }
  11273. function $IntervalProvider() {
  11274. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  11275. function($rootScope, $window, $q, $$q, $browser) {
  11276. var intervals = {};
  11277. /**
  11278. * @ngdoc service
  11279. * @name $interval
  11280. *
  11281. * @description
  11282. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  11283. * milliseconds.
  11284. *
  11285. * The return value of registering an interval function is a promise. This promise will be
  11286. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  11287. * run indefinitely if `count` is not defined. The value of the notification will be the
  11288. * number of iterations that have run.
  11289. * To cancel an interval, call `$interval.cancel(promise)`.
  11290. *
  11291. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  11292. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  11293. * time.
  11294. *
  11295. * <div class="alert alert-warning">
  11296. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  11297. * with them. In particular they are not automatically destroyed when a controller's scope or a
  11298. * directive's element are destroyed.
  11299. * You should take this into consideration and make sure to always cancel the interval at the
  11300. * appropriate moment. See the example below for more details on how and when to do this.
  11301. * </div>
  11302. *
  11303. * @param {function()} fn A function that should be called repeatedly.
  11304. * @param {number} delay Number of milliseconds between each function call.
  11305. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  11306. * indefinitely.
  11307. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  11308. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  11309. * @param {...*=} Pass additional parameters to the executed function.
  11310. * @returns {promise} A promise which will be notified on each iteration.
  11311. *
  11312. * @example
  11313. * <example module="intervalExample">
  11314. * <file name="index.html">
  11315. * <script>
  11316. * angular.module('intervalExample', [])
  11317. * .controller('ExampleController', ['$scope', '$interval',
  11318. * function($scope, $interval) {
  11319. * $scope.format = 'M/d/yy h:mm:ss a';
  11320. * $scope.blood_1 = 100;
  11321. * $scope.blood_2 = 120;
  11322. *
  11323. * var stop;
  11324. * $scope.fight = function() {
  11325. * // Don't start a new fight if we are already fighting
  11326. * if ( angular.isDefined(stop) ) return;
  11327. *
  11328. * stop = $interval(function() {
  11329. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  11330. * $scope.blood_1 = $scope.blood_1 - 3;
  11331. * $scope.blood_2 = $scope.blood_2 - 4;
  11332. * } else {
  11333. * $scope.stopFight();
  11334. * }
  11335. * }, 100);
  11336. * };
  11337. *
  11338. * $scope.stopFight = function() {
  11339. * if (angular.isDefined(stop)) {
  11340. * $interval.cancel(stop);
  11341. * stop = undefined;
  11342. * }
  11343. * };
  11344. *
  11345. * $scope.resetFight = function() {
  11346. * $scope.blood_1 = 100;
  11347. * $scope.blood_2 = 120;
  11348. * };
  11349. *
  11350. * $scope.$on('$destroy', function() {
  11351. * // Make sure that the interval is destroyed too
  11352. * $scope.stopFight();
  11353. * });
  11354. * }])
  11355. * // Register the 'myCurrentTime' directive factory method.
  11356. * // We inject $interval and dateFilter service since the factory method is DI.
  11357. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  11358. * function($interval, dateFilter) {
  11359. * // return the directive link function. (compile function not needed)
  11360. * return function(scope, element, attrs) {
  11361. * var format, // date format
  11362. * stopTime; // so that we can cancel the time updates
  11363. *
  11364. * // used to update the UI
  11365. * function updateTime() {
  11366. * element.text(dateFilter(new Date(), format));
  11367. * }
  11368. *
  11369. * // watch the expression, and update the UI on change.
  11370. * scope.$watch(attrs.myCurrentTime, function(value) {
  11371. * format = value;
  11372. * updateTime();
  11373. * });
  11374. *
  11375. * stopTime = $interval(updateTime, 1000);
  11376. *
  11377. * // listen on DOM destroy (removal) event, and cancel the next UI update
  11378. * // to prevent updating time after the DOM element was removed.
  11379. * element.on('$destroy', function() {
  11380. * $interval.cancel(stopTime);
  11381. * });
  11382. * }
  11383. * }]);
  11384. * </script>
  11385. *
  11386. * <div>
  11387. * <div ng-controller="ExampleController">
  11388. * <label>Date format: <input ng-model="format"></label> <hr/>
  11389. * Current time is: <span my-current-time="format"></span>
  11390. * <hr/>
  11391. * Blood 1 : <font color='red'>{{blood_1}}</font>
  11392. * Blood 2 : <font color='red'>{{blood_2}}</font>
  11393. * <button type="button" data-ng-click="fight()">Fight</button>
  11394. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  11395. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  11396. * </div>
  11397. * </div>
  11398. *
  11399. * </file>
  11400. * </example>
  11401. */
  11402. function interval(fn, delay, count, invokeApply) {
  11403. var hasParams = arguments.length > 4,
  11404. args = hasParams ? sliceArgs(arguments, 4) : [],
  11405. setInterval = $window.setInterval,
  11406. clearInterval = $window.clearInterval,
  11407. iteration = 0,
  11408. skipApply = (isDefined(invokeApply) && !invokeApply),
  11409. deferred = (skipApply ? $$q : $q).defer(),
  11410. promise = deferred.promise;
  11411. count = isDefined(count) ? count : 0;
  11412. promise.$$intervalId = setInterval(function tick() {
  11413. if (skipApply) {
  11414. $browser.defer(callback);
  11415. } else {
  11416. $rootScope.$evalAsync(callback);
  11417. }
  11418. deferred.notify(iteration++);
  11419. if (count > 0 && iteration >= count) {
  11420. deferred.resolve(iteration);
  11421. clearInterval(promise.$$intervalId);
  11422. delete intervals[promise.$$intervalId];
  11423. }
  11424. if (!skipApply) $rootScope.$apply();
  11425. }, delay);
  11426. intervals[promise.$$intervalId] = deferred;
  11427. return promise;
  11428. function callback() {
  11429. if (!hasParams) {
  11430. fn(iteration);
  11431. } else {
  11432. fn.apply(null, args);
  11433. }
  11434. }
  11435. }
  11436. /**
  11437. * @ngdoc method
  11438. * @name $interval#cancel
  11439. *
  11440. * @description
  11441. * Cancels a task associated with the `promise`.
  11442. *
  11443. * @param {Promise=} promise returned by the `$interval` function.
  11444. * @returns {boolean} Returns `true` if the task was successfully canceled.
  11445. */
  11446. interval.cancel = function(promise) {
  11447. if (promise && promise.$$intervalId in intervals) {
  11448. intervals[promise.$$intervalId].reject('canceled');
  11449. $window.clearInterval(promise.$$intervalId);
  11450. delete intervals[promise.$$intervalId];
  11451. return true;
  11452. }
  11453. return false;
  11454. };
  11455. return interval;
  11456. }];
  11457. }
  11458. /**
  11459. * @ngdoc service
  11460. * @name $jsonpCallbacks
  11461. * @requires $window
  11462. * @description
  11463. * This service handles the lifecycle of callbacks to handle JSONP requests.
  11464. * Override this service if you wish to customise where the callbacks are stored and
  11465. * how they vary compared to the requested url.
  11466. */
  11467. var $jsonpCallbacksProvider = function() {
  11468. this.$get = ['$window', function($window) {
  11469. var callbacks = $window.angular.callbacks;
  11470. var callbackMap = {};
  11471. function createCallback(callbackId) {
  11472. var callback = function(data) {
  11473. callback.data = data;
  11474. callback.called = true;
  11475. };
  11476. callback.id = callbackId;
  11477. return callback;
  11478. }
  11479. return {
  11480. /**
  11481. * @ngdoc method
  11482. * @name $jsonpCallbacks#createCallback
  11483. * @param {string} url the url of the JSONP request
  11484. * @returns {string} the callback path to send to the server as part of the JSONP request
  11485. * @description
  11486. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  11487. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  11488. */
  11489. createCallback: function(url) {
  11490. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  11491. var callbackPath = 'angular.callbacks.' + callbackId;
  11492. var callback = createCallback(callbackId);
  11493. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  11494. return callbackPath;
  11495. },
  11496. /**
  11497. * @ngdoc method
  11498. * @name $jsonpCallbacks#wasCalled
  11499. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11500. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  11501. * @description
  11502. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  11503. * callback that was passed in the request.
  11504. */
  11505. wasCalled: function(callbackPath) {
  11506. return callbackMap[callbackPath].called;
  11507. },
  11508. /**
  11509. * @ngdoc method
  11510. * @name $jsonpCallbacks#getResponse
  11511. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11512. * @returns {*} the data received from the response via the registered callback
  11513. * @description
  11514. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  11515. * in the JSONP response.
  11516. */
  11517. getResponse: function(callbackPath) {
  11518. return callbackMap[callbackPath].data;
  11519. },
  11520. /**
  11521. * @ngdoc method
  11522. * @name $jsonpCallbacks#removeCallback
  11523. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11524. * @description
  11525. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  11526. * completed or timed-out.
  11527. */
  11528. removeCallback: function(callbackPath) {
  11529. var callback = callbackMap[callbackPath];
  11530. delete callbacks[callback.id];
  11531. delete callbackMap[callbackPath];
  11532. }
  11533. };
  11534. }];
  11535. };
  11536. /**
  11537. * @ngdoc service
  11538. * @name $locale
  11539. *
  11540. * @description
  11541. * $locale service provides localization rules for various Angular components. As of right now the
  11542. * only public api is:
  11543. *
  11544. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  11545. */
  11546. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  11547. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  11548. var $locationMinErr = minErr('$location');
  11549. /**
  11550. * Encode path using encodeUriSegment, ignoring forward slashes
  11551. *
  11552. * @param {string} path Path to encode
  11553. * @returns {string}
  11554. */
  11555. function encodePath(path) {
  11556. var segments = path.split('/'),
  11557. i = segments.length;
  11558. while (i--) {
  11559. segments[i] = encodeUriSegment(segments[i]);
  11560. }
  11561. return segments.join('/');
  11562. }
  11563. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  11564. var parsedUrl = urlResolve(absoluteUrl);
  11565. locationObj.$$protocol = parsedUrl.protocol;
  11566. locationObj.$$host = parsedUrl.hostname;
  11567. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  11568. }
  11569. function parseAppUrl(relativeUrl, locationObj) {
  11570. var prefixed = (relativeUrl.charAt(0) !== '/');
  11571. if (prefixed) {
  11572. relativeUrl = '/' + relativeUrl;
  11573. }
  11574. var match = urlResolve(relativeUrl);
  11575. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  11576. match.pathname.substring(1) : match.pathname);
  11577. locationObj.$$search = parseKeyValue(match.search);
  11578. locationObj.$$hash = decodeURIComponent(match.hash);
  11579. // make sure path starts with '/';
  11580. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  11581. locationObj.$$path = '/' + locationObj.$$path;
  11582. }
  11583. }
  11584. function startsWith(haystack, needle) {
  11585. return haystack.lastIndexOf(needle, 0) === 0;
  11586. }
  11587. /**
  11588. *
  11589. * @param {string} base
  11590. * @param {string} url
  11591. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  11592. * the expected string.
  11593. */
  11594. function stripBaseUrl(base, url) {
  11595. if (startsWith(url, base)) {
  11596. return url.substr(base.length);
  11597. }
  11598. }
  11599. function stripHash(url) {
  11600. var index = url.indexOf('#');
  11601. return index == -1 ? url : url.substr(0, index);
  11602. }
  11603. function trimEmptyHash(url) {
  11604. return url.replace(/(#.+)|#$/, '$1');
  11605. }
  11606. function stripFile(url) {
  11607. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  11608. }
  11609. /* return the server only (scheme://host:port) */
  11610. function serverBase(url) {
  11611. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  11612. }
  11613. /**
  11614. * LocationHtml5Url represents an url
  11615. * This object is exposed as $location service when HTML5 mode is enabled and supported
  11616. *
  11617. * @constructor
  11618. * @param {string} appBase application base URL
  11619. * @param {string} appBaseNoFile application base URL stripped of any filename
  11620. * @param {string} basePrefix url path prefix
  11621. */
  11622. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  11623. this.$$html5 = true;
  11624. basePrefix = basePrefix || '';
  11625. parseAbsoluteUrl(appBase, this);
  11626. /**
  11627. * Parse given html5 (regular) url string into properties
  11628. * @param {string} url HTML5 url
  11629. * @private
  11630. */
  11631. this.$$parse = function(url) {
  11632. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  11633. if (!isString(pathUrl)) {
  11634. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  11635. appBaseNoFile);
  11636. }
  11637. parseAppUrl(pathUrl, this);
  11638. if (!this.$$path) {
  11639. this.$$path = '/';
  11640. }
  11641. this.$$compose();
  11642. };
  11643. /**
  11644. * Compose url and update `absUrl` property
  11645. * @private
  11646. */
  11647. this.$$compose = function() {
  11648. var search = toKeyValue(this.$$search),
  11649. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11650. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11651. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  11652. };
  11653. this.$$parseLinkUrl = function(url, relHref) {
  11654. if (relHref && relHref[0] === '#') {
  11655. // special case for links to hash fragments:
  11656. // keep the old url and only replace the hash fragment
  11657. this.hash(relHref.slice(1));
  11658. return true;
  11659. }
  11660. var appUrl, prevAppUrl;
  11661. var rewrittenUrl;
  11662. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  11663. prevAppUrl = appUrl;
  11664. if (isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  11665. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  11666. } else {
  11667. rewrittenUrl = appBase + prevAppUrl;
  11668. }
  11669. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  11670. rewrittenUrl = appBaseNoFile + appUrl;
  11671. } else if (appBaseNoFile == url + '/') {
  11672. rewrittenUrl = appBaseNoFile;
  11673. }
  11674. if (rewrittenUrl) {
  11675. this.$$parse(rewrittenUrl);
  11676. }
  11677. return !!rewrittenUrl;
  11678. };
  11679. }
  11680. /**
  11681. * LocationHashbangUrl represents url
  11682. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  11683. * It also serves as the base class for html5 mode fallback on legacy browsers.
  11684. *
  11685. * @constructor
  11686. * @param {string} appBase application base URL
  11687. * @param {string} appBaseNoFile application base URL stripped of any filename
  11688. * @param {string} hashPrefix hashbang prefix
  11689. */
  11690. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  11691. parseAbsoluteUrl(appBase, this);
  11692. /**
  11693. * Parse given hashbang url into properties
  11694. * @param {string} url Hashbang url
  11695. * @private
  11696. */
  11697. this.$$parse = function(url) {
  11698. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  11699. var withoutHashUrl;
  11700. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  11701. // The rest of the url starts with a hash so we have
  11702. // got either a hashbang path or a plain hash fragment
  11703. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  11704. if (isUndefined(withoutHashUrl)) {
  11705. // There was no hashbang prefix so we just have a hash fragment
  11706. withoutHashUrl = withoutBaseUrl;
  11707. }
  11708. } else {
  11709. // There was no hashbang path nor hash fragment:
  11710. // If we are in HTML5 mode we use what is left as the path;
  11711. // Otherwise we ignore what is left
  11712. if (this.$$html5) {
  11713. withoutHashUrl = withoutBaseUrl;
  11714. } else {
  11715. withoutHashUrl = '';
  11716. if (isUndefined(withoutBaseUrl)) {
  11717. appBase = url;
  11718. this.replace();
  11719. }
  11720. }
  11721. }
  11722. parseAppUrl(withoutHashUrl, this);
  11723. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  11724. this.$$compose();
  11725. /*
  11726. * In Windows, on an anchor node on documents loaded from
  11727. * the filesystem, the browser will return a pathname
  11728. * prefixed with the drive name ('/C:/path') when a
  11729. * pathname without a drive is set:
  11730. * * a.setAttribute('href', '/foo')
  11731. * * a.pathname === '/C:/foo' //true
  11732. *
  11733. * Inside of Angular, we're always using pathnames that
  11734. * do not include drive names for routing.
  11735. */
  11736. function removeWindowsDriveName(path, url, base) {
  11737. /*
  11738. Matches paths for file protocol on windows,
  11739. such as /C:/foo/bar, and captures only /foo/bar.
  11740. */
  11741. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  11742. var firstPathSegmentMatch;
  11743. //Get the relative path from the input URL.
  11744. if (startsWith(url, base)) {
  11745. url = url.replace(base, '');
  11746. }
  11747. // The input URL intentionally contains a first path segment that ends with a colon.
  11748. if (windowsFilePathExp.exec(url)) {
  11749. return path;
  11750. }
  11751. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  11752. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  11753. }
  11754. };
  11755. /**
  11756. * Compose hashbang url and update `absUrl` property
  11757. * @private
  11758. */
  11759. this.$$compose = function() {
  11760. var search = toKeyValue(this.$$search),
  11761. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11762. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11763. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  11764. };
  11765. this.$$parseLinkUrl = function(url, relHref) {
  11766. if (stripHash(appBase) == stripHash(url)) {
  11767. this.$$parse(url);
  11768. return true;
  11769. }
  11770. return false;
  11771. };
  11772. }
  11773. /**
  11774. * LocationHashbangUrl represents url
  11775. * This object is exposed as $location service when html5 history api is enabled but the browser
  11776. * does not support it.
  11777. *
  11778. * @constructor
  11779. * @param {string} appBase application base URL
  11780. * @param {string} appBaseNoFile application base URL stripped of any filename
  11781. * @param {string} hashPrefix hashbang prefix
  11782. */
  11783. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  11784. this.$$html5 = true;
  11785. LocationHashbangUrl.apply(this, arguments);
  11786. this.$$parseLinkUrl = function(url, relHref) {
  11787. if (relHref && relHref[0] === '#') {
  11788. // special case for links to hash fragments:
  11789. // keep the old url and only replace the hash fragment
  11790. this.hash(relHref.slice(1));
  11791. return true;
  11792. }
  11793. var rewrittenUrl;
  11794. var appUrl;
  11795. if (appBase == stripHash(url)) {
  11796. rewrittenUrl = url;
  11797. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  11798. rewrittenUrl = appBase + hashPrefix + appUrl;
  11799. } else if (appBaseNoFile === url + '/') {
  11800. rewrittenUrl = appBaseNoFile;
  11801. }
  11802. if (rewrittenUrl) {
  11803. this.$$parse(rewrittenUrl);
  11804. }
  11805. return !!rewrittenUrl;
  11806. };
  11807. this.$$compose = function() {
  11808. var search = toKeyValue(this.$$search),
  11809. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11810. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11811. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  11812. this.$$absUrl = appBase + hashPrefix + this.$$url;
  11813. };
  11814. }
  11815. var locationPrototype = {
  11816. /**
  11817. * Ensure absolute url is initialized.
  11818. * @private
  11819. */
  11820. $$absUrl:'',
  11821. /**
  11822. * Are we in html5 mode?
  11823. * @private
  11824. */
  11825. $$html5: false,
  11826. /**
  11827. * Has any change been replacing?
  11828. * @private
  11829. */
  11830. $$replace: false,
  11831. /**
  11832. * @ngdoc method
  11833. * @name $location#absUrl
  11834. *
  11835. * @description
  11836. * This method is getter only.
  11837. *
  11838. * Return full url representation with all segments encoded according to rules specified in
  11839. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  11840. *
  11841. *
  11842. * ```js
  11843. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11844. * var absUrl = $location.absUrl();
  11845. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  11846. * ```
  11847. *
  11848. * @return {string} full url
  11849. */
  11850. absUrl: locationGetter('$$absUrl'),
  11851. /**
  11852. * @ngdoc method
  11853. * @name $location#url
  11854. *
  11855. * @description
  11856. * This method is getter / setter.
  11857. *
  11858. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  11859. *
  11860. * Change path, search and hash, when called with parameter and return `$location`.
  11861. *
  11862. *
  11863. * ```js
  11864. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11865. * var url = $location.url();
  11866. * // => "/some/path?foo=bar&baz=xoxo"
  11867. * ```
  11868. *
  11869. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  11870. * @return {string} url
  11871. */
  11872. url: function(url) {
  11873. if (isUndefined(url)) {
  11874. return this.$$url;
  11875. }
  11876. var match = PATH_MATCH.exec(url);
  11877. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  11878. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  11879. this.hash(match[5] || '');
  11880. return this;
  11881. },
  11882. /**
  11883. * @ngdoc method
  11884. * @name $location#protocol
  11885. *
  11886. * @description
  11887. * This method is getter only.
  11888. *
  11889. * Return protocol of current url.
  11890. *
  11891. *
  11892. * ```js
  11893. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11894. * var protocol = $location.protocol();
  11895. * // => "http"
  11896. * ```
  11897. *
  11898. * @return {string} protocol of current url
  11899. */
  11900. protocol: locationGetter('$$protocol'),
  11901. /**
  11902. * @ngdoc method
  11903. * @name $location#host
  11904. *
  11905. * @description
  11906. * This method is getter only.
  11907. *
  11908. * Return host of current url.
  11909. *
  11910. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  11911. *
  11912. *
  11913. * ```js
  11914. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11915. * var host = $location.host();
  11916. * // => "example.com"
  11917. *
  11918. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  11919. * host = $location.host();
  11920. * // => "example.com"
  11921. * host = location.host;
  11922. * // => "example.com:8080"
  11923. * ```
  11924. *
  11925. * @return {string} host of current url.
  11926. */
  11927. host: locationGetter('$$host'),
  11928. /**
  11929. * @ngdoc method
  11930. * @name $location#port
  11931. *
  11932. * @description
  11933. * This method is getter only.
  11934. *
  11935. * Return port of current url.
  11936. *
  11937. *
  11938. * ```js
  11939. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11940. * var port = $location.port();
  11941. * // => 80
  11942. * ```
  11943. *
  11944. * @return {Number} port
  11945. */
  11946. port: locationGetter('$$port'),
  11947. /**
  11948. * @ngdoc method
  11949. * @name $location#path
  11950. *
  11951. * @description
  11952. * This method is getter / setter.
  11953. *
  11954. * Return path of current url when called without any parameter.
  11955. *
  11956. * Change path when called with parameter and return `$location`.
  11957. *
  11958. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  11959. * if it is missing.
  11960. *
  11961. *
  11962. * ```js
  11963. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11964. * var path = $location.path();
  11965. * // => "/some/path"
  11966. * ```
  11967. *
  11968. * @param {(string|number)=} path New path
  11969. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  11970. */
  11971. path: locationGetterSetter('$$path', function(path) {
  11972. path = path !== null ? path.toString() : '';
  11973. return path.charAt(0) == '/' ? path : '/' + path;
  11974. }),
  11975. /**
  11976. * @ngdoc method
  11977. * @name $location#search
  11978. *
  11979. * @description
  11980. * This method is getter / setter.
  11981. *
  11982. * Return search part (as object) of current url when called without any parameter.
  11983. *
  11984. * Change search part when called with parameter and return `$location`.
  11985. *
  11986. *
  11987. * ```js
  11988. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11989. * var searchObject = $location.search();
  11990. * // => {foo: 'bar', baz: 'xoxo'}
  11991. *
  11992. * // set foo to 'yipee'
  11993. * $location.search('foo', 'yipee');
  11994. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  11995. * ```
  11996. *
  11997. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  11998. * hash object.
  11999. *
  12000. * When called with a single argument the method acts as a setter, setting the `search` component
  12001. * of `$location` to the specified value.
  12002. *
  12003. * If the argument is a hash object containing an array of values, these values will be encoded
  12004. * as duplicate search parameters in the url.
  12005. *
  12006. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  12007. * will override only a single search property.
  12008. *
  12009. * If `paramValue` is an array, it will override the property of the `search` component of
  12010. * `$location` specified via the first argument.
  12011. *
  12012. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  12013. *
  12014. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  12015. * value nor trailing equal sign.
  12016. *
  12017. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  12018. * one or more arguments returns `$location` object itself.
  12019. */
  12020. search: function(search, paramValue) {
  12021. switch (arguments.length) {
  12022. case 0:
  12023. return this.$$search;
  12024. case 1:
  12025. if (isString(search) || isNumber(search)) {
  12026. search = search.toString();
  12027. this.$$search = parseKeyValue(search);
  12028. } else if (isObject(search)) {
  12029. search = copy(search, {});
  12030. // remove object undefined or null properties
  12031. forEach(search, function(value, key) {
  12032. if (value == null) delete search[key];
  12033. });
  12034. this.$$search = search;
  12035. } else {
  12036. throw $locationMinErr('isrcharg',
  12037. 'The first argument of the `$location#search()` call must be a string or an object.');
  12038. }
  12039. break;
  12040. default:
  12041. if (isUndefined(paramValue) || paramValue === null) {
  12042. delete this.$$search[search];
  12043. } else {
  12044. this.$$search[search] = paramValue;
  12045. }
  12046. }
  12047. this.$$compose();
  12048. return this;
  12049. },
  12050. /**
  12051. * @ngdoc method
  12052. * @name $location#hash
  12053. *
  12054. * @description
  12055. * This method is getter / setter.
  12056. *
  12057. * Returns the hash fragment when called without any parameters.
  12058. *
  12059. * Changes the hash fragment when called with a parameter and returns `$location`.
  12060. *
  12061. *
  12062. * ```js
  12063. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  12064. * var hash = $location.hash();
  12065. * // => "hashValue"
  12066. * ```
  12067. *
  12068. * @param {(string|number)=} hash New hash fragment
  12069. * @return {string} hash
  12070. */
  12071. hash: locationGetterSetter('$$hash', function(hash) {
  12072. return hash !== null ? hash.toString() : '';
  12073. }),
  12074. /**
  12075. * @ngdoc method
  12076. * @name $location#replace
  12077. *
  12078. * @description
  12079. * If called, all changes to $location during the current `$digest` will replace the current history
  12080. * record, instead of adding a new one.
  12081. */
  12082. replace: function() {
  12083. this.$$replace = true;
  12084. return this;
  12085. }
  12086. };
  12087. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  12088. Location.prototype = Object.create(locationPrototype);
  12089. /**
  12090. * @ngdoc method
  12091. * @name $location#state
  12092. *
  12093. * @description
  12094. * This method is getter / setter.
  12095. *
  12096. * Return the history state object when called without any parameter.
  12097. *
  12098. * Change the history state object when called with one parameter and return `$location`.
  12099. * The state object is later passed to `pushState` or `replaceState`.
  12100. *
  12101. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  12102. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  12103. * older browsers (like IE9 or Android < 4.0), don't use this method.
  12104. *
  12105. * @param {object=} state State object for pushState or replaceState
  12106. * @return {object} state
  12107. */
  12108. Location.prototype.state = function(state) {
  12109. if (!arguments.length) {
  12110. return this.$$state;
  12111. }
  12112. if (Location !== LocationHtml5Url || !this.$$html5) {
  12113. throw $locationMinErr('nostate', 'History API state support is available only ' +
  12114. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  12115. }
  12116. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  12117. // but we're changing the $$state reference to $browser.state() during the $digest
  12118. // so the modification window is narrow.
  12119. this.$$state = isUndefined(state) ? null : state;
  12120. return this;
  12121. };
  12122. });
  12123. function locationGetter(property) {
  12124. return function() {
  12125. return this[property];
  12126. };
  12127. }
  12128. function locationGetterSetter(property, preprocess) {
  12129. return function(value) {
  12130. if (isUndefined(value)) {
  12131. return this[property];
  12132. }
  12133. this[property] = preprocess(value);
  12134. this.$$compose();
  12135. return this;
  12136. };
  12137. }
  12138. /**
  12139. * @ngdoc service
  12140. * @name $location
  12141. *
  12142. * @requires $rootElement
  12143. *
  12144. * @description
  12145. * The $location service parses the URL in the browser address bar (based on the
  12146. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  12147. * available to your application. Changes to the URL in the address bar are reflected into
  12148. * $location service and changes to $location are reflected into the browser address bar.
  12149. *
  12150. * **The $location service:**
  12151. *
  12152. * - Exposes the current URL in the browser address bar, so you can
  12153. * - Watch and observe the URL.
  12154. * - Change the URL.
  12155. * - Synchronizes the URL with the browser when the user
  12156. * - Changes the address bar.
  12157. * - Clicks the back or forward button (or clicks a History link).
  12158. * - Clicks on a link.
  12159. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  12160. *
  12161. * For more information see {@link guide/$location Developer Guide: Using $location}
  12162. */
  12163. /**
  12164. * @ngdoc provider
  12165. * @name $locationProvider
  12166. * @description
  12167. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  12168. */
  12169. function $LocationProvider() {
  12170. var hashPrefix = '',
  12171. html5Mode = {
  12172. enabled: false,
  12173. requireBase: true,
  12174. rewriteLinks: true
  12175. };
  12176. /**
  12177. * @ngdoc method
  12178. * @name $locationProvider#hashPrefix
  12179. * @description
  12180. * @param {string=} prefix Prefix for hash part (containing path and search)
  12181. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12182. */
  12183. this.hashPrefix = function(prefix) {
  12184. if (isDefined(prefix)) {
  12185. hashPrefix = prefix;
  12186. return this;
  12187. } else {
  12188. return hashPrefix;
  12189. }
  12190. };
  12191. /**
  12192. * @ngdoc method
  12193. * @name $locationProvider#html5Mode
  12194. * @description
  12195. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  12196. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  12197. * properties:
  12198. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  12199. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  12200. * support `pushState`.
  12201. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  12202. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  12203. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  12204. * See the {@link guide/$location $location guide for more information}
  12205. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  12206. * enables/disables url rewriting for relative links.
  12207. *
  12208. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  12209. */
  12210. this.html5Mode = function(mode) {
  12211. if (isBoolean(mode)) {
  12212. html5Mode.enabled = mode;
  12213. return this;
  12214. } else if (isObject(mode)) {
  12215. if (isBoolean(mode.enabled)) {
  12216. html5Mode.enabled = mode.enabled;
  12217. }
  12218. if (isBoolean(mode.requireBase)) {
  12219. html5Mode.requireBase = mode.requireBase;
  12220. }
  12221. if (isBoolean(mode.rewriteLinks)) {
  12222. html5Mode.rewriteLinks = mode.rewriteLinks;
  12223. }
  12224. return this;
  12225. } else {
  12226. return html5Mode;
  12227. }
  12228. };
  12229. /**
  12230. * @ngdoc event
  12231. * @name $location#$locationChangeStart
  12232. * @eventType broadcast on root scope
  12233. * @description
  12234. * Broadcasted before a URL will change.
  12235. *
  12236. * This change can be prevented by calling
  12237. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  12238. * details about event object. Upon successful change
  12239. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  12240. *
  12241. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12242. * the browser supports the HTML5 History API.
  12243. *
  12244. * @param {Object} angularEvent Synthetic event object.
  12245. * @param {string} newUrl New URL
  12246. * @param {string=} oldUrl URL that was before it was changed.
  12247. * @param {string=} newState New history state object
  12248. * @param {string=} oldState History state object that was before it was changed.
  12249. */
  12250. /**
  12251. * @ngdoc event
  12252. * @name $location#$locationChangeSuccess
  12253. * @eventType broadcast on root scope
  12254. * @description
  12255. * Broadcasted after a URL was changed.
  12256. *
  12257. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12258. * the browser supports the HTML5 History API.
  12259. *
  12260. * @param {Object} angularEvent Synthetic event object.
  12261. * @param {string} newUrl New URL
  12262. * @param {string=} oldUrl URL that was before it was changed.
  12263. * @param {string=} newState New history state object
  12264. * @param {string=} oldState History state object that was before it was changed.
  12265. */
  12266. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  12267. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  12268. var $location,
  12269. LocationMode,
  12270. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  12271. initialUrl = $browser.url(),
  12272. appBase;
  12273. if (html5Mode.enabled) {
  12274. if (!baseHref && html5Mode.requireBase) {
  12275. throw $locationMinErr('nobase',
  12276. "$location in HTML5 mode requires a <base> tag to be present!");
  12277. }
  12278. appBase = serverBase(initialUrl) + (baseHref || '/');
  12279. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  12280. } else {
  12281. appBase = stripHash(initialUrl);
  12282. LocationMode = LocationHashbangUrl;
  12283. }
  12284. var appBaseNoFile = stripFile(appBase);
  12285. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  12286. $location.$$parseLinkUrl(initialUrl, initialUrl);
  12287. $location.$$state = $browser.state();
  12288. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  12289. function setBrowserUrlWithFallback(url, replace, state) {
  12290. var oldUrl = $location.url();
  12291. var oldState = $location.$$state;
  12292. try {
  12293. $browser.url(url, replace, state);
  12294. // Make sure $location.state() returns referentially identical (not just deeply equal)
  12295. // state object; this makes possible quick checking if the state changed in the digest
  12296. // loop. Checking deep equality would be too expensive.
  12297. $location.$$state = $browser.state();
  12298. } catch (e) {
  12299. // Restore old values if pushState fails
  12300. $location.url(oldUrl);
  12301. $location.$$state = oldState;
  12302. throw e;
  12303. }
  12304. }
  12305. $rootElement.on('click', function(event) {
  12306. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  12307. // currently we open nice url link and redirect then
  12308. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  12309. var elm = jqLite(event.target);
  12310. // traverse the DOM up to find first A tag
  12311. while (nodeName_(elm[0]) !== 'a') {
  12312. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  12313. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  12314. }
  12315. var absHref = elm.prop('href');
  12316. // get the actual href attribute - see
  12317. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  12318. var relHref = elm.attr('href') || elm.attr('xlink:href');
  12319. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  12320. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  12321. // an animation.
  12322. absHref = urlResolve(absHref.animVal).href;
  12323. }
  12324. // Ignore when url is started with javascript: or mailto:
  12325. if (IGNORE_URI_REGEXP.test(absHref)) return;
  12326. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  12327. if ($location.$$parseLinkUrl(absHref, relHref)) {
  12328. // We do a preventDefault for all urls that are part of the angular application,
  12329. // in html5mode and also without, so that we are able to abort navigation without
  12330. // getting double entries in the location history.
  12331. event.preventDefault();
  12332. // update location manually
  12333. if ($location.absUrl() != $browser.url()) {
  12334. $rootScope.$apply();
  12335. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  12336. $window.angular['ff-684208-preventDefault'] = true;
  12337. }
  12338. }
  12339. }
  12340. });
  12341. // rewrite hashbang url <> html5 url
  12342. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  12343. $browser.url($location.absUrl(), true);
  12344. }
  12345. var initializing = true;
  12346. // update $location when $browser url changes
  12347. $browser.onUrlChange(function(newUrl, newState) {
  12348. if (isUndefined(stripBaseUrl(appBaseNoFile, newUrl))) {
  12349. // If we are navigating outside of the app then force a reload
  12350. $window.location.href = newUrl;
  12351. return;
  12352. }
  12353. $rootScope.$evalAsync(function() {
  12354. var oldUrl = $location.absUrl();
  12355. var oldState = $location.$$state;
  12356. var defaultPrevented;
  12357. newUrl = trimEmptyHash(newUrl);
  12358. $location.$$parse(newUrl);
  12359. $location.$$state = newState;
  12360. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12361. newState, oldState).defaultPrevented;
  12362. // if the location was changed by a `$locationChangeStart` handler then stop
  12363. // processing this location change
  12364. if ($location.absUrl() !== newUrl) return;
  12365. if (defaultPrevented) {
  12366. $location.$$parse(oldUrl);
  12367. $location.$$state = oldState;
  12368. setBrowserUrlWithFallback(oldUrl, false, oldState);
  12369. } else {
  12370. initializing = false;
  12371. afterLocationChange(oldUrl, oldState);
  12372. }
  12373. });
  12374. if (!$rootScope.$$phase) $rootScope.$digest();
  12375. });
  12376. // update browser
  12377. $rootScope.$watch(function $locationWatch() {
  12378. var oldUrl = trimEmptyHash($browser.url());
  12379. var newUrl = trimEmptyHash($location.absUrl());
  12380. var oldState = $browser.state();
  12381. var currentReplace = $location.$$replace;
  12382. var urlOrStateChanged = oldUrl !== newUrl ||
  12383. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  12384. if (initializing || urlOrStateChanged) {
  12385. initializing = false;
  12386. $rootScope.$evalAsync(function() {
  12387. var newUrl = $location.absUrl();
  12388. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12389. $location.$$state, oldState).defaultPrevented;
  12390. // if the location was changed by a `$locationChangeStart` handler then stop
  12391. // processing this location change
  12392. if ($location.absUrl() !== newUrl) return;
  12393. if (defaultPrevented) {
  12394. $location.$$parse(oldUrl);
  12395. $location.$$state = oldState;
  12396. } else {
  12397. if (urlOrStateChanged) {
  12398. setBrowserUrlWithFallback(newUrl, currentReplace,
  12399. oldState === $location.$$state ? null : $location.$$state);
  12400. }
  12401. afterLocationChange(oldUrl, oldState);
  12402. }
  12403. });
  12404. }
  12405. $location.$$replace = false;
  12406. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  12407. // there is a change
  12408. });
  12409. return $location;
  12410. function afterLocationChange(oldUrl, oldState) {
  12411. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  12412. $location.$$state, oldState);
  12413. }
  12414. }];
  12415. }
  12416. /**
  12417. * @ngdoc service
  12418. * @name $log
  12419. * @requires $window
  12420. *
  12421. * @description
  12422. * Simple service for logging. Default implementation safely writes the message
  12423. * into the browser's console (if present).
  12424. *
  12425. * The main purpose of this service is to simplify debugging and troubleshooting.
  12426. *
  12427. * The default is to log `debug` messages. You can use
  12428. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  12429. *
  12430. * @example
  12431. <example module="logExample">
  12432. <file name="script.js">
  12433. angular.module('logExample', [])
  12434. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  12435. $scope.$log = $log;
  12436. $scope.message = 'Hello World!';
  12437. }]);
  12438. </file>
  12439. <file name="index.html">
  12440. <div ng-controller="LogController">
  12441. <p>Reload this page with open console, enter text and hit the log button...</p>
  12442. <label>Message:
  12443. <input type="text" ng-model="message" /></label>
  12444. <button ng-click="$log.log(message)">log</button>
  12445. <button ng-click="$log.warn(message)">warn</button>
  12446. <button ng-click="$log.info(message)">info</button>
  12447. <button ng-click="$log.error(message)">error</button>
  12448. <button ng-click="$log.debug(message)">debug</button>
  12449. </div>
  12450. </file>
  12451. </example>
  12452. */
  12453. /**
  12454. * @ngdoc provider
  12455. * @name $logProvider
  12456. * @description
  12457. * Use the `$logProvider` to configure how the application logs messages
  12458. */
  12459. function $LogProvider() {
  12460. var debug = true,
  12461. self = this;
  12462. /**
  12463. * @ngdoc method
  12464. * @name $logProvider#debugEnabled
  12465. * @description
  12466. * @param {boolean=} flag enable or disable debug level messages
  12467. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12468. */
  12469. this.debugEnabled = function(flag) {
  12470. if (isDefined(flag)) {
  12471. debug = flag;
  12472. return this;
  12473. } else {
  12474. return debug;
  12475. }
  12476. };
  12477. this.$get = ['$window', function($window) {
  12478. return {
  12479. /**
  12480. * @ngdoc method
  12481. * @name $log#log
  12482. *
  12483. * @description
  12484. * Write a log message
  12485. */
  12486. log: consoleLog('log'),
  12487. /**
  12488. * @ngdoc method
  12489. * @name $log#info
  12490. *
  12491. * @description
  12492. * Write an information message
  12493. */
  12494. info: consoleLog('info'),
  12495. /**
  12496. * @ngdoc method
  12497. * @name $log#warn
  12498. *
  12499. * @description
  12500. * Write a warning message
  12501. */
  12502. warn: consoleLog('warn'),
  12503. /**
  12504. * @ngdoc method
  12505. * @name $log#error
  12506. *
  12507. * @description
  12508. * Write an error message
  12509. */
  12510. error: consoleLog('error'),
  12511. /**
  12512. * @ngdoc method
  12513. * @name $log#debug
  12514. *
  12515. * @description
  12516. * Write a debug message
  12517. */
  12518. debug: (function() {
  12519. var fn = consoleLog('debug');
  12520. return function() {
  12521. if (debug) {
  12522. fn.apply(self, arguments);
  12523. }
  12524. };
  12525. }())
  12526. };
  12527. function formatError(arg) {
  12528. if (arg instanceof Error) {
  12529. if (arg.stack) {
  12530. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  12531. ? 'Error: ' + arg.message + '\n' + arg.stack
  12532. : arg.stack;
  12533. } else if (arg.sourceURL) {
  12534. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  12535. }
  12536. }
  12537. return arg;
  12538. }
  12539. function consoleLog(type) {
  12540. var console = $window.console || {},
  12541. logFn = console[type] || console.log || noop,
  12542. hasApply = false;
  12543. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  12544. // The reason behind this is that console.log has type "object" in IE8...
  12545. try {
  12546. hasApply = !!logFn.apply;
  12547. } catch (e) {}
  12548. if (hasApply) {
  12549. return function() {
  12550. var args = [];
  12551. forEach(arguments, function(arg) {
  12552. args.push(formatError(arg));
  12553. });
  12554. return logFn.apply(console, args);
  12555. };
  12556. }
  12557. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  12558. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  12559. return function(arg1, arg2) {
  12560. logFn(arg1, arg2 == null ? '' : arg2);
  12561. };
  12562. }
  12563. }];
  12564. }
  12565. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  12566. * Any commits to this file should be reviewed with security in mind. *
  12567. * Changes to this file can potentially create security vulnerabilities. *
  12568. * An approval from 2 Core members with history of modifying *
  12569. * this file is required. *
  12570. * *
  12571. * Does the change somehow allow for arbitrary javascript to be executed? *
  12572. * Or allows for someone to change the prototype of built-in objects? *
  12573. * Or gives undesired access to variables likes document or window? *
  12574. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  12575. var $parseMinErr = minErr('$parse');
  12576. // Sandboxing Angular Expressions
  12577. // ------------------------------
  12578. // Angular expressions are generally considered safe because these expressions only have direct
  12579. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  12580. // obtaining a reference to native JS functions such as the Function constructor.
  12581. //
  12582. // As an example, consider the following Angular expression:
  12583. //
  12584. // {}.toString.constructor('alert("evil JS code")')
  12585. //
  12586. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  12587. // against the expression language, but not to prevent exploits that were enabled by exposing
  12588. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  12589. // practice and therefore we are not even trying to protect against interaction with an object
  12590. // explicitly exposed in this way.
  12591. //
  12592. // In general, it is not possible to access a Window object from an angular expression unless a
  12593. // window or some DOM object that has a reference to window is published onto a Scope.
  12594. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  12595. // native objects.
  12596. //
  12597. // See https://docs.angularjs.org/guide/security
  12598. function ensureSafeMemberName(name, fullExpression) {
  12599. if (name === "__defineGetter__" || name === "__defineSetter__"
  12600. || name === "__lookupGetter__" || name === "__lookupSetter__"
  12601. || name === "__proto__") {
  12602. throw $parseMinErr('isecfld',
  12603. 'Attempting to access a disallowed field in Angular expressions! '
  12604. + 'Expression: {0}', fullExpression);
  12605. }
  12606. return name;
  12607. }
  12608. function getStringValue(name) {
  12609. // Property names must be strings. This means that non-string objects cannot be used
  12610. // as keys in an object. Any non-string object, including a number, is typecasted
  12611. // into a string via the toString method.
  12612. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  12613. //
  12614. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  12615. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  12616. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  12617. //
  12618. // TypeError: Cannot convert object to primitive value
  12619. //
  12620. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  12621. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  12622. // such a 'broken' object as a key.
  12623. return name + '';
  12624. }
  12625. function ensureSafeObject(obj, fullExpression) {
  12626. // nifty check if obj is Function that is fast and works across iframes and other contexts
  12627. if (obj) {
  12628. if (obj.constructor === obj) {
  12629. throw $parseMinErr('isecfn',
  12630. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  12631. fullExpression);
  12632. } else if (// isWindow(obj)
  12633. obj.window === obj) {
  12634. throw $parseMinErr('isecwindow',
  12635. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  12636. fullExpression);
  12637. } else if (// isElement(obj)
  12638. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  12639. throw $parseMinErr('isecdom',
  12640. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  12641. fullExpression);
  12642. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  12643. obj === Object) {
  12644. throw $parseMinErr('isecobj',
  12645. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  12646. fullExpression);
  12647. }
  12648. }
  12649. return obj;
  12650. }
  12651. var CALL = Function.prototype.call;
  12652. var APPLY = Function.prototype.apply;
  12653. var BIND = Function.prototype.bind;
  12654. function ensureSafeFunction(obj, fullExpression) {
  12655. if (obj) {
  12656. if (obj.constructor === obj) {
  12657. throw $parseMinErr('isecfn',
  12658. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  12659. fullExpression);
  12660. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  12661. throw $parseMinErr('isecff',
  12662. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  12663. fullExpression);
  12664. }
  12665. }
  12666. }
  12667. function ensureSafeAssignContext(obj, fullExpression) {
  12668. if (obj) {
  12669. if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
  12670. obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
  12671. throw $parseMinErr('isecaf',
  12672. 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
  12673. }
  12674. }
  12675. }
  12676. var OPERATORS = createMap();
  12677. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  12678. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  12679. /////////////////////////////////////////
  12680. /**
  12681. * @constructor
  12682. */
  12683. var Lexer = function(options) {
  12684. this.options = options;
  12685. };
  12686. Lexer.prototype = {
  12687. constructor: Lexer,
  12688. lex: function(text) {
  12689. this.text = text;
  12690. this.index = 0;
  12691. this.tokens = [];
  12692. while (this.index < this.text.length) {
  12693. var ch = this.text.charAt(this.index);
  12694. if (ch === '"' || ch === "'") {
  12695. this.readString(ch);
  12696. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  12697. this.readNumber();
  12698. } else if (this.isIdentifierStart(this.peekMultichar())) {
  12699. this.readIdent();
  12700. } else if (this.is(ch, '(){}[].,;:?')) {
  12701. this.tokens.push({index: this.index, text: ch});
  12702. this.index++;
  12703. } else if (this.isWhitespace(ch)) {
  12704. this.index++;
  12705. } else {
  12706. var ch2 = ch + this.peek();
  12707. var ch3 = ch2 + this.peek(2);
  12708. var op1 = OPERATORS[ch];
  12709. var op2 = OPERATORS[ch2];
  12710. var op3 = OPERATORS[ch3];
  12711. if (op1 || op2 || op3) {
  12712. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  12713. this.tokens.push({index: this.index, text: token, operator: true});
  12714. this.index += token.length;
  12715. } else {
  12716. this.throwError('Unexpected next character ', this.index, this.index + 1);
  12717. }
  12718. }
  12719. }
  12720. return this.tokens;
  12721. },
  12722. is: function(ch, chars) {
  12723. return chars.indexOf(ch) !== -1;
  12724. },
  12725. peek: function(i) {
  12726. var num = i || 1;
  12727. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  12728. },
  12729. isNumber: function(ch) {
  12730. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  12731. },
  12732. isWhitespace: function(ch) {
  12733. // IE treats non-breaking space as \u00A0
  12734. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  12735. ch === '\n' || ch === '\v' || ch === '\u00A0');
  12736. },
  12737. isIdentifierStart: function(ch) {
  12738. return this.options.isIdentifierStart ?
  12739. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  12740. this.isValidIdentifierStart(ch);
  12741. },
  12742. isValidIdentifierStart: function(ch) {
  12743. return ('a' <= ch && ch <= 'z' ||
  12744. 'A' <= ch && ch <= 'Z' ||
  12745. '_' === ch || ch === '$');
  12746. },
  12747. isIdentifierContinue: function(ch) {
  12748. return this.options.isIdentifierContinue ?
  12749. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  12750. this.isValidIdentifierContinue(ch);
  12751. },
  12752. isValidIdentifierContinue: function(ch, cp) {
  12753. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  12754. },
  12755. codePointAt: function(ch) {
  12756. if (ch.length === 1) return ch.charCodeAt(0);
  12757. /*jshint bitwise: false*/
  12758. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  12759. /*jshint bitwise: true*/
  12760. },
  12761. peekMultichar: function() {
  12762. var ch = this.text.charAt(this.index);
  12763. var peek = this.peek();
  12764. if (!peek) {
  12765. return ch;
  12766. }
  12767. var cp1 = ch.charCodeAt(0);
  12768. var cp2 = peek.charCodeAt(0);
  12769. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  12770. return ch + peek;
  12771. }
  12772. return ch;
  12773. },
  12774. isExpOperator: function(ch) {
  12775. return (ch === '-' || ch === '+' || this.isNumber(ch));
  12776. },
  12777. throwError: function(error, start, end) {
  12778. end = end || this.index;
  12779. var colStr = (isDefined(start)
  12780. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  12781. : ' ' + end);
  12782. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  12783. error, colStr, this.text);
  12784. },
  12785. readNumber: function() {
  12786. var number = '';
  12787. var start = this.index;
  12788. while (this.index < this.text.length) {
  12789. var ch = lowercase(this.text.charAt(this.index));
  12790. if (ch == '.' || this.isNumber(ch)) {
  12791. number += ch;
  12792. } else {
  12793. var peekCh = this.peek();
  12794. if (ch == 'e' && this.isExpOperator(peekCh)) {
  12795. number += ch;
  12796. } else if (this.isExpOperator(ch) &&
  12797. peekCh && this.isNumber(peekCh) &&
  12798. number.charAt(number.length - 1) == 'e') {
  12799. number += ch;
  12800. } else if (this.isExpOperator(ch) &&
  12801. (!peekCh || !this.isNumber(peekCh)) &&
  12802. number.charAt(number.length - 1) == 'e') {
  12803. this.throwError('Invalid exponent');
  12804. } else {
  12805. break;
  12806. }
  12807. }
  12808. this.index++;
  12809. }
  12810. this.tokens.push({
  12811. index: start,
  12812. text: number,
  12813. constant: true,
  12814. value: Number(number)
  12815. });
  12816. },
  12817. readIdent: function() {
  12818. var start = this.index;
  12819. this.index += this.peekMultichar().length;
  12820. while (this.index < this.text.length) {
  12821. var ch = this.peekMultichar();
  12822. if (!this.isIdentifierContinue(ch)) {
  12823. break;
  12824. }
  12825. this.index += ch.length;
  12826. }
  12827. this.tokens.push({
  12828. index: start,
  12829. text: this.text.slice(start, this.index),
  12830. identifier: true
  12831. });
  12832. },
  12833. readString: function(quote) {
  12834. var start = this.index;
  12835. this.index++;
  12836. var string = '';
  12837. var rawString = quote;
  12838. var escape = false;
  12839. while (this.index < this.text.length) {
  12840. var ch = this.text.charAt(this.index);
  12841. rawString += ch;
  12842. if (escape) {
  12843. if (ch === 'u') {
  12844. var hex = this.text.substring(this.index + 1, this.index + 5);
  12845. if (!hex.match(/[\da-f]{4}/i)) {
  12846. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  12847. }
  12848. this.index += 4;
  12849. string += String.fromCharCode(parseInt(hex, 16));
  12850. } else {
  12851. var rep = ESCAPE[ch];
  12852. string = string + (rep || ch);
  12853. }
  12854. escape = false;
  12855. } else if (ch === '\\') {
  12856. escape = true;
  12857. } else if (ch === quote) {
  12858. this.index++;
  12859. this.tokens.push({
  12860. index: start,
  12861. text: rawString,
  12862. constant: true,
  12863. value: string
  12864. });
  12865. return;
  12866. } else {
  12867. string += ch;
  12868. }
  12869. this.index++;
  12870. }
  12871. this.throwError('Unterminated quote', start);
  12872. }
  12873. };
  12874. var AST = function(lexer, options) {
  12875. this.lexer = lexer;
  12876. this.options = options;
  12877. };
  12878. AST.Program = 'Program';
  12879. AST.ExpressionStatement = 'ExpressionStatement';
  12880. AST.AssignmentExpression = 'AssignmentExpression';
  12881. AST.ConditionalExpression = 'ConditionalExpression';
  12882. AST.LogicalExpression = 'LogicalExpression';
  12883. AST.BinaryExpression = 'BinaryExpression';
  12884. AST.UnaryExpression = 'UnaryExpression';
  12885. AST.CallExpression = 'CallExpression';
  12886. AST.MemberExpression = 'MemberExpression';
  12887. AST.Identifier = 'Identifier';
  12888. AST.Literal = 'Literal';
  12889. AST.ArrayExpression = 'ArrayExpression';
  12890. AST.Property = 'Property';
  12891. AST.ObjectExpression = 'ObjectExpression';
  12892. AST.ThisExpression = 'ThisExpression';
  12893. AST.LocalsExpression = 'LocalsExpression';
  12894. // Internal use only
  12895. AST.NGValueParameter = 'NGValueParameter';
  12896. AST.prototype = {
  12897. ast: function(text) {
  12898. this.text = text;
  12899. this.tokens = this.lexer.lex(text);
  12900. var value = this.program();
  12901. if (this.tokens.length !== 0) {
  12902. this.throwError('is an unexpected token', this.tokens[0]);
  12903. }
  12904. return value;
  12905. },
  12906. program: function() {
  12907. var body = [];
  12908. while (true) {
  12909. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  12910. body.push(this.expressionStatement());
  12911. if (!this.expect(';')) {
  12912. return { type: AST.Program, body: body};
  12913. }
  12914. }
  12915. },
  12916. expressionStatement: function() {
  12917. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  12918. },
  12919. filterChain: function() {
  12920. var left = this.expression();
  12921. var token;
  12922. while ((token = this.expect('|'))) {
  12923. left = this.filter(left);
  12924. }
  12925. return left;
  12926. },
  12927. expression: function() {
  12928. return this.assignment();
  12929. },
  12930. assignment: function() {
  12931. var result = this.ternary();
  12932. if (this.expect('=')) {
  12933. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  12934. }
  12935. return result;
  12936. },
  12937. ternary: function() {
  12938. var test = this.logicalOR();
  12939. var alternate;
  12940. var consequent;
  12941. if (this.expect('?')) {
  12942. alternate = this.expression();
  12943. if (this.consume(':')) {
  12944. consequent = this.expression();
  12945. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  12946. }
  12947. }
  12948. return test;
  12949. },
  12950. logicalOR: function() {
  12951. var left = this.logicalAND();
  12952. while (this.expect('||')) {
  12953. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  12954. }
  12955. return left;
  12956. },
  12957. logicalAND: function() {
  12958. var left = this.equality();
  12959. while (this.expect('&&')) {
  12960. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  12961. }
  12962. return left;
  12963. },
  12964. equality: function() {
  12965. var left = this.relational();
  12966. var token;
  12967. while ((token = this.expect('==','!=','===','!=='))) {
  12968. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  12969. }
  12970. return left;
  12971. },
  12972. relational: function() {
  12973. var left = this.additive();
  12974. var token;
  12975. while ((token = this.expect('<', '>', '<=', '>='))) {
  12976. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  12977. }
  12978. return left;
  12979. },
  12980. additive: function() {
  12981. var left = this.multiplicative();
  12982. var token;
  12983. while ((token = this.expect('+','-'))) {
  12984. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  12985. }
  12986. return left;
  12987. },
  12988. multiplicative: function() {
  12989. var left = this.unary();
  12990. var token;
  12991. while ((token = this.expect('*','/','%'))) {
  12992. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  12993. }
  12994. return left;
  12995. },
  12996. unary: function() {
  12997. var token;
  12998. if ((token = this.expect('+', '-', '!'))) {
  12999. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  13000. } else {
  13001. return this.primary();
  13002. }
  13003. },
  13004. primary: function() {
  13005. var primary;
  13006. if (this.expect('(')) {
  13007. primary = this.filterChain();
  13008. this.consume(')');
  13009. } else if (this.expect('[')) {
  13010. primary = this.arrayDeclaration();
  13011. } else if (this.expect('{')) {
  13012. primary = this.object();
  13013. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  13014. primary = copy(this.selfReferential[this.consume().text]);
  13015. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  13016. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  13017. } else if (this.peek().identifier) {
  13018. primary = this.identifier();
  13019. } else if (this.peek().constant) {
  13020. primary = this.constant();
  13021. } else {
  13022. this.throwError('not a primary expression', this.peek());
  13023. }
  13024. var next;
  13025. while ((next = this.expect('(', '[', '.'))) {
  13026. if (next.text === '(') {
  13027. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  13028. this.consume(')');
  13029. } else if (next.text === '[') {
  13030. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  13031. this.consume(']');
  13032. } else if (next.text === '.') {
  13033. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  13034. } else {
  13035. this.throwError('IMPOSSIBLE');
  13036. }
  13037. }
  13038. return primary;
  13039. },
  13040. filter: function(baseExpression) {
  13041. var args = [baseExpression];
  13042. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  13043. while (this.expect(':')) {
  13044. args.push(this.expression());
  13045. }
  13046. return result;
  13047. },
  13048. parseArguments: function() {
  13049. var args = [];
  13050. if (this.peekToken().text !== ')') {
  13051. do {
  13052. args.push(this.filterChain());
  13053. } while (this.expect(','));
  13054. }
  13055. return args;
  13056. },
  13057. identifier: function() {
  13058. var token = this.consume();
  13059. if (!token.identifier) {
  13060. this.throwError('is not a valid identifier', token);
  13061. }
  13062. return { type: AST.Identifier, name: token.text };
  13063. },
  13064. constant: function() {
  13065. // TODO check that it is a constant
  13066. return { type: AST.Literal, value: this.consume().value };
  13067. },
  13068. arrayDeclaration: function() {
  13069. var elements = [];
  13070. if (this.peekToken().text !== ']') {
  13071. do {
  13072. if (this.peek(']')) {
  13073. // Support trailing commas per ES5.1.
  13074. break;
  13075. }
  13076. elements.push(this.expression());
  13077. } while (this.expect(','));
  13078. }
  13079. this.consume(']');
  13080. return { type: AST.ArrayExpression, elements: elements };
  13081. },
  13082. object: function() {
  13083. var properties = [], property;
  13084. if (this.peekToken().text !== '}') {
  13085. do {
  13086. if (this.peek('}')) {
  13087. // Support trailing commas per ES5.1.
  13088. break;
  13089. }
  13090. property = {type: AST.Property, kind: 'init'};
  13091. if (this.peek().constant) {
  13092. property.key = this.constant();
  13093. property.computed = false;
  13094. this.consume(':');
  13095. property.value = this.expression();
  13096. } else if (this.peek().identifier) {
  13097. property.key = this.identifier();
  13098. property.computed = false;
  13099. if (this.peek(':')) {
  13100. this.consume(':');
  13101. property.value = this.expression();
  13102. } else {
  13103. property.value = property.key;
  13104. }
  13105. } else if (this.peek('[')) {
  13106. this.consume('[');
  13107. property.key = this.expression();
  13108. this.consume(']');
  13109. property.computed = true;
  13110. this.consume(':');
  13111. property.value = this.expression();
  13112. } else {
  13113. this.throwError("invalid key", this.peek());
  13114. }
  13115. properties.push(property);
  13116. } while (this.expect(','));
  13117. }
  13118. this.consume('}');
  13119. return {type: AST.ObjectExpression, properties: properties };
  13120. },
  13121. throwError: function(msg, token) {
  13122. throw $parseMinErr('syntax',
  13123. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  13124. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  13125. },
  13126. consume: function(e1) {
  13127. if (this.tokens.length === 0) {
  13128. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13129. }
  13130. var token = this.expect(e1);
  13131. if (!token) {
  13132. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  13133. }
  13134. return token;
  13135. },
  13136. peekToken: function() {
  13137. if (this.tokens.length === 0) {
  13138. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13139. }
  13140. return this.tokens[0];
  13141. },
  13142. peek: function(e1, e2, e3, e4) {
  13143. return this.peekAhead(0, e1, e2, e3, e4);
  13144. },
  13145. peekAhead: function(i, e1, e2, e3, e4) {
  13146. if (this.tokens.length > i) {
  13147. var token = this.tokens[i];
  13148. var t = token.text;
  13149. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  13150. (!e1 && !e2 && !e3 && !e4)) {
  13151. return token;
  13152. }
  13153. }
  13154. return false;
  13155. },
  13156. expect: function(e1, e2, e3, e4) {
  13157. var token = this.peek(e1, e2, e3, e4);
  13158. if (token) {
  13159. this.tokens.shift();
  13160. return token;
  13161. }
  13162. return false;
  13163. },
  13164. selfReferential: {
  13165. 'this': {type: AST.ThisExpression },
  13166. '$locals': {type: AST.LocalsExpression }
  13167. }
  13168. };
  13169. function ifDefined(v, d) {
  13170. return typeof v !== 'undefined' ? v : d;
  13171. }
  13172. function plusFn(l, r) {
  13173. if (typeof l === 'undefined') return r;
  13174. if (typeof r === 'undefined') return l;
  13175. return l + r;
  13176. }
  13177. function isStateless($filter, filterName) {
  13178. var fn = $filter(filterName);
  13179. return !fn.$stateful;
  13180. }
  13181. function findConstantAndWatchExpressions(ast, $filter) {
  13182. var allConstants;
  13183. var argsToWatch;
  13184. switch (ast.type) {
  13185. case AST.Program:
  13186. allConstants = true;
  13187. forEach(ast.body, function(expr) {
  13188. findConstantAndWatchExpressions(expr.expression, $filter);
  13189. allConstants = allConstants && expr.expression.constant;
  13190. });
  13191. ast.constant = allConstants;
  13192. break;
  13193. case AST.Literal:
  13194. ast.constant = true;
  13195. ast.toWatch = [];
  13196. break;
  13197. case AST.UnaryExpression:
  13198. findConstantAndWatchExpressions(ast.argument, $filter);
  13199. ast.constant = ast.argument.constant;
  13200. ast.toWatch = ast.argument.toWatch;
  13201. break;
  13202. case AST.BinaryExpression:
  13203. findConstantAndWatchExpressions(ast.left, $filter);
  13204. findConstantAndWatchExpressions(ast.right, $filter);
  13205. ast.constant = ast.left.constant && ast.right.constant;
  13206. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  13207. break;
  13208. case AST.LogicalExpression:
  13209. findConstantAndWatchExpressions(ast.left, $filter);
  13210. findConstantAndWatchExpressions(ast.right, $filter);
  13211. ast.constant = ast.left.constant && ast.right.constant;
  13212. ast.toWatch = ast.constant ? [] : [ast];
  13213. break;
  13214. case AST.ConditionalExpression:
  13215. findConstantAndWatchExpressions(ast.test, $filter);
  13216. findConstantAndWatchExpressions(ast.alternate, $filter);
  13217. findConstantAndWatchExpressions(ast.consequent, $filter);
  13218. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  13219. ast.toWatch = ast.constant ? [] : [ast];
  13220. break;
  13221. case AST.Identifier:
  13222. ast.constant = false;
  13223. ast.toWatch = [ast];
  13224. break;
  13225. case AST.MemberExpression:
  13226. findConstantAndWatchExpressions(ast.object, $filter);
  13227. if (ast.computed) {
  13228. findConstantAndWatchExpressions(ast.property, $filter);
  13229. }
  13230. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  13231. ast.toWatch = [ast];
  13232. break;
  13233. case AST.CallExpression:
  13234. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  13235. argsToWatch = [];
  13236. forEach(ast.arguments, function(expr) {
  13237. findConstantAndWatchExpressions(expr, $filter);
  13238. allConstants = allConstants && expr.constant;
  13239. if (!expr.constant) {
  13240. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13241. }
  13242. });
  13243. ast.constant = allConstants;
  13244. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  13245. break;
  13246. case AST.AssignmentExpression:
  13247. findConstantAndWatchExpressions(ast.left, $filter);
  13248. findConstantAndWatchExpressions(ast.right, $filter);
  13249. ast.constant = ast.left.constant && ast.right.constant;
  13250. ast.toWatch = [ast];
  13251. break;
  13252. case AST.ArrayExpression:
  13253. allConstants = true;
  13254. argsToWatch = [];
  13255. forEach(ast.elements, function(expr) {
  13256. findConstantAndWatchExpressions(expr, $filter);
  13257. allConstants = allConstants && expr.constant;
  13258. if (!expr.constant) {
  13259. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13260. }
  13261. });
  13262. ast.constant = allConstants;
  13263. ast.toWatch = argsToWatch;
  13264. break;
  13265. case AST.ObjectExpression:
  13266. allConstants = true;
  13267. argsToWatch = [];
  13268. forEach(ast.properties, function(property) {
  13269. findConstantAndWatchExpressions(property.value, $filter);
  13270. allConstants = allConstants && property.value.constant && !property.computed;
  13271. if (!property.value.constant) {
  13272. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  13273. }
  13274. });
  13275. ast.constant = allConstants;
  13276. ast.toWatch = argsToWatch;
  13277. break;
  13278. case AST.ThisExpression:
  13279. ast.constant = false;
  13280. ast.toWatch = [];
  13281. break;
  13282. case AST.LocalsExpression:
  13283. ast.constant = false;
  13284. ast.toWatch = [];
  13285. break;
  13286. }
  13287. }
  13288. function getInputs(body) {
  13289. if (body.length != 1) return;
  13290. var lastExpression = body[0].expression;
  13291. var candidate = lastExpression.toWatch;
  13292. if (candidate.length !== 1) return candidate;
  13293. return candidate[0] !== lastExpression ? candidate : undefined;
  13294. }
  13295. function isAssignable(ast) {
  13296. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  13297. }
  13298. function assignableAST(ast) {
  13299. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  13300. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  13301. }
  13302. }
  13303. function isLiteral(ast) {
  13304. return ast.body.length === 0 ||
  13305. ast.body.length === 1 && (
  13306. ast.body[0].expression.type === AST.Literal ||
  13307. ast.body[0].expression.type === AST.ArrayExpression ||
  13308. ast.body[0].expression.type === AST.ObjectExpression);
  13309. }
  13310. function isConstant(ast) {
  13311. return ast.constant;
  13312. }
  13313. function ASTCompiler(astBuilder, $filter) {
  13314. this.astBuilder = astBuilder;
  13315. this.$filter = $filter;
  13316. }
  13317. ASTCompiler.prototype = {
  13318. compile: function(expression, expensiveChecks) {
  13319. var self = this;
  13320. var ast = this.astBuilder.ast(expression);
  13321. this.state = {
  13322. nextId: 0,
  13323. filters: {},
  13324. expensiveChecks: expensiveChecks,
  13325. fn: {vars: [], body: [], own: {}},
  13326. assign: {vars: [], body: [], own: {}},
  13327. inputs: []
  13328. };
  13329. findConstantAndWatchExpressions(ast, self.$filter);
  13330. var extra = '';
  13331. var assignable;
  13332. this.stage = 'assign';
  13333. if ((assignable = assignableAST(ast))) {
  13334. this.state.computing = 'assign';
  13335. var result = this.nextId();
  13336. this.recurse(assignable, result);
  13337. this.return_(result);
  13338. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  13339. }
  13340. var toWatch = getInputs(ast.body);
  13341. self.stage = 'inputs';
  13342. forEach(toWatch, function(watch, key) {
  13343. var fnKey = 'fn' + key;
  13344. self.state[fnKey] = {vars: [], body: [], own: {}};
  13345. self.state.computing = fnKey;
  13346. var intoId = self.nextId();
  13347. self.recurse(watch, intoId);
  13348. self.return_(intoId);
  13349. self.state.inputs.push(fnKey);
  13350. watch.watchId = key;
  13351. });
  13352. this.state.computing = 'fn';
  13353. this.stage = 'main';
  13354. this.recurse(ast);
  13355. var fnString =
  13356. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  13357. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  13358. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  13359. this.filterPrefix() +
  13360. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  13361. extra +
  13362. this.watchFns() +
  13363. 'return fn;';
  13364. /* jshint -W054 */
  13365. var fn = (new Function('$filter',
  13366. 'ensureSafeMemberName',
  13367. 'ensureSafeObject',
  13368. 'ensureSafeFunction',
  13369. 'getStringValue',
  13370. 'ensureSafeAssignContext',
  13371. 'ifDefined',
  13372. 'plus',
  13373. 'text',
  13374. fnString))(
  13375. this.$filter,
  13376. ensureSafeMemberName,
  13377. ensureSafeObject,
  13378. ensureSafeFunction,
  13379. getStringValue,
  13380. ensureSafeAssignContext,
  13381. ifDefined,
  13382. plusFn,
  13383. expression);
  13384. /* jshint +W054 */
  13385. this.state = this.stage = undefined;
  13386. fn.literal = isLiteral(ast);
  13387. fn.constant = isConstant(ast);
  13388. return fn;
  13389. },
  13390. USE: 'use',
  13391. STRICT: 'strict',
  13392. watchFns: function() {
  13393. var result = [];
  13394. var fns = this.state.inputs;
  13395. var self = this;
  13396. forEach(fns, function(name) {
  13397. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  13398. });
  13399. if (fns.length) {
  13400. result.push('fn.inputs=[' + fns.join(',') + '];');
  13401. }
  13402. return result.join('');
  13403. },
  13404. generateFunction: function(name, params) {
  13405. return 'function(' + params + '){' +
  13406. this.varsPrefix(name) +
  13407. this.body(name) +
  13408. '};';
  13409. },
  13410. filterPrefix: function() {
  13411. var parts = [];
  13412. var self = this;
  13413. forEach(this.state.filters, function(id, filter) {
  13414. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  13415. });
  13416. if (parts.length) return 'var ' + parts.join(',') + ';';
  13417. return '';
  13418. },
  13419. varsPrefix: function(section) {
  13420. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  13421. },
  13422. body: function(section) {
  13423. return this.state[section].body.join('');
  13424. },
  13425. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13426. var left, right, self = this, args, expression, computed;
  13427. recursionFn = recursionFn || noop;
  13428. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  13429. intoId = intoId || this.nextId();
  13430. this.if_('i',
  13431. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  13432. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  13433. );
  13434. return;
  13435. }
  13436. switch (ast.type) {
  13437. case AST.Program:
  13438. forEach(ast.body, function(expression, pos) {
  13439. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  13440. if (pos !== ast.body.length - 1) {
  13441. self.current().body.push(right, ';');
  13442. } else {
  13443. self.return_(right);
  13444. }
  13445. });
  13446. break;
  13447. case AST.Literal:
  13448. expression = this.escape(ast.value);
  13449. this.assign(intoId, expression);
  13450. recursionFn(expression);
  13451. break;
  13452. case AST.UnaryExpression:
  13453. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  13454. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  13455. this.assign(intoId, expression);
  13456. recursionFn(expression);
  13457. break;
  13458. case AST.BinaryExpression:
  13459. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  13460. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  13461. if (ast.operator === '+') {
  13462. expression = this.plus(left, right);
  13463. } else if (ast.operator === '-') {
  13464. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  13465. } else {
  13466. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  13467. }
  13468. this.assign(intoId, expression);
  13469. recursionFn(expression);
  13470. break;
  13471. case AST.LogicalExpression:
  13472. intoId = intoId || this.nextId();
  13473. self.recurse(ast.left, intoId);
  13474. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  13475. recursionFn(intoId);
  13476. break;
  13477. case AST.ConditionalExpression:
  13478. intoId = intoId || this.nextId();
  13479. self.recurse(ast.test, intoId);
  13480. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  13481. recursionFn(intoId);
  13482. break;
  13483. case AST.Identifier:
  13484. intoId = intoId || this.nextId();
  13485. if (nameId) {
  13486. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  13487. nameId.computed = false;
  13488. nameId.name = ast.name;
  13489. }
  13490. ensureSafeMemberName(ast.name);
  13491. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  13492. function() {
  13493. self.if_(self.stage === 'inputs' || 's', function() {
  13494. if (create && create !== 1) {
  13495. self.if_(
  13496. self.not(self.nonComputedMember('s', ast.name)),
  13497. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  13498. }
  13499. self.assign(intoId, self.nonComputedMember('s', ast.name));
  13500. });
  13501. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  13502. );
  13503. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  13504. self.addEnsureSafeObject(intoId);
  13505. }
  13506. recursionFn(intoId);
  13507. break;
  13508. case AST.MemberExpression:
  13509. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  13510. intoId = intoId || this.nextId();
  13511. self.recurse(ast.object, left, undefined, function() {
  13512. self.if_(self.notNull(left), function() {
  13513. if (create && create !== 1) {
  13514. self.addEnsureSafeAssignContext(left);
  13515. }
  13516. if (ast.computed) {
  13517. right = self.nextId();
  13518. self.recurse(ast.property, right);
  13519. self.getStringValue(right);
  13520. self.addEnsureSafeMemberName(right);
  13521. if (create && create !== 1) {
  13522. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  13523. }
  13524. expression = self.ensureSafeObject(self.computedMember(left, right));
  13525. self.assign(intoId, expression);
  13526. if (nameId) {
  13527. nameId.computed = true;
  13528. nameId.name = right;
  13529. }
  13530. } else {
  13531. ensureSafeMemberName(ast.property.name);
  13532. if (create && create !== 1) {
  13533. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  13534. }
  13535. expression = self.nonComputedMember(left, ast.property.name);
  13536. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  13537. expression = self.ensureSafeObject(expression);
  13538. }
  13539. self.assign(intoId, expression);
  13540. if (nameId) {
  13541. nameId.computed = false;
  13542. nameId.name = ast.property.name;
  13543. }
  13544. }
  13545. }, function() {
  13546. self.assign(intoId, 'undefined');
  13547. });
  13548. recursionFn(intoId);
  13549. }, !!create);
  13550. break;
  13551. case AST.CallExpression:
  13552. intoId = intoId || this.nextId();
  13553. if (ast.filter) {
  13554. right = self.filter(ast.callee.name);
  13555. args = [];
  13556. forEach(ast.arguments, function(expr) {
  13557. var argument = self.nextId();
  13558. self.recurse(expr, argument);
  13559. args.push(argument);
  13560. });
  13561. expression = right + '(' + args.join(',') + ')';
  13562. self.assign(intoId, expression);
  13563. recursionFn(intoId);
  13564. } else {
  13565. right = self.nextId();
  13566. left = {};
  13567. args = [];
  13568. self.recurse(ast.callee, right, left, function() {
  13569. self.if_(self.notNull(right), function() {
  13570. self.addEnsureSafeFunction(right);
  13571. forEach(ast.arguments, function(expr) {
  13572. self.recurse(expr, self.nextId(), undefined, function(argument) {
  13573. args.push(self.ensureSafeObject(argument));
  13574. });
  13575. });
  13576. if (left.name) {
  13577. if (!self.state.expensiveChecks) {
  13578. self.addEnsureSafeObject(left.context);
  13579. }
  13580. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  13581. } else {
  13582. expression = right + '(' + args.join(',') + ')';
  13583. }
  13584. expression = self.ensureSafeObject(expression);
  13585. self.assign(intoId, expression);
  13586. }, function() {
  13587. self.assign(intoId, 'undefined');
  13588. });
  13589. recursionFn(intoId);
  13590. });
  13591. }
  13592. break;
  13593. case AST.AssignmentExpression:
  13594. right = this.nextId();
  13595. left = {};
  13596. if (!isAssignable(ast.left)) {
  13597. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13598. }
  13599. this.recurse(ast.left, undefined, left, function() {
  13600. self.if_(self.notNull(left.context), function() {
  13601. self.recurse(ast.right, right);
  13602. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  13603. self.addEnsureSafeAssignContext(left.context);
  13604. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  13605. self.assign(intoId, expression);
  13606. recursionFn(intoId || expression);
  13607. });
  13608. }, 1);
  13609. break;
  13610. case AST.ArrayExpression:
  13611. args = [];
  13612. forEach(ast.elements, function(expr) {
  13613. self.recurse(expr, self.nextId(), undefined, function(argument) {
  13614. args.push(argument);
  13615. });
  13616. });
  13617. expression = '[' + args.join(',') + ']';
  13618. this.assign(intoId, expression);
  13619. recursionFn(expression);
  13620. break;
  13621. case AST.ObjectExpression:
  13622. args = [];
  13623. computed = false;
  13624. forEach(ast.properties, function(property) {
  13625. if (property.computed) {
  13626. computed = true;
  13627. }
  13628. });
  13629. if (computed) {
  13630. intoId = intoId || this.nextId();
  13631. this.assign(intoId, '{}');
  13632. forEach(ast.properties, function(property) {
  13633. if (property.computed) {
  13634. left = self.nextId();
  13635. self.recurse(property.key, left);
  13636. } else {
  13637. left = property.key.type === AST.Identifier ?
  13638. property.key.name :
  13639. ('' + property.key.value);
  13640. }
  13641. right = self.nextId();
  13642. self.recurse(property.value, right);
  13643. self.assign(self.member(intoId, left, property.computed), right);
  13644. });
  13645. } else {
  13646. forEach(ast.properties, function(property) {
  13647. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  13648. args.push(self.escape(
  13649. property.key.type === AST.Identifier ? property.key.name :
  13650. ('' + property.key.value)) +
  13651. ':' + expr);
  13652. });
  13653. });
  13654. expression = '{' + args.join(',') + '}';
  13655. this.assign(intoId, expression);
  13656. }
  13657. recursionFn(intoId || expression);
  13658. break;
  13659. case AST.ThisExpression:
  13660. this.assign(intoId, 's');
  13661. recursionFn('s');
  13662. break;
  13663. case AST.LocalsExpression:
  13664. this.assign(intoId, 'l');
  13665. recursionFn('l');
  13666. break;
  13667. case AST.NGValueParameter:
  13668. this.assign(intoId, 'v');
  13669. recursionFn('v');
  13670. break;
  13671. }
  13672. },
  13673. getHasOwnProperty: function(element, property) {
  13674. var key = element + '.' + property;
  13675. var own = this.current().own;
  13676. if (!own.hasOwnProperty(key)) {
  13677. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  13678. }
  13679. return own[key];
  13680. },
  13681. assign: function(id, value) {
  13682. if (!id) return;
  13683. this.current().body.push(id, '=', value, ';');
  13684. return id;
  13685. },
  13686. filter: function(filterName) {
  13687. if (!this.state.filters.hasOwnProperty(filterName)) {
  13688. this.state.filters[filterName] = this.nextId(true);
  13689. }
  13690. return this.state.filters[filterName];
  13691. },
  13692. ifDefined: function(id, defaultValue) {
  13693. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  13694. },
  13695. plus: function(left, right) {
  13696. return 'plus(' + left + ',' + right + ')';
  13697. },
  13698. return_: function(id) {
  13699. this.current().body.push('return ', id, ';');
  13700. },
  13701. if_: function(test, alternate, consequent) {
  13702. if (test === true) {
  13703. alternate();
  13704. } else {
  13705. var body = this.current().body;
  13706. body.push('if(', test, '){');
  13707. alternate();
  13708. body.push('}');
  13709. if (consequent) {
  13710. body.push('else{');
  13711. consequent();
  13712. body.push('}');
  13713. }
  13714. }
  13715. },
  13716. not: function(expression) {
  13717. return '!(' + expression + ')';
  13718. },
  13719. notNull: function(expression) {
  13720. return expression + '!=null';
  13721. },
  13722. nonComputedMember: function(left, right) {
  13723. var SAFE_IDENTIFIER = /[$_a-zA-Z][$_a-zA-Z0-9]*/;
  13724. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  13725. if (SAFE_IDENTIFIER.test(right)) {
  13726. return left + '.' + right;
  13727. } else {
  13728. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  13729. }
  13730. },
  13731. computedMember: function(left, right) {
  13732. return left + '[' + right + ']';
  13733. },
  13734. member: function(left, right, computed) {
  13735. if (computed) return this.computedMember(left, right);
  13736. return this.nonComputedMember(left, right);
  13737. },
  13738. addEnsureSafeObject: function(item) {
  13739. this.current().body.push(this.ensureSafeObject(item), ';');
  13740. },
  13741. addEnsureSafeMemberName: function(item) {
  13742. this.current().body.push(this.ensureSafeMemberName(item), ';');
  13743. },
  13744. addEnsureSafeFunction: function(item) {
  13745. this.current().body.push(this.ensureSafeFunction(item), ';');
  13746. },
  13747. addEnsureSafeAssignContext: function(item) {
  13748. this.current().body.push(this.ensureSafeAssignContext(item), ';');
  13749. },
  13750. ensureSafeObject: function(item) {
  13751. return 'ensureSafeObject(' + item + ',text)';
  13752. },
  13753. ensureSafeMemberName: function(item) {
  13754. return 'ensureSafeMemberName(' + item + ',text)';
  13755. },
  13756. ensureSafeFunction: function(item) {
  13757. return 'ensureSafeFunction(' + item + ',text)';
  13758. },
  13759. getStringValue: function(item) {
  13760. this.assign(item, 'getStringValue(' + item + ')');
  13761. },
  13762. ensureSafeAssignContext: function(item) {
  13763. return 'ensureSafeAssignContext(' + item + ',text)';
  13764. },
  13765. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13766. var self = this;
  13767. return function() {
  13768. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  13769. };
  13770. },
  13771. lazyAssign: function(id, value) {
  13772. var self = this;
  13773. return function() {
  13774. self.assign(id, value);
  13775. };
  13776. },
  13777. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  13778. stringEscapeFn: function(c) {
  13779. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  13780. },
  13781. escape: function(value) {
  13782. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  13783. if (isNumber(value)) return value.toString();
  13784. if (value === true) return 'true';
  13785. if (value === false) return 'false';
  13786. if (value === null) return 'null';
  13787. if (typeof value === 'undefined') return 'undefined';
  13788. throw $parseMinErr('esc', 'IMPOSSIBLE');
  13789. },
  13790. nextId: function(skip, init) {
  13791. var id = 'v' + (this.state.nextId++);
  13792. if (!skip) {
  13793. this.current().vars.push(id + (init ? '=' + init : ''));
  13794. }
  13795. return id;
  13796. },
  13797. current: function() {
  13798. return this.state[this.state.computing];
  13799. }
  13800. };
  13801. function ASTInterpreter(astBuilder, $filter) {
  13802. this.astBuilder = astBuilder;
  13803. this.$filter = $filter;
  13804. }
  13805. ASTInterpreter.prototype = {
  13806. compile: function(expression, expensiveChecks) {
  13807. var self = this;
  13808. var ast = this.astBuilder.ast(expression);
  13809. this.expression = expression;
  13810. this.expensiveChecks = expensiveChecks;
  13811. findConstantAndWatchExpressions(ast, self.$filter);
  13812. var assignable;
  13813. var assign;
  13814. if ((assignable = assignableAST(ast))) {
  13815. assign = this.recurse(assignable);
  13816. }
  13817. var toWatch = getInputs(ast.body);
  13818. var inputs;
  13819. if (toWatch) {
  13820. inputs = [];
  13821. forEach(toWatch, function(watch, key) {
  13822. var input = self.recurse(watch);
  13823. watch.input = input;
  13824. inputs.push(input);
  13825. watch.watchId = key;
  13826. });
  13827. }
  13828. var expressions = [];
  13829. forEach(ast.body, function(expression) {
  13830. expressions.push(self.recurse(expression.expression));
  13831. });
  13832. var fn = ast.body.length === 0 ? noop :
  13833. ast.body.length === 1 ? expressions[0] :
  13834. function(scope, locals) {
  13835. var lastValue;
  13836. forEach(expressions, function(exp) {
  13837. lastValue = exp(scope, locals);
  13838. });
  13839. return lastValue;
  13840. };
  13841. if (assign) {
  13842. fn.assign = function(scope, value, locals) {
  13843. return assign(scope, locals, value);
  13844. };
  13845. }
  13846. if (inputs) {
  13847. fn.inputs = inputs;
  13848. }
  13849. fn.literal = isLiteral(ast);
  13850. fn.constant = isConstant(ast);
  13851. return fn;
  13852. },
  13853. recurse: function(ast, context, create) {
  13854. var left, right, self = this, args, expression;
  13855. if (ast.input) {
  13856. return this.inputs(ast.input, ast.watchId);
  13857. }
  13858. switch (ast.type) {
  13859. case AST.Literal:
  13860. return this.value(ast.value, context);
  13861. case AST.UnaryExpression:
  13862. right = this.recurse(ast.argument);
  13863. return this['unary' + ast.operator](right, context);
  13864. case AST.BinaryExpression:
  13865. left = this.recurse(ast.left);
  13866. right = this.recurse(ast.right);
  13867. return this['binary' + ast.operator](left, right, context);
  13868. case AST.LogicalExpression:
  13869. left = this.recurse(ast.left);
  13870. right = this.recurse(ast.right);
  13871. return this['binary' + ast.operator](left, right, context);
  13872. case AST.ConditionalExpression:
  13873. return this['ternary?:'](
  13874. this.recurse(ast.test),
  13875. this.recurse(ast.alternate),
  13876. this.recurse(ast.consequent),
  13877. context
  13878. );
  13879. case AST.Identifier:
  13880. ensureSafeMemberName(ast.name, self.expression);
  13881. return self.identifier(ast.name,
  13882. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  13883. context, create, self.expression);
  13884. case AST.MemberExpression:
  13885. left = this.recurse(ast.object, false, !!create);
  13886. if (!ast.computed) {
  13887. ensureSafeMemberName(ast.property.name, self.expression);
  13888. right = ast.property.name;
  13889. }
  13890. if (ast.computed) right = this.recurse(ast.property);
  13891. return ast.computed ?
  13892. this.computedMember(left, right, context, create, self.expression) :
  13893. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  13894. case AST.CallExpression:
  13895. args = [];
  13896. forEach(ast.arguments, function(expr) {
  13897. args.push(self.recurse(expr));
  13898. });
  13899. if (ast.filter) right = this.$filter(ast.callee.name);
  13900. if (!ast.filter) right = this.recurse(ast.callee, true);
  13901. return ast.filter ?
  13902. function(scope, locals, assign, inputs) {
  13903. var values = [];
  13904. for (var i = 0; i < args.length; ++i) {
  13905. values.push(args[i](scope, locals, assign, inputs));
  13906. }
  13907. var value = right.apply(undefined, values, inputs);
  13908. return context ? {context: undefined, name: undefined, value: value} : value;
  13909. } :
  13910. function(scope, locals, assign, inputs) {
  13911. var rhs = right(scope, locals, assign, inputs);
  13912. var value;
  13913. if (rhs.value != null) {
  13914. ensureSafeObject(rhs.context, self.expression);
  13915. ensureSafeFunction(rhs.value, self.expression);
  13916. var values = [];
  13917. for (var i = 0; i < args.length; ++i) {
  13918. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  13919. }
  13920. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  13921. }
  13922. return context ? {value: value} : value;
  13923. };
  13924. case AST.AssignmentExpression:
  13925. left = this.recurse(ast.left, true, 1);
  13926. right = this.recurse(ast.right);
  13927. return function(scope, locals, assign, inputs) {
  13928. var lhs = left(scope, locals, assign, inputs);
  13929. var rhs = right(scope, locals, assign, inputs);
  13930. ensureSafeObject(lhs.value, self.expression);
  13931. ensureSafeAssignContext(lhs.context);
  13932. lhs.context[lhs.name] = rhs;
  13933. return context ? {value: rhs} : rhs;
  13934. };
  13935. case AST.ArrayExpression:
  13936. args = [];
  13937. forEach(ast.elements, function(expr) {
  13938. args.push(self.recurse(expr));
  13939. });
  13940. return function(scope, locals, assign, inputs) {
  13941. var value = [];
  13942. for (var i = 0; i < args.length; ++i) {
  13943. value.push(args[i](scope, locals, assign, inputs));
  13944. }
  13945. return context ? {value: value} : value;
  13946. };
  13947. case AST.ObjectExpression:
  13948. args = [];
  13949. forEach(ast.properties, function(property) {
  13950. if (property.computed) {
  13951. args.push({key: self.recurse(property.key),
  13952. computed: true,
  13953. value: self.recurse(property.value)
  13954. });
  13955. } else {
  13956. args.push({key: property.key.type === AST.Identifier ?
  13957. property.key.name :
  13958. ('' + property.key.value),
  13959. computed: false,
  13960. value: self.recurse(property.value)
  13961. });
  13962. }
  13963. });
  13964. return function(scope, locals, assign, inputs) {
  13965. var value = {};
  13966. for (var i = 0; i < args.length; ++i) {
  13967. if (args[i].computed) {
  13968. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  13969. } else {
  13970. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  13971. }
  13972. }
  13973. return context ? {value: value} : value;
  13974. };
  13975. case AST.ThisExpression:
  13976. return function(scope) {
  13977. return context ? {value: scope} : scope;
  13978. };
  13979. case AST.LocalsExpression:
  13980. return function(scope, locals) {
  13981. return context ? {value: locals} : locals;
  13982. };
  13983. case AST.NGValueParameter:
  13984. return function(scope, locals, assign) {
  13985. return context ? {value: assign} : assign;
  13986. };
  13987. }
  13988. },
  13989. 'unary+': function(argument, context) {
  13990. return function(scope, locals, assign, inputs) {
  13991. var arg = argument(scope, locals, assign, inputs);
  13992. if (isDefined(arg)) {
  13993. arg = +arg;
  13994. } else {
  13995. arg = 0;
  13996. }
  13997. return context ? {value: arg} : arg;
  13998. };
  13999. },
  14000. 'unary-': function(argument, context) {
  14001. return function(scope, locals, assign, inputs) {
  14002. var arg = argument(scope, locals, assign, inputs);
  14003. if (isDefined(arg)) {
  14004. arg = -arg;
  14005. } else {
  14006. arg = 0;
  14007. }
  14008. return context ? {value: arg} : arg;
  14009. };
  14010. },
  14011. 'unary!': function(argument, context) {
  14012. return function(scope, locals, assign, inputs) {
  14013. var arg = !argument(scope, locals, assign, inputs);
  14014. return context ? {value: arg} : arg;
  14015. };
  14016. },
  14017. 'binary+': function(left, right, context) {
  14018. return function(scope, locals, assign, inputs) {
  14019. var lhs = left(scope, locals, assign, inputs);
  14020. var rhs = right(scope, locals, assign, inputs);
  14021. var arg = plusFn(lhs, rhs);
  14022. return context ? {value: arg} : arg;
  14023. };
  14024. },
  14025. 'binary-': function(left, right, context) {
  14026. return function(scope, locals, assign, inputs) {
  14027. var lhs = left(scope, locals, assign, inputs);
  14028. var rhs = right(scope, locals, assign, inputs);
  14029. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  14030. return context ? {value: arg} : arg;
  14031. };
  14032. },
  14033. 'binary*': function(left, right, context) {
  14034. return function(scope, locals, assign, inputs) {
  14035. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  14036. return context ? {value: arg} : arg;
  14037. };
  14038. },
  14039. 'binary/': function(left, right, context) {
  14040. return function(scope, locals, assign, inputs) {
  14041. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  14042. return context ? {value: arg} : arg;
  14043. };
  14044. },
  14045. 'binary%': function(left, right, context) {
  14046. return function(scope, locals, assign, inputs) {
  14047. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  14048. return context ? {value: arg} : arg;
  14049. };
  14050. },
  14051. 'binary===': function(left, right, context) {
  14052. return function(scope, locals, assign, inputs) {
  14053. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  14054. return context ? {value: arg} : arg;
  14055. };
  14056. },
  14057. 'binary!==': function(left, right, context) {
  14058. return function(scope, locals, assign, inputs) {
  14059. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  14060. return context ? {value: arg} : arg;
  14061. };
  14062. },
  14063. 'binary==': function(left, right, context) {
  14064. return function(scope, locals, assign, inputs) {
  14065. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  14066. return context ? {value: arg} : arg;
  14067. };
  14068. },
  14069. 'binary!=': function(left, right, context) {
  14070. return function(scope, locals, assign, inputs) {
  14071. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  14072. return context ? {value: arg} : arg;
  14073. };
  14074. },
  14075. 'binary<': function(left, right, context) {
  14076. return function(scope, locals, assign, inputs) {
  14077. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  14078. return context ? {value: arg} : arg;
  14079. };
  14080. },
  14081. 'binary>': function(left, right, context) {
  14082. return function(scope, locals, assign, inputs) {
  14083. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  14084. return context ? {value: arg} : arg;
  14085. };
  14086. },
  14087. 'binary<=': function(left, right, context) {
  14088. return function(scope, locals, assign, inputs) {
  14089. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  14090. return context ? {value: arg} : arg;
  14091. };
  14092. },
  14093. 'binary>=': function(left, right, context) {
  14094. return function(scope, locals, assign, inputs) {
  14095. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  14096. return context ? {value: arg} : arg;
  14097. };
  14098. },
  14099. 'binary&&': function(left, right, context) {
  14100. return function(scope, locals, assign, inputs) {
  14101. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  14102. return context ? {value: arg} : arg;
  14103. };
  14104. },
  14105. 'binary||': function(left, right, context) {
  14106. return function(scope, locals, assign, inputs) {
  14107. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  14108. return context ? {value: arg} : arg;
  14109. };
  14110. },
  14111. 'ternary?:': function(test, alternate, consequent, context) {
  14112. return function(scope, locals, assign, inputs) {
  14113. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  14114. return context ? {value: arg} : arg;
  14115. };
  14116. },
  14117. value: function(value, context) {
  14118. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  14119. },
  14120. identifier: function(name, expensiveChecks, context, create, expression) {
  14121. return function(scope, locals, assign, inputs) {
  14122. var base = locals && (name in locals) ? locals : scope;
  14123. if (create && create !== 1 && base && !(base[name])) {
  14124. base[name] = {};
  14125. }
  14126. var value = base ? base[name] : undefined;
  14127. if (expensiveChecks) {
  14128. ensureSafeObject(value, expression);
  14129. }
  14130. if (context) {
  14131. return {context: base, name: name, value: value};
  14132. } else {
  14133. return value;
  14134. }
  14135. };
  14136. },
  14137. computedMember: function(left, right, context, create, expression) {
  14138. return function(scope, locals, assign, inputs) {
  14139. var lhs = left(scope, locals, assign, inputs);
  14140. var rhs;
  14141. var value;
  14142. if (lhs != null) {
  14143. rhs = right(scope, locals, assign, inputs);
  14144. rhs = getStringValue(rhs);
  14145. ensureSafeMemberName(rhs, expression);
  14146. if (create && create !== 1) {
  14147. ensureSafeAssignContext(lhs);
  14148. if (lhs && !(lhs[rhs])) {
  14149. lhs[rhs] = {};
  14150. }
  14151. }
  14152. value = lhs[rhs];
  14153. ensureSafeObject(value, expression);
  14154. }
  14155. if (context) {
  14156. return {context: lhs, name: rhs, value: value};
  14157. } else {
  14158. return value;
  14159. }
  14160. };
  14161. },
  14162. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  14163. return function(scope, locals, assign, inputs) {
  14164. var lhs = left(scope, locals, assign, inputs);
  14165. if (create && create !== 1) {
  14166. ensureSafeAssignContext(lhs);
  14167. if (lhs && !(lhs[right])) {
  14168. lhs[right] = {};
  14169. }
  14170. }
  14171. var value = lhs != null ? lhs[right] : undefined;
  14172. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  14173. ensureSafeObject(value, expression);
  14174. }
  14175. if (context) {
  14176. return {context: lhs, name: right, value: value};
  14177. } else {
  14178. return value;
  14179. }
  14180. };
  14181. },
  14182. inputs: function(input, watchId) {
  14183. return function(scope, value, locals, inputs) {
  14184. if (inputs) return inputs[watchId];
  14185. return input(scope, value, locals);
  14186. };
  14187. }
  14188. };
  14189. /**
  14190. * @constructor
  14191. */
  14192. var Parser = function(lexer, $filter, options) {
  14193. this.lexer = lexer;
  14194. this.$filter = $filter;
  14195. this.options = options;
  14196. this.ast = new AST(lexer, options);
  14197. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  14198. new ASTCompiler(this.ast, $filter);
  14199. };
  14200. Parser.prototype = {
  14201. constructor: Parser,
  14202. parse: function(text) {
  14203. return this.astCompiler.compile(text, this.options.expensiveChecks);
  14204. }
  14205. };
  14206. function isPossiblyDangerousMemberName(name) {
  14207. return name == 'constructor';
  14208. }
  14209. var objectValueOf = Object.prototype.valueOf;
  14210. function getValueOf(value) {
  14211. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  14212. }
  14213. ///////////////////////////////////
  14214. /**
  14215. * @ngdoc service
  14216. * @name $parse
  14217. * @kind function
  14218. *
  14219. * @description
  14220. *
  14221. * Converts Angular {@link guide/expression expression} into a function.
  14222. *
  14223. * ```js
  14224. * var getter = $parse('user.name');
  14225. * var setter = getter.assign;
  14226. * var context = {user:{name:'angular'}};
  14227. * var locals = {user:{name:'local'}};
  14228. *
  14229. * expect(getter(context)).toEqual('angular');
  14230. * setter(context, 'newValue');
  14231. * expect(context.user.name).toEqual('newValue');
  14232. * expect(getter(context, locals)).toEqual('local');
  14233. * ```
  14234. *
  14235. *
  14236. * @param {string} expression String expression to compile.
  14237. * @returns {function(context, locals)} a function which represents the compiled expression:
  14238. *
  14239. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14240. * are evaluated against (typically a scope object).
  14241. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14242. * `context`.
  14243. *
  14244. * The returned function also has the following properties:
  14245. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  14246. * literal.
  14247. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  14248. * constant literals.
  14249. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  14250. * set to a function to change its value on the given context.
  14251. *
  14252. */
  14253. /**
  14254. * @ngdoc provider
  14255. * @name $parseProvider
  14256. *
  14257. * @description
  14258. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  14259. * service.
  14260. */
  14261. function $ParseProvider() {
  14262. var cacheDefault = createMap();
  14263. var cacheExpensive = createMap();
  14264. var literals = {
  14265. 'true': true,
  14266. 'false': false,
  14267. 'null': null,
  14268. 'undefined': undefined
  14269. };
  14270. var identStart, identContinue;
  14271. /**
  14272. * @ngdoc method
  14273. * @name $parseProvider#addLiteral
  14274. * @description
  14275. *
  14276. * Configure $parse service to add literal values that will be present as literal at expressions.
  14277. *
  14278. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  14279. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  14280. *
  14281. **/
  14282. this.addLiteral = function(literalName, literalValue) {
  14283. literals[literalName] = literalValue;
  14284. };
  14285. /**
  14286. * @ngdoc method
  14287. * @name $parseProvider#setIdentifierFns
  14288. * @description
  14289. *
  14290. * Allows defining the set of characters that are allowed in Angular expressions. The function
  14291. * `identifierStart` will get called to know if a given character is a valid character to be the
  14292. * first character for an identifier. The function `identifierContinue` will get called to know if
  14293. * a given character is a valid character to be a follow-up identifier character. The functions
  14294. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  14295. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  14296. * mind that the `string` parameter can be two characters long depending on the character
  14297. * representation. It is expected for the function to return `true` or `false`, whether that
  14298. * character is allowed or not.
  14299. *
  14300. * Since this function will be called extensivelly, keep the implementation of these functions fast,
  14301. * as the performance of these functions have a direct impact on the expressions parsing speed.
  14302. *
  14303. * @param {function=} identifierStart The function that will decide whether the given character is
  14304. * a valid identifier start character.
  14305. * @param {function=} identifierContinue The function that will decide whether the given character is
  14306. * a valid identifier continue character.
  14307. */
  14308. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  14309. identStart = identifierStart;
  14310. identContinue = identifierContinue;
  14311. return this;
  14312. };
  14313. this.$get = ['$filter', function($filter) {
  14314. var noUnsafeEval = csp().noUnsafeEval;
  14315. var $parseOptions = {
  14316. csp: noUnsafeEval,
  14317. expensiveChecks: false,
  14318. literals: copy(literals),
  14319. isIdentifierStart: isFunction(identStart) && identStart,
  14320. isIdentifierContinue: isFunction(identContinue) && identContinue
  14321. },
  14322. $parseOptionsExpensive = {
  14323. csp: noUnsafeEval,
  14324. expensiveChecks: true,
  14325. literals: copy(literals),
  14326. isIdentifierStart: isFunction(identStart) && identStart,
  14327. isIdentifierContinue: isFunction(identContinue) && identContinue
  14328. };
  14329. var runningChecksEnabled = false;
  14330. $parse.$$runningExpensiveChecks = function() {
  14331. return runningChecksEnabled;
  14332. };
  14333. return $parse;
  14334. function $parse(exp, interceptorFn, expensiveChecks) {
  14335. var parsedExpression, oneTime, cacheKey;
  14336. expensiveChecks = expensiveChecks || runningChecksEnabled;
  14337. switch (typeof exp) {
  14338. case 'string':
  14339. exp = exp.trim();
  14340. cacheKey = exp;
  14341. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  14342. parsedExpression = cache[cacheKey];
  14343. if (!parsedExpression) {
  14344. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  14345. oneTime = true;
  14346. exp = exp.substring(2);
  14347. }
  14348. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  14349. var lexer = new Lexer(parseOptions);
  14350. var parser = new Parser(lexer, $filter, parseOptions);
  14351. parsedExpression = parser.parse(exp);
  14352. if (parsedExpression.constant) {
  14353. parsedExpression.$$watchDelegate = constantWatchDelegate;
  14354. } else if (oneTime) {
  14355. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  14356. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  14357. } else if (parsedExpression.inputs) {
  14358. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  14359. }
  14360. if (expensiveChecks) {
  14361. parsedExpression = expensiveChecksInterceptor(parsedExpression);
  14362. }
  14363. cache[cacheKey] = parsedExpression;
  14364. }
  14365. return addInterceptor(parsedExpression, interceptorFn);
  14366. case 'function':
  14367. return addInterceptor(exp, interceptorFn);
  14368. default:
  14369. return addInterceptor(noop, interceptorFn);
  14370. }
  14371. }
  14372. function expensiveChecksInterceptor(fn) {
  14373. if (!fn) return fn;
  14374. expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
  14375. expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
  14376. expensiveCheckFn.constant = fn.constant;
  14377. expensiveCheckFn.literal = fn.literal;
  14378. for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
  14379. fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
  14380. }
  14381. expensiveCheckFn.inputs = fn.inputs;
  14382. return expensiveCheckFn;
  14383. function expensiveCheckFn(scope, locals, assign, inputs) {
  14384. var expensiveCheckOldValue = runningChecksEnabled;
  14385. runningChecksEnabled = true;
  14386. try {
  14387. return fn(scope, locals, assign, inputs);
  14388. } finally {
  14389. runningChecksEnabled = expensiveCheckOldValue;
  14390. }
  14391. }
  14392. }
  14393. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  14394. if (newValue == null || oldValueOfValue == null) { // null/undefined
  14395. return newValue === oldValueOfValue;
  14396. }
  14397. if (typeof newValue === 'object') {
  14398. // attempt to convert the value to a primitive type
  14399. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  14400. // be cheaply dirty-checked
  14401. newValue = getValueOf(newValue);
  14402. if (typeof newValue === 'object') {
  14403. // objects/arrays are not supported - deep-watching them would be too expensive
  14404. return false;
  14405. }
  14406. // fall-through to the primitive equality check
  14407. }
  14408. //Primitive or NaN
  14409. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  14410. }
  14411. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14412. var inputExpressions = parsedExpression.inputs;
  14413. var lastResult;
  14414. if (inputExpressions.length === 1) {
  14415. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14416. inputExpressions = inputExpressions[0];
  14417. return scope.$watch(function expressionInputWatch(scope) {
  14418. var newInputValue = inputExpressions(scope);
  14419. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  14420. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  14421. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  14422. }
  14423. return lastResult;
  14424. }, listener, objectEquality, prettyPrintExpression);
  14425. }
  14426. var oldInputValueOfValues = [];
  14427. var oldInputValues = [];
  14428. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14429. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14430. oldInputValues[i] = null;
  14431. }
  14432. return scope.$watch(function expressionInputsWatch(scope) {
  14433. var changed = false;
  14434. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14435. var newInputValue = inputExpressions[i](scope);
  14436. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  14437. oldInputValues[i] = newInputValue;
  14438. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  14439. }
  14440. }
  14441. if (changed) {
  14442. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  14443. }
  14444. return lastResult;
  14445. }, listener, objectEquality, prettyPrintExpression);
  14446. }
  14447. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14448. var unwatch, lastValue;
  14449. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  14450. return parsedExpression(scope);
  14451. }, function oneTimeListener(value, old, scope) {
  14452. lastValue = value;
  14453. if (isFunction(listener)) {
  14454. listener.apply(this, arguments);
  14455. }
  14456. if (isDefined(value)) {
  14457. scope.$$postDigest(function() {
  14458. if (isDefined(lastValue)) {
  14459. unwatch();
  14460. }
  14461. });
  14462. }
  14463. }, objectEquality);
  14464. }
  14465. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14466. var unwatch, lastValue;
  14467. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  14468. return parsedExpression(scope);
  14469. }, function oneTimeListener(value, old, scope) {
  14470. lastValue = value;
  14471. if (isFunction(listener)) {
  14472. listener.call(this, value, old, scope);
  14473. }
  14474. if (isAllDefined(value)) {
  14475. scope.$$postDigest(function() {
  14476. if (isAllDefined(lastValue)) unwatch();
  14477. });
  14478. }
  14479. }, objectEquality);
  14480. function isAllDefined(value) {
  14481. var allDefined = true;
  14482. forEach(value, function(val) {
  14483. if (!isDefined(val)) allDefined = false;
  14484. });
  14485. return allDefined;
  14486. }
  14487. }
  14488. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14489. var unwatch;
  14490. return unwatch = scope.$watch(function constantWatch(scope) {
  14491. unwatch();
  14492. return parsedExpression(scope);
  14493. }, listener, objectEquality);
  14494. }
  14495. function addInterceptor(parsedExpression, interceptorFn) {
  14496. if (!interceptorFn) return parsedExpression;
  14497. var watchDelegate = parsedExpression.$$watchDelegate;
  14498. var useInputs = false;
  14499. var regularWatch =
  14500. watchDelegate !== oneTimeLiteralWatchDelegate &&
  14501. watchDelegate !== oneTimeWatchDelegate;
  14502. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  14503. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  14504. return interceptorFn(value, scope, locals);
  14505. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  14506. var value = parsedExpression(scope, locals, assign, inputs);
  14507. var result = interceptorFn(value, scope, locals);
  14508. // we only return the interceptor's result if the
  14509. // initial value is defined (for bind-once)
  14510. return isDefined(value) ? result : value;
  14511. };
  14512. // Propagate $$watchDelegates other then inputsWatchDelegate
  14513. if (parsedExpression.$$watchDelegate &&
  14514. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  14515. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  14516. } else if (!interceptorFn.$stateful) {
  14517. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  14518. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  14519. fn.$$watchDelegate = inputsWatchDelegate;
  14520. useInputs = !parsedExpression.inputs;
  14521. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  14522. }
  14523. return fn;
  14524. }
  14525. }];
  14526. }
  14527. /**
  14528. * @ngdoc service
  14529. * @name $q
  14530. * @requires $rootScope
  14531. *
  14532. * @description
  14533. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  14534. * when they are done processing.
  14535. *
  14536. * This is an implementation of promises/deferred objects inspired by
  14537. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  14538. *
  14539. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  14540. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  14541. *
  14542. * # $q constructor
  14543. *
  14544. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  14545. * function as the first argument. This is similar to the native Promise implementation from ES6,
  14546. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  14547. *
  14548. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  14549. * available yet.
  14550. *
  14551. * It can be used like so:
  14552. *
  14553. * ```js
  14554. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14555. * // are available in the current lexical scope (they could have been injected or passed in).
  14556. *
  14557. * function asyncGreet(name) {
  14558. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  14559. * return $q(function(resolve, reject) {
  14560. * setTimeout(function() {
  14561. * if (okToGreet(name)) {
  14562. * resolve('Hello, ' + name + '!');
  14563. * } else {
  14564. * reject('Greeting ' + name + ' is not allowed.');
  14565. * }
  14566. * }, 1000);
  14567. * });
  14568. * }
  14569. *
  14570. * var promise = asyncGreet('Robin Hood');
  14571. * promise.then(function(greeting) {
  14572. * alert('Success: ' + greeting);
  14573. * }, function(reason) {
  14574. * alert('Failed: ' + reason);
  14575. * });
  14576. * ```
  14577. *
  14578. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  14579. *
  14580. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  14581. *
  14582. * However, the more traditional CommonJS-style usage is still available, and documented below.
  14583. *
  14584. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  14585. * interface for interacting with an object that represents the result of an action that is
  14586. * performed asynchronously, and may or may not be finished at any given point in time.
  14587. *
  14588. * From the perspective of dealing with error handling, deferred and promise APIs are to
  14589. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  14590. *
  14591. * ```js
  14592. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14593. * // are available in the current lexical scope (they could have been injected or passed in).
  14594. *
  14595. * function asyncGreet(name) {
  14596. * var deferred = $q.defer();
  14597. *
  14598. * setTimeout(function() {
  14599. * deferred.notify('About to greet ' + name + '.');
  14600. *
  14601. * if (okToGreet(name)) {
  14602. * deferred.resolve('Hello, ' + name + '!');
  14603. * } else {
  14604. * deferred.reject('Greeting ' + name + ' is not allowed.');
  14605. * }
  14606. * }, 1000);
  14607. *
  14608. * return deferred.promise;
  14609. * }
  14610. *
  14611. * var promise = asyncGreet('Robin Hood');
  14612. * promise.then(function(greeting) {
  14613. * alert('Success: ' + greeting);
  14614. * }, function(reason) {
  14615. * alert('Failed: ' + reason);
  14616. * }, function(update) {
  14617. * alert('Got notification: ' + update);
  14618. * });
  14619. * ```
  14620. *
  14621. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  14622. * comes in the way of guarantees that promise and deferred APIs make, see
  14623. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  14624. *
  14625. * Additionally the promise api allows for composition that is very hard to do with the
  14626. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  14627. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  14628. * section on serial or parallel joining of promises.
  14629. *
  14630. * # The Deferred API
  14631. *
  14632. * A new instance of deferred is constructed by calling `$q.defer()`.
  14633. *
  14634. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  14635. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  14636. * of the task.
  14637. *
  14638. * **Methods**
  14639. *
  14640. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  14641. * constructed via `$q.reject`, the promise will be rejected instead.
  14642. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  14643. * resolving it with a rejection constructed via `$q.reject`.
  14644. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  14645. * multiple times before the promise is either resolved or rejected.
  14646. *
  14647. * **Properties**
  14648. *
  14649. * - promise – `{Promise}` – promise object associated with this deferred.
  14650. *
  14651. *
  14652. * # The Promise API
  14653. *
  14654. * A new promise instance is created when a deferred instance is created and can be retrieved by
  14655. * calling `deferred.promise`.
  14656. *
  14657. * The purpose of the promise object is to allow for interested parties to get access to the result
  14658. * of the deferred task when it completes.
  14659. *
  14660. * **Methods**
  14661. *
  14662. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  14663. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  14664. * as soon as the result is available. The callbacks are called with a single argument: the result
  14665. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  14666. * provide a progress indication, before the promise is resolved or rejected.
  14667. *
  14668. * This method *returns a new promise* which is resolved or rejected via the return value of the
  14669. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  14670. * with the value which is resolved in that promise using
  14671. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  14672. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  14673. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  14674. * arguments are optional.
  14675. *
  14676. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  14677. *
  14678. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  14679. * but to do so without modifying the final value. This is useful to release resources or do some
  14680. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  14681. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  14682. * more information.
  14683. *
  14684. * # Chaining promises
  14685. *
  14686. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  14687. * possible to create a chain of promises:
  14688. *
  14689. * ```js
  14690. * promiseB = promiseA.then(function(result) {
  14691. * return result + 1;
  14692. * });
  14693. *
  14694. * // promiseB will be resolved immediately after promiseA is resolved and its value
  14695. * // will be the result of promiseA incremented by 1
  14696. * ```
  14697. *
  14698. * It is possible to create chains of any length and since a promise can be resolved with another
  14699. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  14700. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  14701. * $http's response interceptors.
  14702. *
  14703. *
  14704. * # Differences between Kris Kowal's Q and $q
  14705. *
  14706. * There are two main differences:
  14707. *
  14708. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  14709. * mechanism in angular, which means faster propagation of resolution or rejection into your
  14710. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  14711. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  14712. * all the important functionality needed for common async tasks.
  14713. *
  14714. * # Testing
  14715. *
  14716. * ```js
  14717. * it('should simulate promise', inject(function($q, $rootScope) {
  14718. * var deferred = $q.defer();
  14719. * var promise = deferred.promise;
  14720. * var resolvedValue;
  14721. *
  14722. * promise.then(function(value) { resolvedValue = value; });
  14723. * expect(resolvedValue).toBeUndefined();
  14724. *
  14725. * // Simulate resolving of promise
  14726. * deferred.resolve(123);
  14727. * // Note that the 'then' function does not get called synchronously.
  14728. * // This is because we want the promise API to always be async, whether or not
  14729. * // it got called synchronously or asynchronously.
  14730. * expect(resolvedValue).toBeUndefined();
  14731. *
  14732. * // Propagate promise resolution to 'then' functions using $apply().
  14733. * $rootScope.$apply();
  14734. * expect(resolvedValue).toEqual(123);
  14735. * }));
  14736. * ```
  14737. *
  14738. * @param {function(function, function)} resolver Function which is responsible for resolving or
  14739. * rejecting the newly created promise. The first parameter is a function which resolves the
  14740. * promise, the second parameter is a function which rejects the promise.
  14741. *
  14742. * @returns {Promise} The newly created promise.
  14743. */
  14744. function $QProvider() {
  14745. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  14746. return qFactory(function(callback) {
  14747. $rootScope.$evalAsync(callback);
  14748. }, $exceptionHandler);
  14749. }];
  14750. }
  14751. function $$QProvider() {
  14752. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  14753. return qFactory(function(callback) {
  14754. $browser.defer(callback);
  14755. }, $exceptionHandler);
  14756. }];
  14757. }
  14758. /**
  14759. * Constructs a promise manager.
  14760. *
  14761. * @param {function(function)} nextTick Function for executing functions in the next turn.
  14762. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  14763. * debugging purposes.
  14764. * @returns {object} Promise manager.
  14765. */
  14766. function qFactory(nextTick, exceptionHandler) {
  14767. var $qMinErr = minErr('$q', TypeError);
  14768. /**
  14769. * @ngdoc method
  14770. * @name ng.$q#defer
  14771. * @kind function
  14772. *
  14773. * @description
  14774. * Creates a `Deferred` object which represents a task which will finish in the future.
  14775. *
  14776. * @returns {Deferred} Returns a new instance of deferred.
  14777. */
  14778. var defer = function() {
  14779. var d = new Deferred();
  14780. //Necessary to support unbound execution :/
  14781. d.resolve = simpleBind(d, d.resolve);
  14782. d.reject = simpleBind(d, d.reject);
  14783. d.notify = simpleBind(d, d.notify);
  14784. return d;
  14785. };
  14786. function Promise() {
  14787. this.$$state = { status: 0 };
  14788. }
  14789. extend(Promise.prototype, {
  14790. then: function(onFulfilled, onRejected, progressBack) {
  14791. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  14792. return this;
  14793. }
  14794. var result = new Deferred();
  14795. this.$$state.pending = this.$$state.pending || [];
  14796. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  14797. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  14798. return result.promise;
  14799. },
  14800. "catch": function(callback) {
  14801. return this.then(null, callback);
  14802. },
  14803. "finally": function(callback, progressBack) {
  14804. return this.then(function(value) {
  14805. return handleCallback(value, true, callback);
  14806. }, function(error) {
  14807. return handleCallback(error, false, callback);
  14808. }, progressBack);
  14809. }
  14810. });
  14811. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  14812. function simpleBind(context, fn) {
  14813. return function(value) {
  14814. fn.call(context, value);
  14815. };
  14816. }
  14817. function processQueue(state) {
  14818. var fn, deferred, pending;
  14819. pending = state.pending;
  14820. state.processScheduled = false;
  14821. state.pending = undefined;
  14822. for (var i = 0, ii = pending.length; i < ii; ++i) {
  14823. deferred = pending[i][0];
  14824. fn = pending[i][state.status];
  14825. try {
  14826. if (isFunction(fn)) {
  14827. deferred.resolve(fn(state.value));
  14828. } else if (state.status === 1) {
  14829. deferred.resolve(state.value);
  14830. } else {
  14831. deferred.reject(state.value);
  14832. }
  14833. } catch (e) {
  14834. deferred.reject(e);
  14835. exceptionHandler(e);
  14836. }
  14837. }
  14838. }
  14839. function scheduleProcessQueue(state) {
  14840. if (state.processScheduled || !state.pending) return;
  14841. state.processScheduled = true;
  14842. nextTick(function() { processQueue(state); });
  14843. }
  14844. function Deferred() {
  14845. this.promise = new Promise();
  14846. }
  14847. extend(Deferred.prototype, {
  14848. resolve: function(val) {
  14849. if (this.promise.$$state.status) return;
  14850. if (val === this.promise) {
  14851. this.$$reject($qMinErr(
  14852. 'qcycle',
  14853. "Expected promise to be resolved with value other than itself '{0}'",
  14854. val));
  14855. } else {
  14856. this.$$resolve(val);
  14857. }
  14858. },
  14859. $$resolve: function(val) {
  14860. var then;
  14861. var that = this;
  14862. var done = false;
  14863. try {
  14864. if ((isObject(val) || isFunction(val))) then = val && val.then;
  14865. if (isFunction(then)) {
  14866. this.promise.$$state.status = -1;
  14867. then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
  14868. } else {
  14869. this.promise.$$state.value = val;
  14870. this.promise.$$state.status = 1;
  14871. scheduleProcessQueue(this.promise.$$state);
  14872. }
  14873. } catch (e) {
  14874. rejectPromise(e);
  14875. exceptionHandler(e);
  14876. }
  14877. function resolvePromise(val) {
  14878. if (done) return;
  14879. done = true;
  14880. that.$$resolve(val);
  14881. }
  14882. function rejectPromise(val) {
  14883. if (done) return;
  14884. done = true;
  14885. that.$$reject(val);
  14886. }
  14887. },
  14888. reject: function(reason) {
  14889. if (this.promise.$$state.status) return;
  14890. this.$$reject(reason);
  14891. },
  14892. $$reject: function(reason) {
  14893. this.promise.$$state.value = reason;
  14894. this.promise.$$state.status = 2;
  14895. scheduleProcessQueue(this.promise.$$state);
  14896. },
  14897. notify: function(progress) {
  14898. var callbacks = this.promise.$$state.pending;
  14899. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  14900. nextTick(function() {
  14901. var callback, result;
  14902. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  14903. result = callbacks[i][0];
  14904. callback = callbacks[i][3];
  14905. try {
  14906. result.notify(isFunction(callback) ? callback(progress) : progress);
  14907. } catch (e) {
  14908. exceptionHandler(e);
  14909. }
  14910. }
  14911. });
  14912. }
  14913. }
  14914. });
  14915. /**
  14916. * @ngdoc method
  14917. * @name $q#reject
  14918. * @kind function
  14919. *
  14920. * @description
  14921. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  14922. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  14923. * a promise chain, you don't need to worry about it.
  14924. *
  14925. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  14926. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  14927. * a promise error callback and you want to forward the error to the promise derived from the
  14928. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  14929. * `reject`.
  14930. *
  14931. * ```js
  14932. * promiseB = promiseA.then(function(result) {
  14933. * // success: do something and resolve promiseB
  14934. * // with the old or a new result
  14935. * return result;
  14936. * }, function(reason) {
  14937. * // error: handle the error if possible and
  14938. * // resolve promiseB with newPromiseOrValue,
  14939. * // otherwise forward the rejection to promiseB
  14940. * if (canHandle(reason)) {
  14941. * // handle the error and recover
  14942. * return newPromiseOrValue;
  14943. * }
  14944. * return $q.reject(reason);
  14945. * });
  14946. * ```
  14947. *
  14948. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  14949. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  14950. */
  14951. var reject = function(reason) {
  14952. var result = new Deferred();
  14953. result.reject(reason);
  14954. return result.promise;
  14955. };
  14956. var makePromise = function makePromise(value, resolved) {
  14957. var result = new Deferred();
  14958. if (resolved) {
  14959. result.resolve(value);
  14960. } else {
  14961. result.reject(value);
  14962. }
  14963. return result.promise;
  14964. };
  14965. var handleCallback = function handleCallback(value, isResolved, callback) {
  14966. var callbackOutput = null;
  14967. try {
  14968. if (isFunction(callback)) callbackOutput = callback();
  14969. } catch (e) {
  14970. return makePromise(e, false);
  14971. }
  14972. if (isPromiseLike(callbackOutput)) {
  14973. return callbackOutput.then(function() {
  14974. return makePromise(value, isResolved);
  14975. }, function(error) {
  14976. return makePromise(error, false);
  14977. });
  14978. } else {
  14979. return makePromise(value, isResolved);
  14980. }
  14981. };
  14982. /**
  14983. * @ngdoc method
  14984. * @name $q#when
  14985. * @kind function
  14986. *
  14987. * @description
  14988. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  14989. * This is useful when you are dealing with an object that might or might not be a promise, or if
  14990. * the promise comes from a source that can't be trusted.
  14991. *
  14992. * @param {*} value Value or a promise
  14993. * @param {Function=} successCallback
  14994. * @param {Function=} errorCallback
  14995. * @param {Function=} progressCallback
  14996. * @returns {Promise} Returns a promise of the passed value or promise
  14997. */
  14998. var when = function(value, callback, errback, progressBack) {
  14999. var result = new Deferred();
  15000. result.resolve(value);
  15001. return result.promise.then(callback, errback, progressBack);
  15002. };
  15003. /**
  15004. * @ngdoc method
  15005. * @name $q#resolve
  15006. * @kind function
  15007. *
  15008. * @description
  15009. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  15010. *
  15011. * @param {*} value Value or a promise
  15012. * @param {Function=} successCallback
  15013. * @param {Function=} errorCallback
  15014. * @param {Function=} progressCallback
  15015. * @returns {Promise} Returns a promise of the passed value or promise
  15016. */
  15017. var resolve = when;
  15018. /**
  15019. * @ngdoc method
  15020. * @name $q#all
  15021. * @kind function
  15022. *
  15023. * @description
  15024. * Combines multiple promises into a single promise that is resolved when all of the input
  15025. * promises are resolved.
  15026. *
  15027. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15028. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  15029. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  15030. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  15031. * with the same rejection value.
  15032. */
  15033. function all(promises) {
  15034. var deferred = new Deferred(),
  15035. counter = 0,
  15036. results = isArray(promises) ? [] : {};
  15037. forEach(promises, function(promise, key) {
  15038. counter++;
  15039. when(promise).then(function(value) {
  15040. if (results.hasOwnProperty(key)) return;
  15041. results[key] = value;
  15042. if (!(--counter)) deferred.resolve(results);
  15043. }, function(reason) {
  15044. if (results.hasOwnProperty(key)) return;
  15045. deferred.reject(reason);
  15046. });
  15047. });
  15048. if (counter === 0) {
  15049. deferred.resolve(results);
  15050. }
  15051. return deferred.promise;
  15052. }
  15053. /**
  15054. * @ngdoc method
  15055. * @name $q#race
  15056. * @kind function
  15057. *
  15058. * @description
  15059. * Returns a promise that resolves or rejects as soon as one of those promises
  15060. * resolves or rejects, with the value or reason from that promise.
  15061. *
  15062. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15063. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  15064. * resolves or rejects, with the value or reason from that promise.
  15065. */
  15066. function race(promises) {
  15067. var deferred = defer();
  15068. forEach(promises, function(promise) {
  15069. when(promise).then(deferred.resolve, deferred.reject);
  15070. });
  15071. return deferred.promise;
  15072. }
  15073. var $Q = function Q(resolver) {
  15074. if (!isFunction(resolver)) {
  15075. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  15076. }
  15077. var deferred = new Deferred();
  15078. function resolveFn(value) {
  15079. deferred.resolve(value);
  15080. }
  15081. function rejectFn(reason) {
  15082. deferred.reject(reason);
  15083. }
  15084. resolver(resolveFn, rejectFn);
  15085. return deferred.promise;
  15086. };
  15087. // Let's make the instanceof operator work for promises, so that
  15088. // `new $q(fn) instanceof $q` would evaluate to true.
  15089. $Q.prototype = Promise.prototype;
  15090. $Q.defer = defer;
  15091. $Q.reject = reject;
  15092. $Q.when = when;
  15093. $Q.resolve = resolve;
  15094. $Q.all = all;
  15095. $Q.race = race;
  15096. return $Q;
  15097. }
  15098. function $$RAFProvider() { //rAF
  15099. this.$get = ['$window', '$timeout', function($window, $timeout) {
  15100. var requestAnimationFrame = $window.requestAnimationFrame ||
  15101. $window.webkitRequestAnimationFrame;
  15102. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  15103. $window.webkitCancelAnimationFrame ||
  15104. $window.webkitCancelRequestAnimationFrame;
  15105. var rafSupported = !!requestAnimationFrame;
  15106. var raf = rafSupported
  15107. ? function(fn) {
  15108. var id = requestAnimationFrame(fn);
  15109. return function() {
  15110. cancelAnimationFrame(id);
  15111. };
  15112. }
  15113. : function(fn) {
  15114. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  15115. return function() {
  15116. $timeout.cancel(timer);
  15117. };
  15118. };
  15119. raf.supported = rafSupported;
  15120. return raf;
  15121. }];
  15122. }
  15123. /**
  15124. * DESIGN NOTES
  15125. *
  15126. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  15127. *
  15128. * The typical use of scope is to watch the expressions, which most of the time return the same
  15129. * value as last time so we optimize the operation.
  15130. *
  15131. * Closures construction is expensive in terms of speed as well as memory:
  15132. * - No closures, instead use prototypical inheritance for API
  15133. * - Internal state needs to be stored on scope directly, which means that private state is
  15134. * exposed as $$____ properties
  15135. *
  15136. * Loop operations are optimized by using while(count--) { ... }
  15137. * - This means that in order to keep the same order of execution as addition we have to add
  15138. * items to the array at the beginning (unshift) instead of at the end (push)
  15139. *
  15140. * Child scopes are created and removed often
  15141. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  15142. *
  15143. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  15144. * in the same way as watch. Watch requires return of the initialization function which is expensive
  15145. * to construct.
  15146. */
  15147. /**
  15148. * @ngdoc provider
  15149. * @name $rootScopeProvider
  15150. * @description
  15151. *
  15152. * Provider for the $rootScope service.
  15153. */
  15154. /**
  15155. * @ngdoc method
  15156. * @name $rootScopeProvider#digestTtl
  15157. * @description
  15158. *
  15159. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  15160. * assuming that the model is unstable.
  15161. *
  15162. * The current default is 10 iterations.
  15163. *
  15164. * In complex applications it's possible that the dependencies between `$watch`s will result in
  15165. * several digest iterations. However if an application needs more than the default 10 digest
  15166. * iterations for its model to stabilize then you should investigate what is causing the model to
  15167. * continuously change during the digest.
  15168. *
  15169. * Increasing the TTL could have performance implications, so you should not change it without
  15170. * proper justification.
  15171. *
  15172. * @param {number} limit The number of digest iterations.
  15173. */
  15174. /**
  15175. * @ngdoc service
  15176. * @name $rootScope
  15177. * @description
  15178. *
  15179. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  15180. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  15181. * between the model and the view, via a mechanism for watching the model for changes.
  15182. * They also provide event emission/broadcast and subscription facility. See the
  15183. * {@link guide/scope developer guide on scopes}.
  15184. */
  15185. function $RootScopeProvider() {
  15186. var TTL = 10;
  15187. var $rootScopeMinErr = minErr('$rootScope');
  15188. var lastDirtyWatch = null;
  15189. var applyAsyncId = null;
  15190. this.digestTtl = function(value) {
  15191. if (arguments.length) {
  15192. TTL = value;
  15193. }
  15194. return TTL;
  15195. };
  15196. function createChildScopeClass(parent) {
  15197. function ChildScope() {
  15198. this.$$watchers = this.$$nextSibling =
  15199. this.$$childHead = this.$$childTail = null;
  15200. this.$$listeners = {};
  15201. this.$$listenerCount = {};
  15202. this.$$watchersCount = 0;
  15203. this.$id = nextUid();
  15204. this.$$ChildScope = null;
  15205. }
  15206. ChildScope.prototype = parent;
  15207. return ChildScope;
  15208. }
  15209. this.$get = ['$exceptionHandler', '$parse', '$browser',
  15210. function($exceptionHandler, $parse, $browser) {
  15211. function destroyChildScope($event) {
  15212. $event.currentScope.$$destroyed = true;
  15213. }
  15214. function cleanUpScope($scope) {
  15215. if (msie === 9) {
  15216. // There is a memory leak in IE9 if all child scopes are not disconnected
  15217. // completely when a scope is destroyed. So this code will recurse up through
  15218. // all this scopes children
  15219. //
  15220. // See issue https://github.com/angular/angular.js/issues/10706
  15221. $scope.$$childHead && cleanUpScope($scope.$$childHead);
  15222. $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
  15223. }
  15224. // The code below works around IE9 and V8's memory leaks
  15225. //
  15226. // See:
  15227. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  15228. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  15229. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  15230. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  15231. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  15232. }
  15233. /**
  15234. * @ngdoc type
  15235. * @name $rootScope.Scope
  15236. *
  15237. * @description
  15238. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  15239. * {@link auto.$injector $injector}. Child scopes are created using the
  15240. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  15241. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  15242. * an in-depth introduction and usage examples.
  15243. *
  15244. *
  15245. * # Inheritance
  15246. * A scope can inherit from a parent scope, as in this example:
  15247. * ```js
  15248. var parent = $rootScope;
  15249. var child = parent.$new();
  15250. parent.salutation = "Hello";
  15251. expect(child.salutation).toEqual('Hello');
  15252. child.salutation = "Welcome";
  15253. expect(child.salutation).toEqual('Welcome');
  15254. expect(parent.salutation).toEqual('Hello');
  15255. * ```
  15256. *
  15257. * When interacting with `Scope` in tests, additional helper methods are available on the
  15258. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  15259. * details.
  15260. *
  15261. *
  15262. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  15263. * provided for the current scope. Defaults to {@link ng}.
  15264. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  15265. * append/override services provided by `providers`. This is handy
  15266. * when unit-testing and having the need to override a default
  15267. * service.
  15268. * @returns {Object} Newly created scope.
  15269. *
  15270. */
  15271. function Scope() {
  15272. this.$id = nextUid();
  15273. this.$$phase = this.$parent = this.$$watchers =
  15274. this.$$nextSibling = this.$$prevSibling =
  15275. this.$$childHead = this.$$childTail = null;
  15276. this.$root = this;
  15277. this.$$destroyed = false;
  15278. this.$$listeners = {};
  15279. this.$$listenerCount = {};
  15280. this.$$watchersCount = 0;
  15281. this.$$isolateBindings = null;
  15282. }
  15283. /**
  15284. * @ngdoc property
  15285. * @name $rootScope.Scope#$id
  15286. *
  15287. * @description
  15288. * Unique scope ID (monotonically increasing) useful for debugging.
  15289. */
  15290. /**
  15291. * @ngdoc property
  15292. * @name $rootScope.Scope#$parent
  15293. *
  15294. * @description
  15295. * Reference to the parent scope.
  15296. */
  15297. /**
  15298. * @ngdoc property
  15299. * @name $rootScope.Scope#$root
  15300. *
  15301. * @description
  15302. * Reference to the root scope.
  15303. */
  15304. Scope.prototype = {
  15305. constructor: Scope,
  15306. /**
  15307. * @ngdoc method
  15308. * @name $rootScope.Scope#$new
  15309. * @kind function
  15310. *
  15311. * @description
  15312. * Creates a new child {@link ng.$rootScope.Scope scope}.
  15313. *
  15314. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  15315. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  15316. *
  15317. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  15318. * desired for the scope and its child scopes to be permanently detached from the parent and
  15319. * thus stop participating in model change detection and listener notification by invoking.
  15320. *
  15321. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  15322. * parent scope. The scope is isolated, as it can not see parent scope properties.
  15323. * When creating widgets, it is useful for the widget to not accidentally read parent
  15324. * state.
  15325. *
  15326. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  15327. * of the newly created scope. Defaults to `this` scope if not provided.
  15328. * This is used when creating a transclude scope to correctly place it
  15329. * in the scope hierarchy while maintaining the correct prototypical
  15330. * inheritance.
  15331. *
  15332. * @returns {Object} The newly created child scope.
  15333. *
  15334. */
  15335. $new: function(isolate, parent) {
  15336. var child;
  15337. parent = parent || this;
  15338. if (isolate) {
  15339. child = new Scope();
  15340. child.$root = this.$root;
  15341. } else {
  15342. // Only create a child scope class if somebody asks for one,
  15343. // but cache it to allow the VM to optimize lookups.
  15344. if (!this.$$ChildScope) {
  15345. this.$$ChildScope = createChildScopeClass(this);
  15346. }
  15347. child = new this.$$ChildScope();
  15348. }
  15349. child.$parent = parent;
  15350. child.$$prevSibling = parent.$$childTail;
  15351. if (parent.$$childHead) {
  15352. parent.$$childTail.$$nextSibling = child;
  15353. parent.$$childTail = child;
  15354. } else {
  15355. parent.$$childHead = parent.$$childTail = child;
  15356. }
  15357. // When the new scope is not isolated or we inherit from `this`, and
  15358. // the parent scope is destroyed, the property `$$destroyed` is inherited
  15359. // prototypically. In all other cases, this property needs to be set
  15360. // when the parent scope is destroyed.
  15361. // The listener needs to be added after the parent is set
  15362. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  15363. return child;
  15364. },
  15365. /**
  15366. * @ngdoc method
  15367. * @name $rootScope.Scope#$watch
  15368. * @kind function
  15369. *
  15370. * @description
  15371. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  15372. *
  15373. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  15374. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  15375. * its value when executed multiple times with the same input because it may be executed multiple
  15376. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  15377. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
  15378. * - The `listener` is called only when the value from the current `watchExpression` and the
  15379. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  15380. * see below). Inequality is determined according to reference inequality,
  15381. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  15382. * via the `!==` Javascript operator, unless `objectEquality == true`
  15383. * (see next point)
  15384. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  15385. * according to the {@link angular.equals} function. To save the value of the object for
  15386. * later comparison, the {@link angular.copy} function is used. This therefore means that
  15387. * watching complex objects will have adverse memory and performance implications.
  15388. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  15389. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  15390. * iteration limit is 10 to prevent an infinite loop deadlock.
  15391. *
  15392. *
  15393. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  15394. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  15395. * multiple calls to your `watchExpression` because it will execute multiple times in a
  15396. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  15397. *
  15398. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  15399. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  15400. * watcher. In rare cases, this is undesirable because the listener is called when the result
  15401. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  15402. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  15403. * listener was called due to initialization.
  15404. *
  15405. *
  15406. *
  15407. * # Example
  15408. * ```js
  15409. // let's assume that scope was dependency injected as the $rootScope
  15410. var scope = $rootScope;
  15411. scope.name = 'misko';
  15412. scope.counter = 0;
  15413. expect(scope.counter).toEqual(0);
  15414. scope.$watch('name', function(newValue, oldValue) {
  15415. scope.counter = scope.counter + 1;
  15416. });
  15417. expect(scope.counter).toEqual(0);
  15418. scope.$digest();
  15419. // the listener is always called during the first $digest loop after it was registered
  15420. expect(scope.counter).toEqual(1);
  15421. scope.$digest();
  15422. // but now it will not be called unless the value changes
  15423. expect(scope.counter).toEqual(1);
  15424. scope.name = 'adam';
  15425. scope.$digest();
  15426. expect(scope.counter).toEqual(2);
  15427. // Using a function as a watchExpression
  15428. var food;
  15429. scope.foodCounter = 0;
  15430. expect(scope.foodCounter).toEqual(0);
  15431. scope.$watch(
  15432. // This function returns the value being watched. It is called for each turn of the $digest loop
  15433. function() { return food; },
  15434. // This is the change listener, called when the value returned from the above function changes
  15435. function(newValue, oldValue) {
  15436. if ( newValue !== oldValue ) {
  15437. // Only increment the counter if the value changed
  15438. scope.foodCounter = scope.foodCounter + 1;
  15439. }
  15440. }
  15441. );
  15442. // No digest has been run so the counter will be zero
  15443. expect(scope.foodCounter).toEqual(0);
  15444. // Run the digest but since food has not changed count will still be zero
  15445. scope.$digest();
  15446. expect(scope.foodCounter).toEqual(0);
  15447. // Update food and run digest. Now the counter will increment
  15448. food = 'cheeseburger';
  15449. scope.$digest();
  15450. expect(scope.foodCounter).toEqual(1);
  15451. * ```
  15452. *
  15453. *
  15454. *
  15455. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  15456. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  15457. * a call to the `listener`.
  15458. *
  15459. * - `string`: Evaluated as {@link guide/expression expression}
  15460. * - `function(scope)`: called with current `scope` as a parameter.
  15461. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  15462. * of `watchExpression` changes.
  15463. *
  15464. * - `newVal` contains the current value of the `watchExpression`
  15465. * - `oldVal` contains the previous value of the `watchExpression`
  15466. * - `scope` refers to the current scope
  15467. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  15468. * comparing for reference equality.
  15469. * @returns {function()} Returns a deregistration function for this listener.
  15470. */
  15471. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  15472. var get = $parse(watchExp);
  15473. if (get.$$watchDelegate) {
  15474. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  15475. }
  15476. var scope = this,
  15477. array = scope.$$watchers,
  15478. watcher = {
  15479. fn: listener,
  15480. last: initWatchVal,
  15481. get: get,
  15482. exp: prettyPrintExpression || watchExp,
  15483. eq: !!objectEquality
  15484. };
  15485. lastDirtyWatch = null;
  15486. if (!isFunction(listener)) {
  15487. watcher.fn = noop;
  15488. }
  15489. if (!array) {
  15490. array = scope.$$watchers = [];
  15491. }
  15492. // we use unshift since we use a while loop in $digest for speed.
  15493. // the while loop reads in reverse order.
  15494. array.unshift(watcher);
  15495. incrementWatchersCount(this, 1);
  15496. return function deregisterWatch() {
  15497. if (arrayRemove(array, watcher) >= 0) {
  15498. incrementWatchersCount(scope, -1);
  15499. }
  15500. lastDirtyWatch = null;
  15501. };
  15502. },
  15503. /**
  15504. * @ngdoc method
  15505. * @name $rootScope.Scope#$watchGroup
  15506. * @kind function
  15507. *
  15508. * @description
  15509. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  15510. * If any one expression in the collection changes the `listener` is executed.
  15511. *
  15512. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  15513. * call to $digest() to see if any items changes.
  15514. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  15515. *
  15516. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  15517. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  15518. *
  15519. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  15520. * expression in `watchExpressions` changes
  15521. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  15522. * those of `watchExpression`
  15523. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  15524. * those of `watchExpression`
  15525. * The `scope` refers to the current scope.
  15526. * @returns {function()} Returns a de-registration function for all listeners.
  15527. */
  15528. $watchGroup: function(watchExpressions, listener) {
  15529. var oldValues = new Array(watchExpressions.length);
  15530. var newValues = new Array(watchExpressions.length);
  15531. var deregisterFns = [];
  15532. var self = this;
  15533. var changeReactionScheduled = false;
  15534. var firstRun = true;
  15535. if (!watchExpressions.length) {
  15536. // No expressions means we call the listener ASAP
  15537. var shouldCall = true;
  15538. self.$evalAsync(function() {
  15539. if (shouldCall) listener(newValues, newValues, self);
  15540. });
  15541. return function deregisterWatchGroup() {
  15542. shouldCall = false;
  15543. };
  15544. }
  15545. if (watchExpressions.length === 1) {
  15546. // Special case size of one
  15547. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  15548. newValues[0] = value;
  15549. oldValues[0] = oldValue;
  15550. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  15551. });
  15552. }
  15553. forEach(watchExpressions, function(expr, i) {
  15554. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  15555. newValues[i] = value;
  15556. oldValues[i] = oldValue;
  15557. if (!changeReactionScheduled) {
  15558. changeReactionScheduled = true;
  15559. self.$evalAsync(watchGroupAction);
  15560. }
  15561. });
  15562. deregisterFns.push(unwatchFn);
  15563. });
  15564. function watchGroupAction() {
  15565. changeReactionScheduled = false;
  15566. if (firstRun) {
  15567. firstRun = false;
  15568. listener(newValues, newValues, self);
  15569. } else {
  15570. listener(newValues, oldValues, self);
  15571. }
  15572. }
  15573. return function deregisterWatchGroup() {
  15574. while (deregisterFns.length) {
  15575. deregisterFns.shift()();
  15576. }
  15577. };
  15578. },
  15579. /**
  15580. * @ngdoc method
  15581. * @name $rootScope.Scope#$watchCollection
  15582. * @kind function
  15583. *
  15584. * @description
  15585. * Shallow watches the properties of an object and fires whenever any of the properties change
  15586. * (for arrays, this implies watching the array items; for object maps, this implies watching
  15587. * the properties). If a change is detected, the `listener` callback is fired.
  15588. *
  15589. * - The `obj` collection is observed via standard $watch operation and is examined on every
  15590. * call to $digest() to see if any items have been added, removed, or moved.
  15591. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  15592. * adding, removing, and moving items belonging to an object or array.
  15593. *
  15594. *
  15595. * # Example
  15596. * ```js
  15597. $scope.names = ['igor', 'matias', 'misko', 'james'];
  15598. $scope.dataCount = 4;
  15599. $scope.$watchCollection('names', function(newNames, oldNames) {
  15600. $scope.dataCount = newNames.length;
  15601. });
  15602. expect($scope.dataCount).toEqual(4);
  15603. $scope.$digest();
  15604. //still at 4 ... no changes
  15605. expect($scope.dataCount).toEqual(4);
  15606. $scope.names.pop();
  15607. $scope.$digest();
  15608. //now there's been a change
  15609. expect($scope.dataCount).toEqual(3);
  15610. * ```
  15611. *
  15612. *
  15613. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  15614. * expression value should evaluate to an object or an array which is observed on each
  15615. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  15616. * collection will trigger a call to the `listener`.
  15617. *
  15618. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  15619. * when a change is detected.
  15620. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  15621. * - The `oldCollection` object is a copy of the former collection data.
  15622. * Due to performance considerations, the`oldCollection` value is computed only if the
  15623. * `listener` function declares two or more arguments.
  15624. * - The `scope` argument refers to the current scope.
  15625. *
  15626. * @returns {function()} Returns a de-registration function for this listener. When the
  15627. * de-registration function is executed, the internal watch operation is terminated.
  15628. */
  15629. $watchCollection: function(obj, listener) {
  15630. $watchCollectionInterceptor.$stateful = true;
  15631. var self = this;
  15632. // the current value, updated on each dirty-check run
  15633. var newValue;
  15634. // a shallow copy of the newValue from the last dirty-check run,
  15635. // updated to match newValue during dirty-check run
  15636. var oldValue;
  15637. // a shallow copy of the newValue from when the last change happened
  15638. var veryOldValue;
  15639. // only track veryOldValue if the listener is asking for it
  15640. var trackVeryOldValue = (listener.length > 1);
  15641. var changeDetected = 0;
  15642. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  15643. var internalArray = [];
  15644. var internalObject = {};
  15645. var initRun = true;
  15646. var oldLength = 0;
  15647. function $watchCollectionInterceptor(_value) {
  15648. newValue = _value;
  15649. var newLength, key, bothNaN, newItem, oldItem;
  15650. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  15651. if (isUndefined(newValue)) return;
  15652. if (!isObject(newValue)) { // if primitive
  15653. if (oldValue !== newValue) {
  15654. oldValue = newValue;
  15655. changeDetected++;
  15656. }
  15657. } else if (isArrayLike(newValue)) {
  15658. if (oldValue !== internalArray) {
  15659. // we are transitioning from something which was not an array into array.
  15660. oldValue = internalArray;
  15661. oldLength = oldValue.length = 0;
  15662. changeDetected++;
  15663. }
  15664. newLength = newValue.length;
  15665. if (oldLength !== newLength) {
  15666. // if lengths do not match we need to trigger change notification
  15667. changeDetected++;
  15668. oldValue.length = oldLength = newLength;
  15669. }
  15670. // copy the items to oldValue and look for changes.
  15671. for (var i = 0; i < newLength; i++) {
  15672. oldItem = oldValue[i];
  15673. newItem = newValue[i];
  15674. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  15675. if (!bothNaN && (oldItem !== newItem)) {
  15676. changeDetected++;
  15677. oldValue[i] = newItem;
  15678. }
  15679. }
  15680. } else {
  15681. if (oldValue !== internalObject) {
  15682. // we are transitioning from something which was not an object into object.
  15683. oldValue = internalObject = {};
  15684. oldLength = 0;
  15685. changeDetected++;
  15686. }
  15687. // copy the items to oldValue and look for changes.
  15688. newLength = 0;
  15689. for (key in newValue) {
  15690. if (hasOwnProperty.call(newValue, key)) {
  15691. newLength++;
  15692. newItem = newValue[key];
  15693. oldItem = oldValue[key];
  15694. if (key in oldValue) {
  15695. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  15696. if (!bothNaN && (oldItem !== newItem)) {
  15697. changeDetected++;
  15698. oldValue[key] = newItem;
  15699. }
  15700. } else {
  15701. oldLength++;
  15702. oldValue[key] = newItem;
  15703. changeDetected++;
  15704. }
  15705. }
  15706. }
  15707. if (oldLength > newLength) {
  15708. // we used to have more keys, need to find them and destroy them.
  15709. changeDetected++;
  15710. for (key in oldValue) {
  15711. if (!hasOwnProperty.call(newValue, key)) {
  15712. oldLength--;
  15713. delete oldValue[key];
  15714. }
  15715. }
  15716. }
  15717. }
  15718. return changeDetected;
  15719. }
  15720. function $watchCollectionAction() {
  15721. if (initRun) {
  15722. initRun = false;
  15723. listener(newValue, newValue, self);
  15724. } else {
  15725. listener(newValue, veryOldValue, self);
  15726. }
  15727. // make a copy for the next time a collection is changed
  15728. if (trackVeryOldValue) {
  15729. if (!isObject(newValue)) {
  15730. //primitive
  15731. veryOldValue = newValue;
  15732. } else if (isArrayLike(newValue)) {
  15733. veryOldValue = new Array(newValue.length);
  15734. for (var i = 0; i < newValue.length; i++) {
  15735. veryOldValue[i] = newValue[i];
  15736. }
  15737. } else { // if object
  15738. veryOldValue = {};
  15739. for (var key in newValue) {
  15740. if (hasOwnProperty.call(newValue, key)) {
  15741. veryOldValue[key] = newValue[key];
  15742. }
  15743. }
  15744. }
  15745. }
  15746. }
  15747. return this.$watch(changeDetector, $watchCollectionAction);
  15748. },
  15749. /**
  15750. * @ngdoc method
  15751. * @name $rootScope.Scope#$digest
  15752. * @kind function
  15753. *
  15754. * @description
  15755. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  15756. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  15757. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  15758. * until no more listeners are firing. This means that it is possible to get into an infinite
  15759. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  15760. * iterations exceeds 10.
  15761. *
  15762. * Usually, you don't call `$digest()` directly in
  15763. * {@link ng.directive:ngController controllers} or in
  15764. * {@link ng.$compileProvider#directive directives}.
  15765. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  15766. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  15767. *
  15768. * If you want to be notified whenever `$digest()` is called,
  15769. * you can register a `watchExpression` function with
  15770. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  15771. *
  15772. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  15773. *
  15774. * # Example
  15775. * ```js
  15776. var scope = ...;
  15777. scope.name = 'misko';
  15778. scope.counter = 0;
  15779. expect(scope.counter).toEqual(0);
  15780. scope.$watch('name', function(newValue, oldValue) {
  15781. scope.counter = scope.counter + 1;
  15782. });
  15783. expect(scope.counter).toEqual(0);
  15784. scope.$digest();
  15785. // the listener is always called during the first $digest loop after it was registered
  15786. expect(scope.counter).toEqual(1);
  15787. scope.$digest();
  15788. // but now it will not be called unless the value changes
  15789. expect(scope.counter).toEqual(1);
  15790. scope.name = 'adam';
  15791. scope.$digest();
  15792. expect(scope.counter).toEqual(2);
  15793. * ```
  15794. *
  15795. */
  15796. $digest: function() {
  15797. var watch, value, last, fn, get,
  15798. watchers,
  15799. length,
  15800. dirty, ttl = TTL,
  15801. next, current, target = this,
  15802. watchLog = [],
  15803. logIdx, asyncTask;
  15804. beginPhase('$digest');
  15805. // Check for changes to browser url that happened in sync before the call to $digest
  15806. $browser.$$checkUrlChange();
  15807. if (this === $rootScope && applyAsyncId !== null) {
  15808. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  15809. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  15810. $browser.defer.cancel(applyAsyncId);
  15811. flushApplyAsync();
  15812. }
  15813. lastDirtyWatch = null;
  15814. do { // "while dirty" loop
  15815. dirty = false;
  15816. current = target;
  15817. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  15818. // be reentered recursively. Calling $digest from a function passed to $applyAsync would
  15819. // lead to a '$digest already in progress' error.
  15820. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  15821. try {
  15822. asyncTask = asyncQueue[asyncQueuePosition];
  15823. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  15824. } catch (e) {
  15825. $exceptionHandler(e);
  15826. }
  15827. lastDirtyWatch = null;
  15828. }
  15829. asyncQueue.length = 0;
  15830. traverseScopesLoop:
  15831. do { // "traverse the scopes" loop
  15832. if ((watchers = current.$$watchers)) {
  15833. // process our watches
  15834. length = watchers.length;
  15835. while (length--) {
  15836. try {
  15837. watch = watchers[length];
  15838. // Most common watches are on primitives, in which case we can short
  15839. // circuit it with === operator, only when === fails do we use .equals
  15840. if (watch) {
  15841. get = watch.get;
  15842. if ((value = get(current)) !== (last = watch.last) &&
  15843. !(watch.eq
  15844. ? equals(value, last)
  15845. : (typeof value === 'number' && typeof last === 'number'
  15846. && isNaN(value) && isNaN(last)))) {
  15847. dirty = true;
  15848. lastDirtyWatch = watch;
  15849. watch.last = watch.eq ? copy(value, null) : value;
  15850. fn = watch.fn;
  15851. fn(value, ((last === initWatchVal) ? value : last), current);
  15852. if (ttl < 5) {
  15853. logIdx = 4 - ttl;
  15854. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  15855. watchLog[logIdx].push({
  15856. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  15857. newVal: value,
  15858. oldVal: last
  15859. });
  15860. }
  15861. } else if (watch === lastDirtyWatch) {
  15862. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  15863. // have already been tested.
  15864. dirty = false;
  15865. break traverseScopesLoop;
  15866. }
  15867. }
  15868. } catch (e) {
  15869. $exceptionHandler(e);
  15870. }
  15871. }
  15872. }
  15873. // Insanity Warning: scope depth-first traversal
  15874. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  15875. // this piece should be kept in sync with the traversal in $broadcast
  15876. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  15877. (current !== target && current.$$nextSibling)))) {
  15878. while (current !== target && !(next = current.$$nextSibling)) {
  15879. current = current.$parent;
  15880. }
  15881. }
  15882. } while ((current = next));
  15883. // `break traverseScopesLoop;` takes us to here
  15884. if ((dirty || asyncQueue.length) && !(ttl--)) {
  15885. clearPhase();
  15886. throw $rootScopeMinErr('infdig',
  15887. '{0} $digest() iterations reached. Aborting!\n' +
  15888. 'Watchers fired in the last 5 iterations: {1}',
  15889. TTL, watchLog);
  15890. }
  15891. } while (dirty || asyncQueue.length);
  15892. clearPhase();
  15893. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  15894. while (postDigestQueuePosition < postDigestQueue.length) {
  15895. try {
  15896. postDigestQueue[postDigestQueuePosition++]();
  15897. } catch (e) {
  15898. $exceptionHandler(e);
  15899. }
  15900. }
  15901. postDigestQueue.length = postDigestQueuePosition = 0;
  15902. },
  15903. /**
  15904. * @ngdoc event
  15905. * @name $rootScope.Scope#$destroy
  15906. * @eventType broadcast on scope being destroyed
  15907. *
  15908. * @description
  15909. * Broadcasted when a scope and its children are being destroyed.
  15910. *
  15911. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  15912. * clean up DOM bindings before an element is removed from the DOM.
  15913. */
  15914. /**
  15915. * @ngdoc method
  15916. * @name $rootScope.Scope#$destroy
  15917. * @kind function
  15918. *
  15919. * @description
  15920. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  15921. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  15922. * propagate to the current scope and its children. Removal also implies that the current
  15923. * scope is eligible for garbage collection.
  15924. *
  15925. * The `$destroy()` is usually used by directives such as
  15926. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  15927. * unrolling of the loop.
  15928. *
  15929. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  15930. * Application code can register a `$destroy` event handler that will give it a chance to
  15931. * perform any necessary cleanup.
  15932. *
  15933. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  15934. * clean up DOM bindings before an element is removed from the DOM.
  15935. */
  15936. $destroy: function() {
  15937. // We can't destroy a scope that has been already destroyed.
  15938. if (this.$$destroyed) return;
  15939. var parent = this.$parent;
  15940. this.$broadcast('$destroy');
  15941. this.$$destroyed = true;
  15942. if (this === $rootScope) {
  15943. //Remove handlers attached to window when $rootScope is removed
  15944. $browser.$$applicationDestroyed();
  15945. }
  15946. incrementWatchersCount(this, -this.$$watchersCount);
  15947. for (var eventName in this.$$listenerCount) {
  15948. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  15949. }
  15950. // sever all the references to parent scopes (after this cleanup, the current scope should
  15951. // not be retained by any of our references and should be eligible for garbage collection)
  15952. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  15953. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  15954. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  15955. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  15956. // Disable listeners, watchers and apply/digest methods
  15957. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  15958. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  15959. this.$$listeners = {};
  15960. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  15961. this.$$nextSibling = null;
  15962. cleanUpScope(this);
  15963. },
  15964. /**
  15965. * @ngdoc method
  15966. * @name $rootScope.Scope#$eval
  15967. * @kind function
  15968. *
  15969. * @description
  15970. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  15971. * the expression are propagated (uncaught). This is useful when evaluating Angular
  15972. * expressions.
  15973. *
  15974. * # Example
  15975. * ```js
  15976. var scope = ng.$rootScope.Scope();
  15977. scope.a = 1;
  15978. scope.b = 2;
  15979. expect(scope.$eval('a+b')).toEqual(3);
  15980. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  15981. * ```
  15982. *
  15983. * @param {(string|function())=} expression An angular expression to be executed.
  15984. *
  15985. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15986. * - `function(scope)`: execute the function with the current `scope` parameter.
  15987. *
  15988. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  15989. * @returns {*} The result of evaluating the expression.
  15990. */
  15991. $eval: function(expr, locals) {
  15992. return $parse(expr)(this, locals);
  15993. },
  15994. /**
  15995. * @ngdoc method
  15996. * @name $rootScope.Scope#$evalAsync
  15997. * @kind function
  15998. *
  15999. * @description
  16000. * Executes the expression on the current scope at a later point in time.
  16001. *
  16002. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  16003. * that:
  16004. *
  16005. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  16006. * rendering).
  16007. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  16008. * `expression` execution.
  16009. *
  16010. * Any exceptions from the execution of the expression are forwarded to the
  16011. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16012. *
  16013. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  16014. * will be scheduled. However, it is encouraged to always call code that changes the model
  16015. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  16016. *
  16017. * @param {(string|function())=} expression An angular expression to be executed.
  16018. *
  16019. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16020. * - `function(scope)`: execute the function with the current `scope` parameter.
  16021. *
  16022. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16023. */
  16024. $evalAsync: function(expr, locals) {
  16025. // if we are outside of an $digest loop and this is the first time we are scheduling async
  16026. // task also schedule async auto-flush
  16027. if (!$rootScope.$$phase && !asyncQueue.length) {
  16028. $browser.defer(function() {
  16029. if (asyncQueue.length) {
  16030. $rootScope.$digest();
  16031. }
  16032. });
  16033. }
  16034. asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
  16035. },
  16036. $$postDigest: function(fn) {
  16037. postDigestQueue.push(fn);
  16038. },
  16039. /**
  16040. * @ngdoc method
  16041. * @name $rootScope.Scope#$apply
  16042. * @kind function
  16043. *
  16044. * @description
  16045. * `$apply()` is used to execute an expression in angular from outside of the angular
  16046. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  16047. * Because we are calling into the angular framework we need to perform proper scope life
  16048. * cycle of {@link ng.$exceptionHandler exception handling},
  16049. * {@link ng.$rootScope.Scope#$digest executing watches}.
  16050. *
  16051. * ## Life cycle
  16052. *
  16053. * # Pseudo-Code of `$apply()`
  16054. * ```js
  16055. function $apply(expr) {
  16056. try {
  16057. return $eval(expr);
  16058. } catch (e) {
  16059. $exceptionHandler(e);
  16060. } finally {
  16061. $root.$digest();
  16062. }
  16063. }
  16064. * ```
  16065. *
  16066. *
  16067. * Scope's `$apply()` method transitions through the following stages:
  16068. *
  16069. * 1. The {@link guide/expression expression} is executed using the
  16070. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  16071. * 2. Any exceptions from the execution of the expression are forwarded to the
  16072. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16073. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  16074. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  16075. *
  16076. *
  16077. * @param {(string|function())=} exp An angular expression to be executed.
  16078. *
  16079. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16080. * - `function(scope)`: execute the function with current `scope` parameter.
  16081. *
  16082. * @returns {*} The result of evaluating the expression.
  16083. */
  16084. $apply: function(expr) {
  16085. try {
  16086. beginPhase('$apply');
  16087. try {
  16088. return this.$eval(expr);
  16089. } finally {
  16090. clearPhase();
  16091. }
  16092. } catch (e) {
  16093. $exceptionHandler(e);
  16094. } finally {
  16095. try {
  16096. $rootScope.$digest();
  16097. } catch (e) {
  16098. $exceptionHandler(e);
  16099. throw e;
  16100. }
  16101. }
  16102. },
  16103. /**
  16104. * @ngdoc method
  16105. * @name $rootScope.Scope#$applyAsync
  16106. * @kind function
  16107. *
  16108. * @description
  16109. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  16110. * varies across browsers, but is typically around ~10 milliseconds.
  16111. *
  16112. * This can be used to queue up multiple expressions which need to be evaluated in the same
  16113. * digest.
  16114. *
  16115. * @param {(string|function())=} exp An angular expression to be executed.
  16116. *
  16117. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16118. * - `function(scope)`: execute the function with current `scope` parameter.
  16119. */
  16120. $applyAsync: function(expr) {
  16121. var scope = this;
  16122. expr && applyAsyncQueue.push($applyAsyncExpression);
  16123. expr = $parse(expr);
  16124. scheduleApplyAsync();
  16125. function $applyAsyncExpression() {
  16126. scope.$eval(expr);
  16127. }
  16128. },
  16129. /**
  16130. * @ngdoc method
  16131. * @name $rootScope.Scope#$on
  16132. * @kind function
  16133. *
  16134. * @description
  16135. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  16136. * discussion of event life cycle.
  16137. *
  16138. * The event listener function format is: `function(event, args...)`. The `event` object
  16139. * passed into the listener has the following attributes:
  16140. *
  16141. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  16142. * `$broadcast`-ed.
  16143. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  16144. * event propagates through the scope hierarchy, this property is set to null.
  16145. * - `name` - `{string}`: name of the event.
  16146. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  16147. * further event propagation (available only for events that were `$emit`-ed).
  16148. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  16149. * to true.
  16150. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  16151. *
  16152. * @param {string} name Event name to listen on.
  16153. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  16154. * @returns {function()} Returns a deregistration function for this listener.
  16155. */
  16156. $on: function(name, listener) {
  16157. var namedListeners = this.$$listeners[name];
  16158. if (!namedListeners) {
  16159. this.$$listeners[name] = namedListeners = [];
  16160. }
  16161. namedListeners.push(listener);
  16162. var current = this;
  16163. do {
  16164. if (!current.$$listenerCount[name]) {
  16165. current.$$listenerCount[name] = 0;
  16166. }
  16167. current.$$listenerCount[name]++;
  16168. } while ((current = current.$parent));
  16169. var self = this;
  16170. return function() {
  16171. var indexOfListener = namedListeners.indexOf(listener);
  16172. if (indexOfListener !== -1) {
  16173. namedListeners[indexOfListener] = null;
  16174. decrementListenerCount(self, 1, name);
  16175. }
  16176. };
  16177. },
  16178. /**
  16179. * @ngdoc method
  16180. * @name $rootScope.Scope#$emit
  16181. * @kind function
  16182. *
  16183. * @description
  16184. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  16185. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16186. *
  16187. * The event life cycle starts at the scope on which `$emit` was called. All
  16188. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16189. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  16190. * registered listeners along the way. The event will stop propagating if one of the listeners
  16191. * cancels it.
  16192. *
  16193. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16194. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16195. *
  16196. * @param {string} name Event name to emit.
  16197. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16198. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  16199. */
  16200. $emit: function(name, args) {
  16201. var empty = [],
  16202. namedListeners,
  16203. scope = this,
  16204. stopPropagation = false,
  16205. event = {
  16206. name: name,
  16207. targetScope: scope,
  16208. stopPropagation: function() {stopPropagation = true;},
  16209. preventDefault: function() {
  16210. event.defaultPrevented = true;
  16211. },
  16212. defaultPrevented: false
  16213. },
  16214. listenerArgs = concat([event], arguments, 1),
  16215. i, length;
  16216. do {
  16217. namedListeners = scope.$$listeners[name] || empty;
  16218. event.currentScope = scope;
  16219. for (i = 0, length = namedListeners.length; i < length; i++) {
  16220. // if listeners were deregistered, defragment the array
  16221. if (!namedListeners[i]) {
  16222. namedListeners.splice(i, 1);
  16223. i--;
  16224. length--;
  16225. continue;
  16226. }
  16227. try {
  16228. //allow all listeners attached to the current scope to run
  16229. namedListeners[i].apply(null, listenerArgs);
  16230. } catch (e) {
  16231. $exceptionHandler(e);
  16232. }
  16233. }
  16234. //if any listener on the current scope stops propagation, prevent bubbling
  16235. if (stopPropagation) {
  16236. event.currentScope = null;
  16237. return event;
  16238. }
  16239. //traverse upwards
  16240. scope = scope.$parent;
  16241. } while (scope);
  16242. event.currentScope = null;
  16243. return event;
  16244. },
  16245. /**
  16246. * @ngdoc method
  16247. * @name $rootScope.Scope#$broadcast
  16248. * @kind function
  16249. *
  16250. * @description
  16251. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  16252. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16253. *
  16254. * The event life cycle starts at the scope on which `$broadcast` was called. All
  16255. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16256. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  16257. * scope and calls all registered listeners along the way. The event cannot be canceled.
  16258. *
  16259. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16260. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16261. *
  16262. * @param {string} name Event name to broadcast.
  16263. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16264. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  16265. */
  16266. $broadcast: function(name, args) {
  16267. var target = this,
  16268. current = target,
  16269. next = target,
  16270. event = {
  16271. name: name,
  16272. targetScope: target,
  16273. preventDefault: function() {
  16274. event.defaultPrevented = true;
  16275. },
  16276. defaultPrevented: false
  16277. };
  16278. if (!target.$$listenerCount[name]) return event;
  16279. var listenerArgs = concat([event], arguments, 1),
  16280. listeners, i, length;
  16281. //down while you can, then up and next sibling or up and next sibling until back at root
  16282. while ((current = next)) {
  16283. event.currentScope = current;
  16284. listeners = current.$$listeners[name] || [];
  16285. for (i = 0, length = listeners.length; i < length; i++) {
  16286. // if listeners were deregistered, defragment the array
  16287. if (!listeners[i]) {
  16288. listeners.splice(i, 1);
  16289. i--;
  16290. length--;
  16291. continue;
  16292. }
  16293. try {
  16294. listeners[i].apply(null, listenerArgs);
  16295. } catch (e) {
  16296. $exceptionHandler(e);
  16297. }
  16298. }
  16299. // Insanity Warning: scope depth-first traversal
  16300. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16301. // this piece should be kept in sync with the traversal in $digest
  16302. // (though it differs due to having the extra check for $$listenerCount)
  16303. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  16304. (current !== target && current.$$nextSibling)))) {
  16305. while (current !== target && !(next = current.$$nextSibling)) {
  16306. current = current.$parent;
  16307. }
  16308. }
  16309. }
  16310. event.currentScope = null;
  16311. return event;
  16312. }
  16313. };
  16314. var $rootScope = new Scope();
  16315. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  16316. var asyncQueue = $rootScope.$$asyncQueue = [];
  16317. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  16318. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  16319. var postDigestQueuePosition = 0;
  16320. return $rootScope;
  16321. function beginPhase(phase) {
  16322. if ($rootScope.$$phase) {
  16323. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  16324. }
  16325. $rootScope.$$phase = phase;
  16326. }
  16327. function clearPhase() {
  16328. $rootScope.$$phase = null;
  16329. }
  16330. function incrementWatchersCount(current, count) {
  16331. do {
  16332. current.$$watchersCount += count;
  16333. } while ((current = current.$parent));
  16334. }
  16335. function decrementListenerCount(current, count, name) {
  16336. do {
  16337. current.$$listenerCount[name] -= count;
  16338. if (current.$$listenerCount[name] === 0) {
  16339. delete current.$$listenerCount[name];
  16340. }
  16341. } while ((current = current.$parent));
  16342. }
  16343. /**
  16344. * function used as an initial value for watchers.
  16345. * because it's unique we can easily tell it apart from other values
  16346. */
  16347. function initWatchVal() {}
  16348. function flushApplyAsync() {
  16349. while (applyAsyncQueue.length) {
  16350. try {
  16351. applyAsyncQueue.shift()();
  16352. } catch (e) {
  16353. $exceptionHandler(e);
  16354. }
  16355. }
  16356. applyAsyncId = null;
  16357. }
  16358. function scheduleApplyAsync() {
  16359. if (applyAsyncId === null) {
  16360. applyAsyncId = $browser.defer(function() {
  16361. $rootScope.$apply(flushApplyAsync);
  16362. });
  16363. }
  16364. }
  16365. }];
  16366. }
  16367. /**
  16368. * @ngdoc service
  16369. * @name $rootElement
  16370. *
  16371. * @description
  16372. * The root element of Angular application. This is either the element where {@link
  16373. * ng.directive:ngApp ngApp} was declared or the element passed into
  16374. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  16375. * location where the application's {@link auto.$injector $injector} service gets
  16376. * published, and can be retrieved using `$rootElement.injector()`.
  16377. */
  16378. // the implementation is in angular.bootstrap
  16379. /**
  16380. * @description
  16381. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  16382. */
  16383. function $$SanitizeUriProvider() {
  16384. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  16385. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  16386. /**
  16387. * @description
  16388. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16389. * urls during a[href] sanitization.
  16390. *
  16391. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16392. *
  16393. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  16394. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  16395. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16396. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16397. *
  16398. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16399. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16400. * chaining otherwise.
  16401. */
  16402. this.aHrefSanitizationWhitelist = function(regexp) {
  16403. if (isDefined(regexp)) {
  16404. aHrefSanitizationWhitelist = regexp;
  16405. return this;
  16406. }
  16407. return aHrefSanitizationWhitelist;
  16408. };
  16409. /**
  16410. * @description
  16411. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16412. * urls during img[src] sanitization.
  16413. *
  16414. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16415. *
  16416. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  16417. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  16418. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16419. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16420. *
  16421. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16422. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16423. * chaining otherwise.
  16424. */
  16425. this.imgSrcSanitizationWhitelist = function(regexp) {
  16426. if (isDefined(regexp)) {
  16427. imgSrcSanitizationWhitelist = regexp;
  16428. return this;
  16429. }
  16430. return imgSrcSanitizationWhitelist;
  16431. };
  16432. this.$get = function() {
  16433. return function sanitizeUri(uri, isImage) {
  16434. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  16435. var normalizedVal;
  16436. normalizedVal = urlResolve(uri).href;
  16437. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  16438. return 'unsafe:' + normalizedVal;
  16439. }
  16440. return uri;
  16441. };
  16442. };
  16443. }
  16444. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  16445. * Any commits to this file should be reviewed with security in mind. *
  16446. * Changes to this file can potentially create security vulnerabilities. *
  16447. * An approval from 2 Core members with history of modifying *
  16448. * this file is required. *
  16449. * *
  16450. * Does the change somehow allow for arbitrary javascript to be executed? *
  16451. * Or allows for someone to change the prototype of built-in objects? *
  16452. * Or gives undesired access to variables likes document or window? *
  16453. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  16454. var $sceMinErr = minErr('$sce');
  16455. var SCE_CONTEXTS = {
  16456. HTML: 'html',
  16457. CSS: 'css',
  16458. URL: 'url',
  16459. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  16460. // url. (e.g. ng-include, script src, templateUrl)
  16461. RESOURCE_URL: 'resourceUrl',
  16462. JS: 'js'
  16463. };
  16464. // Helper functions follow.
  16465. function adjustMatcher(matcher) {
  16466. if (matcher === 'self') {
  16467. return matcher;
  16468. } else if (isString(matcher)) {
  16469. // Strings match exactly except for 2 wildcards - '*' and '**'.
  16470. // '*' matches any character except those from the set ':/.?&'.
  16471. // '**' matches any character (like .* in a RegExp).
  16472. // More than 2 *'s raises an error as it's ill defined.
  16473. if (matcher.indexOf('***') > -1) {
  16474. throw $sceMinErr('iwcard',
  16475. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  16476. }
  16477. matcher = escapeForRegexp(matcher).
  16478. replace('\\*\\*', '.*').
  16479. replace('\\*', '[^:/.?&;]*');
  16480. return new RegExp('^' + matcher + '$');
  16481. } else if (isRegExp(matcher)) {
  16482. // The only other type of matcher allowed is a Regexp.
  16483. // Match entire URL / disallow partial matches.
  16484. // Flags are reset (i.e. no global, ignoreCase or multiline)
  16485. return new RegExp('^' + matcher.source + '$');
  16486. } else {
  16487. throw $sceMinErr('imatcher',
  16488. 'Matchers may only be "self", string patterns or RegExp objects');
  16489. }
  16490. }
  16491. function adjustMatchers(matchers) {
  16492. var adjustedMatchers = [];
  16493. if (isDefined(matchers)) {
  16494. forEach(matchers, function(matcher) {
  16495. adjustedMatchers.push(adjustMatcher(matcher));
  16496. });
  16497. }
  16498. return adjustedMatchers;
  16499. }
  16500. /**
  16501. * @ngdoc service
  16502. * @name $sceDelegate
  16503. * @kind function
  16504. *
  16505. * @description
  16506. *
  16507. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  16508. * Contextual Escaping (SCE)} services to AngularJS.
  16509. *
  16510. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  16511. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  16512. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  16513. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  16514. * work because `$sce` delegates to `$sceDelegate` for these operations.
  16515. *
  16516. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  16517. *
  16518. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  16519. * can override it completely to change the behavior of `$sce`, the common case would
  16520. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  16521. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  16522. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  16523. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  16524. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16525. */
  16526. /**
  16527. * @ngdoc provider
  16528. * @name $sceDelegateProvider
  16529. * @description
  16530. *
  16531. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  16532. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  16533. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  16534. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  16535. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16536. *
  16537. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  16538. * Strict Contextual Escaping (SCE)}.
  16539. *
  16540. * **Example**: Consider the following case. <a name="example"></a>
  16541. *
  16542. * - your app is hosted at url `http://myapp.example.com/`
  16543. * - but some of your templates are hosted on other domains you control such as
  16544. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  16545. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  16546. *
  16547. * Here is what a secure configuration for this scenario might look like:
  16548. *
  16549. * ```
  16550. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  16551. * $sceDelegateProvider.resourceUrlWhitelist([
  16552. * // Allow same origin resource loads.
  16553. * 'self',
  16554. * // Allow loading from our assets domain. Notice the difference between * and **.
  16555. * 'http://srv*.assets.example.com/**'
  16556. * ]);
  16557. *
  16558. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  16559. * $sceDelegateProvider.resourceUrlBlacklist([
  16560. * 'http://myapp.example.com/clickThru**'
  16561. * ]);
  16562. * });
  16563. * ```
  16564. */
  16565. function $SceDelegateProvider() {
  16566. this.SCE_CONTEXTS = SCE_CONTEXTS;
  16567. // Resource URLs can also be trusted by policy.
  16568. var resourceUrlWhitelist = ['self'],
  16569. resourceUrlBlacklist = [];
  16570. /**
  16571. * @ngdoc method
  16572. * @name $sceDelegateProvider#resourceUrlWhitelist
  16573. * @kind function
  16574. *
  16575. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  16576. * provided. This must be an array or null. A snapshot of this array is used so further
  16577. * changes to the array are ignored.
  16578. *
  16579. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  16580. * allowed in this array.
  16581. *
  16582. * <div class="alert alert-warning">
  16583. * **Note:** an empty whitelist array will block all URLs!
  16584. * </div>
  16585. *
  16586. * @return {Array} the currently set whitelist array.
  16587. *
  16588. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  16589. * same origin resource requests.
  16590. *
  16591. * @description
  16592. * Sets/Gets the whitelist of trusted resource URLs.
  16593. */
  16594. this.resourceUrlWhitelist = function(value) {
  16595. if (arguments.length) {
  16596. resourceUrlWhitelist = adjustMatchers(value);
  16597. }
  16598. return resourceUrlWhitelist;
  16599. };
  16600. /**
  16601. * @ngdoc method
  16602. * @name $sceDelegateProvider#resourceUrlBlacklist
  16603. * @kind function
  16604. *
  16605. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  16606. * provided. This must be an array or null. A snapshot of this array is used so further
  16607. * changes to the array are ignored.
  16608. *
  16609. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  16610. * allowed in this array.
  16611. *
  16612. * The typical usage for the blacklist is to **block
  16613. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  16614. * these would otherwise be trusted but actually return content from the redirected domain.
  16615. *
  16616. * Finally, **the blacklist overrides the whitelist** and has the final say.
  16617. *
  16618. * @return {Array} the currently set blacklist array.
  16619. *
  16620. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  16621. * is no blacklist.)
  16622. *
  16623. * @description
  16624. * Sets/Gets the blacklist of trusted resource URLs.
  16625. */
  16626. this.resourceUrlBlacklist = function(value) {
  16627. if (arguments.length) {
  16628. resourceUrlBlacklist = adjustMatchers(value);
  16629. }
  16630. return resourceUrlBlacklist;
  16631. };
  16632. this.$get = ['$injector', function($injector) {
  16633. var htmlSanitizer = function htmlSanitizer(html) {
  16634. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  16635. };
  16636. if ($injector.has('$sanitize')) {
  16637. htmlSanitizer = $injector.get('$sanitize');
  16638. }
  16639. function matchUrl(matcher, parsedUrl) {
  16640. if (matcher === 'self') {
  16641. return urlIsSameOrigin(parsedUrl);
  16642. } else {
  16643. // definitely a regex. See adjustMatchers()
  16644. return !!matcher.exec(parsedUrl.href);
  16645. }
  16646. }
  16647. function isResourceUrlAllowedByPolicy(url) {
  16648. var parsedUrl = urlResolve(url.toString());
  16649. var i, n, allowed = false;
  16650. // Ensure that at least one item from the whitelist allows this url.
  16651. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  16652. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  16653. allowed = true;
  16654. break;
  16655. }
  16656. }
  16657. if (allowed) {
  16658. // Ensure that no item from the blacklist blocked this url.
  16659. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  16660. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  16661. allowed = false;
  16662. break;
  16663. }
  16664. }
  16665. }
  16666. return allowed;
  16667. }
  16668. function generateHolderType(Base) {
  16669. var holderType = function TrustedValueHolderType(trustedValue) {
  16670. this.$$unwrapTrustedValue = function() {
  16671. return trustedValue;
  16672. };
  16673. };
  16674. if (Base) {
  16675. holderType.prototype = new Base();
  16676. }
  16677. holderType.prototype.valueOf = function sceValueOf() {
  16678. return this.$$unwrapTrustedValue();
  16679. };
  16680. holderType.prototype.toString = function sceToString() {
  16681. return this.$$unwrapTrustedValue().toString();
  16682. };
  16683. return holderType;
  16684. }
  16685. var trustedValueHolderBase = generateHolderType(),
  16686. byType = {};
  16687. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  16688. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  16689. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  16690. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  16691. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  16692. /**
  16693. * @ngdoc method
  16694. * @name $sceDelegate#trustAs
  16695. *
  16696. * @description
  16697. * Returns an object that is trusted by angular for use in specified strict
  16698. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  16699. * attribute interpolation, any dom event binding attribute interpolation
  16700. * such as for onclick, etc.) that uses the provided value.
  16701. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  16702. *
  16703. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  16704. * resourceUrl, html, js and css.
  16705. * @param {*} value The value that that should be considered trusted/safe.
  16706. * @returns {*} A value that can be used to stand in for the provided `value` in places
  16707. * where Angular expects a $sce.trustAs() return value.
  16708. */
  16709. function trustAs(type, trustedValue) {
  16710. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  16711. if (!Constructor) {
  16712. throw $sceMinErr('icontext',
  16713. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  16714. type, trustedValue);
  16715. }
  16716. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  16717. return trustedValue;
  16718. }
  16719. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  16720. // mutable objects, we ensure here that the value passed in is actually a string.
  16721. if (typeof trustedValue !== 'string') {
  16722. throw $sceMinErr('itype',
  16723. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  16724. type);
  16725. }
  16726. return new Constructor(trustedValue);
  16727. }
  16728. /**
  16729. * @ngdoc method
  16730. * @name $sceDelegate#valueOf
  16731. *
  16732. * @description
  16733. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  16734. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  16735. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  16736. *
  16737. * If the passed parameter is not a value that had been returned by {@link
  16738. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  16739. *
  16740. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  16741. * call or anything else.
  16742. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  16743. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  16744. * `value` unchanged.
  16745. */
  16746. function valueOf(maybeTrusted) {
  16747. if (maybeTrusted instanceof trustedValueHolderBase) {
  16748. return maybeTrusted.$$unwrapTrustedValue();
  16749. } else {
  16750. return maybeTrusted;
  16751. }
  16752. }
  16753. /**
  16754. * @ngdoc method
  16755. * @name $sceDelegate#getTrusted
  16756. *
  16757. * @description
  16758. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  16759. * returns the originally supplied value if the queried context type is a supertype of the
  16760. * created type. If this condition isn't satisfied, throws an exception.
  16761. *
  16762. * <div class="alert alert-danger">
  16763. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  16764. * (XSS) vulnerability in your application.
  16765. * </div>
  16766. *
  16767. * @param {string} type The kind of context in which this value is to be used.
  16768. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  16769. * `$sceDelegate.trustAs`} call.
  16770. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  16771. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  16772. */
  16773. function getTrusted(type, maybeTrusted) {
  16774. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  16775. return maybeTrusted;
  16776. }
  16777. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  16778. if (constructor && maybeTrusted instanceof constructor) {
  16779. return maybeTrusted.$$unwrapTrustedValue();
  16780. }
  16781. // If we get here, then we may only take one of two actions.
  16782. // 1. sanitize the value for the requested type, or
  16783. // 2. throw an exception.
  16784. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  16785. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  16786. return maybeTrusted;
  16787. } else {
  16788. throw $sceMinErr('insecurl',
  16789. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  16790. maybeTrusted.toString());
  16791. }
  16792. } else if (type === SCE_CONTEXTS.HTML) {
  16793. return htmlSanitizer(maybeTrusted);
  16794. }
  16795. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  16796. }
  16797. return { trustAs: trustAs,
  16798. getTrusted: getTrusted,
  16799. valueOf: valueOf };
  16800. }];
  16801. }
  16802. /**
  16803. * @ngdoc provider
  16804. * @name $sceProvider
  16805. * @description
  16806. *
  16807. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  16808. * - enable/disable Strict Contextual Escaping (SCE) in a module
  16809. * - override the default implementation with a custom delegate
  16810. *
  16811. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  16812. */
  16813. /* jshint maxlen: false*/
  16814. /**
  16815. * @ngdoc service
  16816. * @name $sce
  16817. * @kind function
  16818. *
  16819. * @description
  16820. *
  16821. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  16822. *
  16823. * # Strict Contextual Escaping
  16824. *
  16825. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  16826. * contexts to result in a value that is marked as safe to use for that context. One example of
  16827. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  16828. * to these contexts as privileged or SCE contexts.
  16829. *
  16830. * As of version 1.2, Angular ships with SCE enabled by default.
  16831. *
  16832. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  16833. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  16834. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  16835. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  16836. * to the top of your HTML document.
  16837. *
  16838. * SCE assists in writing code in a way that (a) is secure by default and (b) makes auditing for
  16839. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  16840. *
  16841. * Here's an example of a binding in a privileged context:
  16842. *
  16843. * ```
  16844. * <input ng-model="userHtml" aria-label="User input">
  16845. * <div ng-bind-html="userHtml"></div>
  16846. * ```
  16847. *
  16848. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  16849. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  16850. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  16851. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  16852. * security vulnerabilities.)
  16853. *
  16854. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  16855. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  16856. *
  16857. * How would you ensure that every place that used these types of bindings was bound to a value that
  16858. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  16859. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  16860. * properties/fields and forgot to update the binding to the sanitized value?
  16861. *
  16862. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  16863. * determine that something explicitly says it's safe to use a value for binding in that
  16864. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  16865. * for those values that you can easily tell are safe - because they were received from your server,
  16866. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  16867. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  16868. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  16869. *
  16870. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  16871. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  16872. * obtain values that will be accepted by SCE / privileged contexts.
  16873. *
  16874. *
  16875. * ## How does it work?
  16876. *
  16877. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  16878. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  16879. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  16880. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  16881. *
  16882. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  16883. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  16884. * simplified):
  16885. *
  16886. * ```
  16887. * var ngBindHtmlDirective = ['$sce', function($sce) {
  16888. * return function(scope, element, attr) {
  16889. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  16890. * element.html(value || '');
  16891. * });
  16892. * };
  16893. * }];
  16894. * ```
  16895. *
  16896. * ## Impact on loading templates
  16897. *
  16898. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  16899. * `templateUrl`'s specified by {@link guide/directive directives}.
  16900. *
  16901. * By default, Angular only loads templates from the same domain and protocol as the application
  16902. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  16903. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  16904. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  16905. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  16906. *
  16907. * *Please note*:
  16908. * The browser's
  16909. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  16910. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  16911. * policy apply in addition to this and may further restrict whether the template is successfully
  16912. * loaded. This means that without the right CORS policy, loading templates from a different domain
  16913. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  16914. * browsers.
  16915. *
  16916. * ## This feels like too much overhead
  16917. *
  16918. * It's important to remember that SCE only applies to interpolation expressions.
  16919. *
  16920. * If your expressions are constant literals, they're automatically trusted and you don't need to
  16921. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  16922. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  16923. *
  16924. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  16925. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  16926. *
  16927. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  16928. * templates in `ng-include` from your application's domain without having to even know about SCE.
  16929. * It blocks loading templates from other domains or loading templates over http from an https
  16930. * served document. You can change these by setting your own custom {@link
  16931. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  16932. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  16933. *
  16934. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  16935. * application that's secure and can be audited to verify that with much more ease than bolting
  16936. * security onto an application later.
  16937. *
  16938. * <a name="contexts"></a>
  16939. * ## What trusted context types are supported?
  16940. *
  16941. * | Context | Notes |
  16942. * |---------------------|----------------|
  16943. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
  16944. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  16945. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
  16946. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  16947. * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
  16948. *
  16949. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  16950. *
  16951. * Each element in these arrays must be one of the following:
  16952. *
  16953. * - **'self'**
  16954. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  16955. * domain** as the application document using the **same protocol**.
  16956. * - **String** (except the special value `'self'`)
  16957. * - The string is matched against the full *normalized / absolute URL* of the resource
  16958. * being tested (substring matches are not good enough.)
  16959. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  16960. * match themselves.
  16961. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  16962. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  16963. * in a whitelist.
  16964. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  16965. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  16966. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  16967. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  16968. * http://foo.example.com/templates/**).
  16969. * - **RegExp** (*see caveat below*)
  16970. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  16971. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  16972. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  16973. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  16974. * small number of cases. A `.` character in the regex used when matching the scheme or a
  16975. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  16976. * is highly recommended to use the string patterns and only fall back to regular expressions
  16977. * as a last resort.
  16978. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  16979. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  16980. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  16981. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  16982. * - If you are generating your JavaScript from some other templating engine (not
  16983. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  16984. * remember to escape your regular expression (and be aware that you might need more than
  16985. * one level of escaping depending on your templating engine and the way you interpolated
  16986. * the value.) Do make use of your platform's escaping mechanism as it might be good
  16987. * enough before coding your own. E.g. Ruby has
  16988. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  16989. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  16990. * Javascript lacks a similar built in function for escaping. Take a look at Google
  16991. * Closure library's [goog.string.regExpEscape(s)](
  16992. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  16993. *
  16994. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  16995. *
  16996. * ## Show me an example using SCE.
  16997. *
  16998. * <example module="mySceApp" deps="angular-sanitize.js">
  16999. * <file name="index.html">
  17000. * <div ng-controller="AppController as myCtrl">
  17001. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  17002. * <b>User comments</b><br>
  17003. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  17004. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  17005. * exploit.
  17006. * <div class="well">
  17007. * <div ng-repeat="userComment in myCtrl.userComments">
  17008. * <b>{{userComment.name}}</b>:
  17009. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  17010. * <br>
  17011. * </div>
  17012. * </div>
  17013. * </div>
  17014. * </file>
  17015. *
  17016. * <file name="script.js">
  17017. * angular.module('mySceApp', ['ngSanitize'])
  17018. * .controller('AppController', ['$http', '$templateCache', '$sce',
  17019. * function($http, $templateCache, $sce) {
  17020. * var self = this;
  17021. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  17022. * self.userComments = userComments;
  17023. * });
  17024. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  17025. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17026. * 'sanitization.&quot;">Hover over this text.</span>');
  17027. * }]);
  17028. * </file>
  17029. *
  17030. * <file name="test_data.json">
  17031. * [
  17032. * { "name": "Alice",
  17033. * "htmlComment":
  17034. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  17035. * },
  17036. * { "name": "Bob",
  17037. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  17038. * }
  17039. * ]
  17040. * </file>
  17041. *
  17042. * <file name="protractor.js" type="protractor">
  17043. * describe('SCE doc demo', function() {
  17044. * it('should sanitize untrusted values', function() {
  17045. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  17046. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  17047. * });
  17048. *
  17049. * it('should NOT sanitize explicitly trusted values', function() {
  17050. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  17051. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17052. * 'sanitization.&quot;">Hover over this text.</span>');
  17053. * });
  17054. * });
  17055. * </file>
  17056. * </example>
  17057. *
  17058. *
  17059. *
  17060. * ## Can I disable SCE completely?
  17061. *
  17062. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  17063. * for little coding overhead. It will be much harder to take an SCE disabled application and
  17064. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  17065. * for cases where you have a lot of existing code that was written before SCE was introduced and
  17066. * you're migrating them a module at a time.
  17067. *
  17068. * That said, here's how you can completely disable SCE:
  17069. *
  17070. * ```
  17071. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  17072. * // Completely disable SCE. For demonstration purposes only!
  17073. * // Do not use in new projects.
  17074. * $sceProvider.enabled(false);
  17075. * });
  17076. * ```
  17077. *
  17078. */
  17079. /* jshint maxlen: 100 */
  17080. function $SceProvider() {
  17081. var enabled = true;
  17082. /**
  17083. * @ngdoc method
  17084. * @name $sceProvider#enabled
  17085. * @kind function
  17086. *
  17087. * @param {boolean=} value If provided, then enables/disables SCE.
  17088. * @return {boolean} true if SCE is enabled, false otherwise.
  17089. *
  17090. * @description
  17091. * Enables/disables SCE and returns the current value.
  17092. */
  17093. this.enabled = function(value) {
  17094. if (arguments.length) {
  17095. enabled = !!value;
  17096. }
  17097. return enabled;
  17098. };
  17099. /* Design notes on the default implementation for SCE.
  17100. *
  17101. * The API contract for the SCE delegate
  17102. * -------------------------------------
  17103. * The SCE delegate object must provide the following 3 methods:
  17104. *
  17105. * - trustAs(contextEnum, value)
  17106. * This method is used to tell the SCE service that the provided value is OK to use in the
  17107. * contexts specified by contextEnum. It must return an object that will be accepted by
  17108. * getTrusted() for a compatible contextEnum and return this value.
  17109. *
  17110. * - valueOf(value)
  17111. * For values that were not produced by trustAs(), return them as is. For values that were
  17112. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  17113. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  17114. * such a value.
  17115. *
  17116. * - getTrusted(contextEnum, value)
  17117. * This function should return the a value that is safe to use in the context specified by
  17118. * contextEnum or throw and exception otherwise.
  17119. *
  17120. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  17121. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  17122. * instance, an implementation could maintain a registry of all trusted objects by context. In
  17123. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  17124. * return the same object passed in if it was found in the registry under a compatible context or
  17125. * throw an exception otherwise. An implementation might only wrap values some of the time based
  17126. * on some criteria. getTrusted() might return a value and not throw an exception for special
  17127. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  17128. *
  17129. *
  17130. * A note on the inheritance model for SCE contexts
  17131. * ------------------------------------------------
  17132. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  17133. * is purely an implementation details.
  17134. *
  17135. * The contract is simply this:
  17136. *
  17137. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  17138. * will also succeed.
  17139. *
  17140. * Inheritance happens to capture this in a natural way. In some future, we
  17141. * may not use inheritance anymore. That is OK because no code outside of
  17142. * sce.js and sceSpecs.js would need to be aware of this detail.
  17143. */
  17144. this.$get = ['$parse', '$sceDelegate', function(
  17145. $parse, $sceDelegate) {
  17146. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  17147. // the "expression(javascript expression)" syntax which is insecure.
  17148. if (enabled && msie < 8) {
  17149. throw $sceMinErr('iequirks',
  17150. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  17151. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  17152. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  17153. }
  17154. var sce = shallowCopy(SCE_CONTEXTS);
  17155. /**
  17156. * @ngdoc method
  17157. * @name $sce#isEnabled
  17158. * @kind function
  17159. *
  17160. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  17161. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  17162. *
  17163. * @description
  17164. * Returns a boolean indicating if SCE is enabled.
  17165. */
  17166. sce.isEnabled = function() {
  17167. return enabled;
  17168. };
  17169. sce.trustAs = $sceDelegate.trustAs;
  17170. sce.getTrusted = $sceDelegate.getTrusted;
  17171. sce.valueOf = $sceDelegate.valueOf;
  17172. if (!enabled) {
  17173. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  17174. sce.valueOf = identity;
  17175. }
  17176. /**
  17177. * @ngdoc method
  17178. * @name $sce#parseAs
  17179. *
  17180. * @description
  17181. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  17182. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  17183. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  17184. * *result*)}
  17185. *
  17186. * @param {string} type The kind of SCE context in which this result will be used.
  17187. * @param {string} expression String expression to compile.
  17188. * @returns {function(context, locals)} a function which represents the compiled expression:
  17189. *
  17190. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17191. * are evaluated against (typically a scope object).
  17192. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17193. * `context`.
  17194. */
  17195. sce.parseAs = function sceParseAs(type, expr) {
  17196. var parsed = $parse(expr);
  17197. if (parsed.literal && parsed.constant) {
  17198. return parsed;
  17199. } else {
  17200. return $parse(expr, function(value) {
  17201. return sce.getTrusted(type, value);
  17202. });
  17203. }
  17204. };
  17205. /**
  17206. * @ngdoc method
  17207. * @name $sce#trustAs
  17208. *
  17209. * @description
  17210. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  17211. * returns an object that is trusted by angular for use in specified strict contextual
  17212. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  17213. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  17214. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  17215. * escaping.
  17216. *
  17217. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  17218. * resourceUrl, html, js and css.
  17219. * @param {*} value The value that that should be considered trusted/safe.
  17220. * @returns {*} A value that can be used to stand in for the provided `value` in places
  17221. * where Angular expects a $sce.trustAs() return value.
  17222. */
  17223. /**
  17224. * @ngdoc method
  17225. * @name $sce#trustAsHtml
  17226. *
  17227. * @description
  17228. * Shorthand method. `$sce.trustAsHtml(value)` →
  17229. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  17230. *
  17231. * @param {*} value The value to trustAs.
  17232. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  17233. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  17234. * only accept expressions that are either literal constants or are the
  17235. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17236. */
  17237. /**
  17238. * @ngdoc method
  17239. * @name $sce#trustAsUrl
  17240. *
  17241. * @description
  17242. * Shorthand method. `$sce.trustAsUrl(value)` →
  17243. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  17244. *
  17245. * @param {*} value The value to trustAs.
  17246. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  17247. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  17248. * only accept expressions that are either literal constants or are the
  17249. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17250. */
  17251. /**
  17252. * @ngdoc method
  17253. * @name $sce#trustAsResourceUrl
  17254. *
  17255. * @description
  17256. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  17257. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  17258. *
  17259. * @param {*} value The value to trustAs.
  17260. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  17261. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  17262. * only accept expressions that are either literal constants or are the return
  17263. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17264. */
  17265. /**
  17266. * @ngdoc method
  17267. * @name $sce#trustAsJs
  17268. *
  17269. * @description
  17270. * Shorthand method. `$sce.trustAsJs(value)` →
  17271. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  17272. *
  17273. * @param {*} value The value to trustAs.
  17274. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  17275. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  17276. * only accept expressions that are either literal constants or are the
  17277. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17278. */
  17279. /**
  17280. * @ngdoc method
  17281. * @name $sce#getTrusted
  17282. *
  17283. * @description
  17284. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  17285. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  17286. * originally supplied value if the queried context type is a supertype of the created type.
  17287. * If this condition isn't satisfied, throws an exception.
  17288. *
  17289. * @param {string} type The kind of context in which this value is to be used.
  17290. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  17291. * call.
  17292. * @returns {*} The value the was originally provided to
  17293. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  17294. * Otherwise, throws an exception.
  17295. */
  17296. /**
  17297. * @ngdoc method
  17298. * @name $sce#getTrustedHtml
  17299. *
  17300. * @description
  17301. * Shorthand method. `$sce.getTrustedHtml(value)` →
  17302. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  17303. *
  17304. * @param {*} value The value to pass to `$sce.getTrusted`.
  17305. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  17306. */
  17307. /**
  17308. * @ngdoc method
  17309. * @name $sce#getTrustedCss
  17310. *
  17311. * @description
  17312. * Shorthand method. `$sce.getTrustedCss(value)` →
  17313. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  17314. *
  17315. * @param {*} value The value to pass to `$sce.getTrusted`.
  17316. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  17317. */
  17318. /**
  17319. * @ngdoc method
  17320. * @name $sce#getTrustedUrl
  17321. *
  17322. * @description
  17323. * Shorthand method. `$sce.getTrustedUrl(value)` →
  17324. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  17325. *
  17326. * @param {*} value The value to pass to `$sce.getTrusted`.
  17327. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  17328. */
  17329. /**
  17330. * @ngdoc method
  17331. * @name $sce#getTrustedResourceUrl
  17332. *
  17333. * @description
  17334. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  17335. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  17336. *
  17337. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  17338. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  17339. */
  17340. /**
  17341. * @ngdoc method
  17342. * @name $sce#getTrustedJs
  17343. *
  17344. * @description
  17345. * Shorthand method. `$sce.getTrustedJs(value)` →
  17346. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  17347. *
  17348. * @param {*} value The value to pass to `$sce.getTrusted`.
  17349. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  17350. */
  17351. /**
  17352. * @ngdoc method
  17353. * @name $sce#parseAsHtml
  17354. *
  17355. * @description
  17356. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  17357. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  17358. *
  17359. * @param {string} expression String expression to compile.
  17360. * @returns {function(context, locals)} a function which represents the compiled expression:
  17361. *
  17362. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17363. * are evaluated against (typically a scope object).
  17364. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17365. * `context`.
  17366. */
  17367. /**
  17368. * @ngdoc method
  17369. * @name $sce#parseAsCss
  17370. *
  17371. * @description
  17372. * Shorthand method. `$sce.parseAsCss(value)` →
  17373. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  17374. *
  17375. * @param {string} expression String expression to compile.
  17376. * @returns {function(context, locals)} a function which represents the compiled expression:
  17377. *
  17378. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17379. * are evaluated against (typically a scope object).
  17380. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17381. * `context`.
  17382. */
  17383. /**
  17384. * @ngdoc method
  17385. * @name $sce#parseAsUrl
  17386. *
  17387. * @description
  17388. * Shorthand method. `$sce.parseAsUrl(value)` →
  17389. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  17390. *
  17391. * @param {string} expression String expression to compile.
  17392. * @returns {function(context, locals)} a function which represents the compiled expression:
  17393. *
  17394. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17395. * are evaluated against (typically a scope object).
  17396. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17397. * `context`.
  17398. */
  17399. /**
  17400. * @ngdoc method
  17401. * @name $sce#parseAsResourceUrl
  17402. *
  17403. * @description
  17404. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  17405. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  17406. *
  17407. * @param {string} expression String expression to compile.
  17408. * @returns {function(context, locals)} a function which represents the compiled expression:
  17409. *
  17410. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17411. * are evaluated against (typically a scope object).
  17412. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17413. * `context`.
  17414. */
  17415. /**
  17416. * @ngdoc method
  17417. * @name $sce#parseAsJs
  17418. *
  17419. * @description
  17420. * Shorthand method. `$sce.parseAsJs(value)` →
  17421. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  17422. *
  17423. * @param {string} expression String expression to compile.
  17424. * @returns {function(context, locals)} a function which represents the compiled expression:
  17425. *
  17426. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17427. * are evaluated against (typically a scope object).
  17428. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17429. * `context`.
  17430. */
  17431. // Shorthand delegations.
  17432. var parse = sce.parseAs,
  17433. getTrusted = sce.getTrusted,
  17434. trustAs = sce.trustAs;
  17435. forEach(SCE_CONTEXTS, function(enumValue, name) {
  17436. var lName = lowercase(name);
  17437. sce[camelCase("parse_as_" + lName)] = function(expr) {
  17438. return parse(enumValue, expr);
  17439. };
  17440. sce[camelCase("get_trusted_" + lName)] = function(value) {
  17441. return getTrusted(enumValue, value);
  17442. };
  17443. sce[camelCase("trust_as_" + lName)] = function(value) {
  17444. return trustAs(enumValue, value);
  17445. };
  17446. });
  17447. return sce;
  17448. }];
  17449. }
  17450. /**
  17451. * !!! This is an undocumented "private" service !!!
  17452. *
  17453. * @name $sniffer
  17454. * @requires $window
  17455. * @requires $document
  17456. *
  17457. * @property {boolean} history Does the browser support html5 history api ?
  17458. * @property {boolean} transitions Does the browser support CSS transition events ?
  17459. * @property {boolean} animations Does the browser support CSS animation events ?
  17460. *
  17461. * @description
  17462. * This is very simple implementation of testing browser's features.
  17463. */
  17464. function $SnifferProvider() {
  17465. this.$get = ['$window', '$document', function($window, $document) {
  17466. var eventSupport = {},
  17467. // Chrome Packaged Apps are not allowed to access `history.pushState`. They can be detected by
  17468. // the presence of `chrome.app.runtime` (see https://developer.chrome.com/apps/api_index)
  17469. isChromePackagedApp = $window.chrome && $window.chrome.app && $window.chrome.app.runtime,
  17470. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  17471. android =
  17472. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  17473. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  17474. document = $document[0] || {},
  17475. vendorPrefix,
  17476. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  17477. bodyStyle = document.body && document.body.style,
  17478. transitions = false,
  17479. animations = false,
  17480. match;
  17481. if (bodyStyle) {
  17482. for (var prop in bodyStyle) {
  17483. if (match = vendorRegex.exec(prop)) {
  17484. vendorPrefix = match[0];
  17485. vendorPrefix = vendorPrefix[0].toUpperCase() + vendorPrefix.substr(1);
  17486. break;
  17487. }
  17488. }
  17489. if (!vendorPrefix) {
  17490. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  17491. }
  17492. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  17493. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  17494. if (android && (!transitions || !animations)) {
  17495. transitions = isString(bodyStyle.webkitTransition);
  17496. animations = isString(bodyStyle.webkitAnimation);
  17497. }
  17498. }
  17499. return {
  17500. // Android has history.pushState, but it does not update location correctly
  17501. // so let's not use the history API at all.
  17502. // http://code.google.com/p/android/issues/detail?id=17471
  17503. // https://github.com/angular/angular.js/issues/904
  17504. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  17505. // so let's not use the history API also
  17506. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  17507. // jshint -W018
  17508. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  17509. // jshint +W018
  17510. hasEvent: function(event) {
  17511. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  17512. // it. In particular the event is not fired when backspace or delete key are pressed or
  17513. // when cut operation is performed.
  17514. // IE10+ implements 'input' event but it erroneously fires under various situations,
  17515. // e.g. when placeholder changes, or a form is focused.
  17516. if (event === 'input' && msie <= 11) return false;
  17517. if (isUndefined(eventSupport[event])) {
  17518. var divElm = document.createElement('div');
  17519. eventSupport[event] = 'on' + event in divElm;
  17520. }
  17521. return eventSupport[event];
  17522. },
  17523. csp: csp(),
  17524. vendorPrefix: vendorPrefix,
  17525. transitions: transitions,
  17526. animations: animations,
  17527. android: android
  17528. };
  17529. }];
  17530. }
  17531. var $templateRequestMinErr = minErr('$compile');
  17532. /**
  17533. * @ngdoc provider
  17534. * @name $templateRequestProvider
  17535. * @description
  17536. * Used to configure the options passed to the {@link $http} service when making a template request.
  17537. *
  17538. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  17539. * requesting a template.
  17540. */
  17541. function $TemplateRequestProvider() {
  17542. var httpOptions;
  17543. /**
  17544. * @ngdoc method
  17545. * @name $templateRequestProvider#httpOptions
  17546. * @description
  17547. * The options to be passed to the {@link $http} service when making the request.
  17548. * You can use this to override options such as the "Accept" header for template requests.
  17549. *
  17550. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  17551. * options if not overridden here.
  17552. *
  17553. * @param {string=} value new value for the {@link $http} options.
  17554. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  17555. */
  17556. this.httpOptions = function(val) {
  17557. if (val) {
  17558. httpOptions = val;
  17559. return this;
  17560. }
  17561. return httpOptions;
  17562. };
  17563. /**
  17564. * @ngdoc service
  17565. * @name $templateRequest
  17566. *
  17567. * @description
  17568. * The `$templateRequest` service runs security checks then downloads the provided template using
  17569. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  17570. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  17571. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  17572. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  17573. * when `tpl` is of type string and `$templateCache` has the matching entry.
  17574. *
  17575. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  17576. * can configure this via {@link $templateRequestProvider#httpOptions}.
  17577. *
  17578. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  17579. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  17580. *
  17581. * @return {Promise} a promise for the HTTP response data of the given URL.
  17582. *
  17583. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  17584. */
  17585. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  17586. function handleRequestFn(tpl, ignoreRequestError) {
  17587. handleRequestFn.totalPendingRequests++;
  17588. // We consider the template cache holds only trusted templates, so
  17589. // there's no need to go through whitelisting again for keys that already
  17590. // are included in there. This also makes Angular accept any script
  17591. // directive, no matter its name. However, we still need to unwrap trusted
  17592. // types.
  17593. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  17594. tpl = $sce.getTrustedResourceUrl(tpl);
  17595. }
  17596. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  17597. if (isArray(transformResponse)) {
  17598. transformResponse = transformResponse.filter(function(transformer) {
  17599. return transformer !== defaultHttpResponseTransform;
  17600. });
  17601. } else if (transformResponse === defaultHttpResponseTransform) {
  17602. transformResponse = null;
  17603. }
  17604. return $http.get(tpl, extend({
  17605. cache: $templateCache,
  17606. transformResponse: transformResponse
  17607. }, httpOptions))
  17608. ['finally'](function() {
  17609. handleRequestFn.totalPendingRequests--;
  17610. })
  17611. .then(function(response) {
  17612. $templateCache.put(tpl, response.data);
  17613. return response.data;
  17614. }, handleError);
  17615. function handleError(resp) {
  17616. if (!ignoreRequestError) {
  17617. throw $templateRequestMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  17618. tpl, resp.status, resp.statusText);
  17619. }
  17620. return $q.reject(resp);
  17621. }
  17622. }
  17623. handleRequestFn.totalPendingRequests = 0;
  17624. return handleRequestFn;
  17625. }];
  17626. }
  17627. function $$TestabilityProvider() {
  17628. this.$get = ['$rootScope', '$browser', '$location',
  17629. function($rootScope, $browser, $location) {
  17630. /**
  17631. * @name $testability
  17632. *
  17633. * @description
  17634. * The private $$testability service provides a collection of methods for use when debugging
  17635. * or by automated test and debugging tools.
  17636. */
  17637. var testability = {};
  17638. /**
  17639. * @name $$testability#findBindings
  17640. *
  17641. * @description
  17642. * Returns an array of elements that are bound (via ng-bind or {{}})
  17643. * to expressions matching the input.
  17644. *
  17645. * @param {Element} element The element root to search from.
  17646. * @param {string} expression The binding expression to match.
  17647. * @param {boolean} opt_exactMatch If true, only returns exact matches
  17648. * for the expression. Filters and whitespace are ignored.
  17649. */
  17650. testability.findBindings = function(element, expression, opt_exactMatch) {
  17651. var bindings = element.getElementsByClassName('ng-binding');
  17652. var matches = [];
  17653. forEach(bindings, function(binding) {
  17654. var dataBinding = angular.element(binding).data('$binding');
  17655. if (dataBinding) {
  17656. forEach(dataBinding, function(bindingName) {
  17657. if (opt_exactMatch) {
  17658. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  17659. if (matcher.test(bindingName)) {
  17660. matches.push(binding);
  17661. }
  17662. } else {
  17663. if (bindingName.indexOf(expression) != -1) {
  17664. matches.push(binding);
  17665. }
  17666. }
  17667. });
  17668. }
  17669. });
  17670. return matches;
  17671. };
  17672. /**
  17673. * @name $$testability#findModels
  17674. *
  17675. * @description
  17676. * Returns an array of elements that are two-way found via ng-model to
  17677. * expressions matching the input.
  17678. *
  17679. * @param {Element} element The element root to search from.
  17680. * @param {string} expression The model expression to match.
  17681. * @param {boolean} opt_exactMatch If true, only returns exact matches
  17682. * for the expression.
  17683. */
  17684. testability.findModels = function(element, expression, opt_exactMatch) {
  17685. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  17686. for (var p = 0; p < prefixes.length; ++p) {
  17687. var attributeEquals = opt_exactMatch ? '=' : '*=';
  17688. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  17689. var elements = element.querySelectorAll(selector);
  17690. if (elements.length) {
  17691. return elements;
  17692. }
  17693. }
  17694. };
  17695. /**
  17696. * @name $$testability#getLocation
  17697. *
  17698. * @description
  17699. * Shortcut for getting the location in a browser agnostic way. Returns
  17700. * the path, search, and hash. (e.g. /path?a=b#hash)
  17701. */
  17702. testability.getLocation = function() {
  17703. return $location.url();
  17704. };
  17705. /**
  17706. * @name $$testability#setLocation
  17707. *
  17708. * @description
  17709. * Shortcut for navigating to a location without doing a full page reload.
  17710. *
  17711. * @param {string} url The location url (path, search and hash,
  17712. * e.g. /path?a=b#hash) to go to.
  17713. */
  17714. testability.setLocation = function(url) {
  17715. if (url !== $location.url()) {
  17716. $location.url(url);
  17717. $rootScope.$digest();
  17718. }
  17719. };
  17720. /**
  17721. * @name $$testability#whenStable
  17722. *
  17723. * @description
  17724. * Calls the callback when $timeout and $http requests are completed.
  17725. *
  17726. * @param {function} callback
  17727. */
  17728. testability.whenStable = function(callback) {
  17729. $browser.notifyWhenNoOutstandingRequests(callback);
  17730. };
  17731. return testability;
  17732. }];
  17733. }
  17734. function $TimeoutProvider() {
  17735. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  17736. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  17737. var deferreds = {};
  17738. /**
  17739. * @ngdoc service
  17740. * @name $timeout
  17741. *
  17742. * @description
  17743. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  17744. * block and delegates any exceptions to
  17745. * {@link ng.$exceptionHandler $exceptionHandler} service.
  17746. *
  17747. * The return value of calling `$timeout` is a promise, which will be resolved when
  17748. * the delay has passed and the timeout function, if provided, is executed.
  17749. *
  17750. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  17751. *
  17752. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  17753. * synchronously flush the queue of deferred functions.
  17754. *
  17755. * If you only want a promise that will be resolved after some specified delay
  17756. * then you can call `$timeout` without the `fn` function.
  17757. *
  17758. * @param {function()=} fn A function, whose execution should be delayed.
  17759. * @param {number=} [delay=0] Delay in milliseconds.
  17760. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  17761. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  17762. * @param {...*=} Pass additional parameters to the executed function.
  17763. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  17764. * will be resolved with the return value of the `fn` function.
  17765. *
  17766. */
  17767. function timeout(fn, delay, invokeApply) {
  17768. if (!isFunction(fn)) {
  17769. invokeApply = delay;
  17770. delay = fn;
  17771. fn = noop;
  17772. }
  17773. var args = sliceArgs(arguments, 3),
  17774. skipApply = (isDefined(invokeApply) && !invokeApply),
  17775. deferred = (skipApply ? $$q : $q).defer(),
  17776. promise = deferred.promise,
  17777. timeoutId;
  17778. timeoutId = $browser.defer(function() {
  17779. try {
  17780. deferred.resolve(fn.apply(null, args));
  17781. } catch (e) {
  17782. deferred.reject(e);
  17783. $exceptionHandler(e);
  17784. }
  17785. finally {
  17786. delete deferreds[promise.$$timeoutId];
  17787. }
  17788. if (!skipApply) $rootScope.$apply();
  17789. }, delay);
  17790. promise.$$timeoutId = timeoutId;
  17791. deferreds[timeoutId] = deferred;
  17792. return promise;
  17793. }
  17794. /**
  17795. * @ngdoc method
  17796. * @name $timeout#cancel
  17797. *
  17798. * @description
  17799. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  17800. * resolved with a rejection.
  17801. *
  17802. * @param {Promise=} promise Promise returned by the `$timeout` function.
  17803. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  17804. * canceled.
  17805. */
  17806. timeout.cancel = function(promise) {
  17807. if (promise && promise.$$timeoutId in deferreds) {
  17808. deferreds[promise.$$timeoutId].reject('canceled');
  17809. delete deferreds[promise.$$timeoutId];
  17810. return $browser.defer.cancel(promise.$$timeoutId);
  17811. }
  17812. return false;
  17813. };
  17814. return timeout;
  17815. }];
  17816. }
  17817. // NOTE: The usage of window and document instead of $window and $document here is
  17818. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  17819. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  17820. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  17821. // doesn't know about mocked locations and resolves URLs to the real document - which is
  17822. // exactly the behavior needed here. There is little value is mocking these out for this
  17823. // service.
  17824. var urlParsingNode = window.document.createElement("a");
  17825. var originUrl = urlResolve(window.location.href);
  17826. /**
  17827. *
  17828. * Implementation Notes for non-IE browsers
  17829. * ----------------------------------------
  17830. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  17831. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  17832. * URL will be resolved into an absolute URL in the context of the application document.
  17833. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  17834. * properties are all populated to reflect the normalized URL. This approach has wide
  17835. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  17836. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  17837. *
  17838. * Implementation Notes for IE
  17839. * ---------------------------
  17840. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  17841. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  17842. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  17843. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  17844. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  17845. * properties such as protocol, hostname, port, etc.
  17846. *
  17847. * References:
  17848. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  17849. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  17850. * http://url.spec.whatwg.org/#urlutils
  17851. * https://github.com/angular/angular.js/pull/2902
  17852. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  17853. *
  17854. * @kind function
  17855. * @param {string} url The URL to be parsed.
  17856. * @description Normalizes and parses a URL.
  17857. * @returns {object} Returns the normalized URL as a dictionary.
  17858. *
  17859. * | member name | Description |
  17860. * |---------------|----------------|
  17861. * | href | A normalized version of the provided URL if it was not an absolute URL |
  17862. * | protocol | The protocol including the trailing colon |
  17863. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  17864. * | search | The search params, minus the question mark |
  17865. * | hash | The hash string, minus the hash symbol
  17866. * | hostname | The hostname
  17867. * | port | The port, without ":"
  17868. * | pathname | The pathname, beginning with "/"
  17869. *
  17870. */
  17871. function urlResolve(url) {
  17872. var href = url;
  17873. if (msie) {
  17874. // Normalize before parse. Refer Implementation Notes on why this is
  17875. // done in two steps on IE.
  17876. urlParsingNode.setAttribute("href", href);
  17877. href = urlParsingNode.href;
  17878. }
  17879. urlParsingNode.setAttribute('href', href);
  17880. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  17881. return {
  17882. href: urlParsingNode.href,
  17883. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  17884. host: urlParsingNode.host,
  17885. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  17886. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  17887. hostname: urlParsingNode.hostname,
  17888. port: urlParsingNode.port,
  17889. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  17890. ? urlParsingNode.pathname
  17891. : '/' + urlParsingNode.pathname
  17892. };
  17893. }
  17894. /**
  17895. * Parse a request URL and determine whether this is a same-origin request as the application document.
  17896. *
  17897. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  17898. * or a parsed URL object.
  17899. * @returns {boolean} Whether the request is for the same origin as the application document.
  17900. */
  17901. function urlIsSameOrigin(requestUrl) {
  17902. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  17903. return (parsed.protocol === originUrl.protocol &&
  17904. parsed.host === originUrl.host);
  17905. }
  17906. /**
  17907. * @ngdoc service
  17908. * @name $window
  17909. *
  17910. * @description
  17911. * A reference to the browser's `window` object. While `window`
  17912. * is globally available in JavaScript, it causes testability problems, because
  17913. * it is a global variable. In angular we always refer to it through the
  17914. * `$window` service, so it may be overridden, removed or mocked for testing.
  17915. *
  17916. * Expressions, like the one defined for the `ngClick` directive in the example
  17917. * below, are evaluated with respect to the current scope. Therefore, there is
  17918. * no risk of inadvertently coding in a dependency on a global value in such an
  17919. * expression.
  17920. *
  17921. * @example
  17922. <example module="windowExample">
  17923. <file name="index.html">
  17924. <script>
  17925. angular.module('windowExample', [])
  17926. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  17927. $scope.greeting = 'Hello, World!';
  17928. $scope.doGreeting = function(greeting) {
  17929. $window.alert(greeting);
  17930. };
  17931. }]);
  17932. </script>
  17933. <div ng-controller="ExampleController">
  17934. <input type="text" ng-model="greeting" aria-label="greeting" />
  17935. <button ng-click="doGreeting(greeting)">ALERT</button>
  17936. </div>
  17937. </file>
  17938. <file name="protractor.js" type="protractor">
  17939. it('should display the greeting in the input box', function() {
  17940. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  17941. // If we click the button it will block the test runner
  17942. // element(':button').click();
  17943. });
  17944. </file>
  17945. </example>
  17946. */
  17947. function $WindowProvider() {
  17948. this.$get = valueFn(window);
  17949. }
  17950. /**
  17951. * @name $$cookieReader
  17952. * @requires $document
  17953. *
  17954. * @description
  17955. * This is a private service for reading cookies used by $http and ngCookies
  17956. *
  17957. * @return {Object} a key/value map of the current cookies
  17958. */
  17959. function $$CookieReader($document) {
  17960. var rawDocument = $document[0] || {};
  17961. var lastCookies = {};
  17962. var lastCookieString = '';
  17963. function safeDecodeURIComponent(str) {
  17964. try {
  17965. return decodeURIComponent(str);
  17966. } catch (e) {
  17967. return str;
  17968. }
  17969. }
  17970. return function() {
  17971. var cookieArray, cookie, i, index, name;
  17972. var currentCookieString = rawDocument.cookie || '';
  17973. if (currentCookieString !== lastCookieString) {
  17974. lastCookieString = currentCookieString;
  17975. cookieArray = lastCookieString.split('; ');
  17976. lastCookies = {};
  17977. for (i = 0; i < cookieArray.length; i++) {
  17978. cookie = cookieArray[i];
  17979. index = cookie.indexOf('=');
  17980. if (index > 0) { //ignore nameless cookies
  17981. name = safeDecodeURIComponent(cookie.substring(0, index));
  17982. // the first value that is seen for a cookie is the most
  17983. // specific one. values for the same cookie name that
  17984. // follow are for less specific paths.
  17985. if (isUndefined(lastCookies[name])) {
  17986. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  17987. }
  17988. }
  17989. }
  17990. }
  17991. return lastCookies;
  17992. };
  17993. }
  17994. $$CookieReader.$inject = ['$document'];
  17995. function $$CookieReaderProvider() {
  17996. this.$get = $$CookieReader;
  17997. }
  17998. /* global currencyFilter: true,
  17999. dateFilter: true,
  18000. filterFilter: true,
  18001. jsonFilter: true,
  18002. limitToFilter: true,
  18003. lowercaseFilter: true,
  18004. numberFilter: true,
  18005. orderByFilter: true,
  18006. uppercaseFilter: true,
  18007. */
  18008. /**
  18009. * @ngdoc provider
  18010. * @name $filterProvider
  18011. * @description
  18012. *
  18013. * Filters are just functions which transform input to an output. However filters need to be
  18014. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  18015. * annotated with dependencies and is responsible for creating a filter function.
  18016. *
  18017. * <div class="alert alert-warning">
  18018. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18019. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18020. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18021. * (`myapp_subsection_filterx`).
  18022. * </div>
  18023. *
  18024. * ```js
  18025. * // Filter registration
  18026. * function MyModule($provide, $filterProvider) {
  18027. * // create a service to demonstrate injection (not always needed)
  18028. * $provide.value('greet', function(name){
  18029. * return 'Hello ' + name + '!';
  18030. * });
  18031. *
  18032. * // register a filter factory which uses the
  18033. * // greet service to demonstrate DI.
  18034. * $filterProvider.register('greet', function(greet){
  18035. * // return the filter function which uses the greet service
  18036. * // to generate salutation
  18037. * return function(text) {
  18038. * // filters need to be forgiving so check input validity
  18039. * return text && greet(text) || text;
  18040. * };
  18041. * });
  18042. * }
  18043. * ```
  18044. *
  18045. * The filter function is registered with the `$injector` under the filter name suffix with
  18046. * `Filter`.
  18047. *
  18048. * ```js
  18049. * it('should be the same instance', inject(
  18050. * function($filterProvider) {
  18051. * $filterProvider.register('reverse', function(){
  18052. * return ...;
  18053. * });
  18054. * },
  18055. * function($filter, reverseFilter) {
  18056. * expect($filter('reverse')).toBe(reverseFilter);
  18057. * });
  18058. * ```
  18059. *
  18060. *
  18061. * For more information about how angular filters work, and how to create your own filters, see
  18062. * {@link guide/filter Filters} in the Angular Developer Guide.
  18063. */
  18064. /**
  18065. * @ngdoc service
  18066. * @name $filter
  18067. * @kind function
  18068. * @description
  18069. * Filters are used for formatting data displayed to the user.
  18070. *
  18071. * The general syntax in templates is as follows:
  18072. *
  18073. * {{ expression [| filter_name[:parameter_value] ... ] }}
  18074. *
  18075. * @param {String} name Name of the filter function to retrieve
  18076. * @return {Function} the filter function
  18077. * @example
  18078. <example name="$filter" module="filterExample">
  18079. <file name="index.html">
  18080. <div ng-controller="MainCtrl">
  18081. <h3>{{ originalText }}</h3>
  18082. <h3>{{ filteredText }}</h3>
  18083. </div>
  18084. </file>
  18085. <file name="script.js">
  18086. angular.module('filterExample', [])
  18087. .controller('MainCtrl', function($scope, $filter) {
  18088. $scope.originalText = 'hello';
  18089. $scope.filteredText = $filter('uppercase')($scope.originalText);
  18090. });
  18091. </file>
  18092. </example>
  18093. */
  18094. $FilterProvider.$inject = ['$provide'];
  18095. function $FilterProvider($provide) {
  18096. var suffix = 'Filter';
  18097. /**
  18098. * @ngdoc method
  18099. * @name $filterProvider#register
  18100. * @param {string|Object} name Name of the filter function, or an object map of filters where
  18101. * the keys are the filter names and the values are the filter factories.
  18102. *
  18103. * <div class="alert alert-warning">
  18104. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18105. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18106. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18107. * (`myapp_subsection_filterx`).
  18108. * </div>
  18109. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  18110. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  18111. * of the registered filter instances.
  18112. */
  18113. function register(name, factory) {
  18114. if (isObject(name)) {
  18115. var filters = {};
  18116. forEach(name, function(filter, key) {
  18117. filters[key] = register(key, filter);
  18118. });
  18119. return filters;
  18120. } else {
  18121. return $provide.factory(name + suffix, factory);
  18122. }
  18123. }
  18124. this.register = register;
  18125. this.$get = ['$injector', function($injector) {
  18126. return function(name) {
  18127. return $injector.get(name + suffix);
  18128. };
  18129. }];
  18130. ////////////////////////////////////////
  18131. /* global
  18132. currencyFilter: false,
  18133. dateFilter: false,
  18134. filterFilter: false,
  18135. jsonFilter: false,
  18136. limitToFilter: false,
  18137. lowercaseFilter: false,
  18138. numberFilter: false,
  18139. orderByFilter: false,
  18140. uppercaseFilter: false,
  18141. */
  18142. register('currency', currencyFilter);
  18143. register('date', dateFilter);
  18144. register('filter', filterFilter);
  18145. register('json', jsonFilter);
  18146. register('limitTo', limitToFilter);
  18147. register('lowercase', lowercaseFilter);
  18148. register('number', numberFilter);
  18149. register('orderBy', orderByFilter);
  18150. register('uppercase', uppercaseFilter);
  18151. }
  18152. /**
  18153. * @ngdoc filter
  18154. * @name filter
  18155. * @kind function
  18156. *
  18157. * @description
  18158. * Selects a subset of items from `array` and returns it as a new array.
  18159. *
  18160. * @param {Array} array The source array.
  18161. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  18162. * `array`.
  18163. *
  18164. * Can be one of:
  18165. *
  18166. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  18167. * objects with string properties in `array` that match this string will be returned. This also
  18168. * applies to nested object properties.
  18169. * The predicate can be negated by prefixing the string with `!`.
  18170. *
  18171. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  18172. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  18173. * which have property `name` containing "M" and property `phone` containing "1". A special
  18174. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  18175. * against any property of the object or its nested object properties. That's equivalent to the
  18176. * simple substring match with a `string` as described above. The special property name can be
  18177. * overwritten, using the `anyPropertyKey` parameter.
  18178. * The predicate can be negated by prefixing the string with `!`.
  18179. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  18180. * not containing "M".
  18181. *
  18182. * Note that a named property will match properties on the same level only, while the special
  18183. * `$` property will match properties on the same level or deeper. E.g. an array item like
  18184. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  18185. * **will** be matched by `{$: 'John'}`.
  18186. *
  18187. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  18188. * The function is called for each element of the array, with the element, its index, and
  18189. * the entire array itself as arguments.
  18190. *
  18191. * The final result is an array of those elements that the predicate returned true for.
  18192. *
  18193. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  18194. * determining if the expected value (from the filter expression) and actual value (from
  18195. * the object in the array) should be considered a match.
  18196. *
  18197. * Can be one of:
  18198. *
  18199. * - `function(actual, expected)`:
  18200. * The function will be given the object value and the predicate value to compare and
  18201. * should return true if both values should be considered equal.
  18202. *
  18203. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  18204. * This is essentially strict comparison of expected and actual.
  18205. *
  18206. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  18207. * insensitive way.
  18208. *
  18209. * Primitive values are converted to strings. Objects are not compared against primitives,
  18210. * unless they have a custom `toString` method (e.g. `Date` objects).
  18211. *
  18212. * @param {string=} anyPropertyKey The special property name that matches against any property.
  18213. * By default `$`.
  18214. *
  18215. * @example
  18216. <example>
  18217. <file name="index.html">
  18218. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  18219. {name:'Mary', phone:'800-BIG-MARY'},
  18220. {name:'Mike', phone:'555-4321'},
  18221. {name:'Adam', phone:'555-5678'},
  18222. {name:'Julie', phone:'555-8765'},
  18223. {name:'Juliette', phone:'555-5678'}]"></div>
  18224. <label>Search: <input ng-model="searchText"></label>
  18225. <table id="searchTextResults">
  18226. <tr><th>Name</th><th>Phone</th></tr>
  18227. <tr ng-repeat="friend in friends | filter:searchText">
  18228. <td>{{friend.name}}</td>
  18229. <td>{{friend.phone}}</td>
  18230. </tr>
  18231. </table>
  18232. <hr>
  18233. <label>Any: <input ng-model="search.$"></label> <br>
  18234. <label>Name only <input ng-model="search.name"></label><br>
  18235. <label>Phone only <input ng-model="search.phone"></label><br>
  18236. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  18237. <table id="searchObjResults">
  18238. <tr><th>Name</th><th>Phone</th></tr>
  18239. <tr ng-repeat="friendObj in friends | filter:search:strict">
  18240. <td>{{friendObj.name}}</td>
  18241. <td>{{friendObj.phone}}</td>
  18242. </tr>
  18243. </table>
  18244. </file>
  18245. <file name="protractor.js" type="protractor">
  18246. var expectFriendNames = function(expectedNames, key) {
  18247. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  18248. arr.forEach(function(wd, i) {
  18249. expect(wd.getText()).toMatch(expectedNames[i]);
  18250. });
  18251. });
  18252. };
  18253. it('should search across all fields when filtering with a string', function() {
  18254. var searchText = element(by.model('searchText'));
  18255. searchText.clear();
  18256. searchText.sendKeys('m');
  18257. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  18258. searchText.clear();
  18259. searchText.sendKeys('76');
  18260. expectFriendNames(['John', 'Julie'], 'friend');
  18261. });
  18262. it('should search in specific fields when filtering with a predicate object', function() {
  18263. var searchAny = element(by.model('search.$'));
  18264. searchAny.clear();
  18265. searchAny.sendKeys('i');
  18266. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  18267. });
  18268. it('should use a equal comparison when comparator is true', function() {
  18269. var searchName = element(by.model('search.name'));
  18270. var strict = element(by.model('strict'));
  18271. searchName.clear();
  18272. searchName.sendKeys('Julie');
  18273. strict.click();
  18274. expectFriendNames(['Julie'], 'friendObj');
  18275. });
  18276. </file>
  18277. </example>
  18278. */
  18279. function filterFilter() {
  18280. return function(array, expression, comparator, anyPropertyKey) {
  18281. if (!isArrayLike(array)) {
  18282. if (array == null) {
  18283. return array;
  18284. } else {
  18285. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  18286. }
  18287. }
  18288. anyPropertyKey = anyPropertyKey || '$';
  18289. var expressionType = getTypeForFilter(expression);
  18290. var predicateFn;
  18291. var matchAgainstAnyProp;
  18292. switch (expressionType) {
  18293. case 'function':
  18294. predicateFn = expression;
  18295. break;
  18296. case 'boolean':
  18297. case 'null':
  18298. case 'number':
  18299. case 'string':
  18300. matchAgainstAnyProp = true;
  18301. //jshint -W086
  18302. case 'object':
  18303. //jshint +W086
  18304. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18305. break;
  18306. default:
  18307. return array;
  18308. }
  18309. return Array.prototype.filter.call(array, predicateFn);
  18310. };
  18311. }
  18312. // Helper functions for `filterFilter`
  18313. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  18314. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  18315. var predicateFn;
  18316. if (comparator === true) {
  18317. comparator = equals;
  18318. } else if (!isFunction(comparator)) {
  18319. comparator = function(actual, expected) {
  18320. if (isUndefined(actual)) {
  18321. // No substring matching against `undefined`
  18322. return false;
  18323. }
  18324. if ((actual === null) || (expected === null)) {
  18325. // No substring matching against `null`; only match against `null`
  18326. return actual === expected;
  18327. }
  18328. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  18329. // Should not compare primitives against objects, unless they have custom `toString` method
  18330. return false;
  18331. }
  18332. actual = lowercase('' + actual);
  18333. expected = lowercase('' + expected);
  18334. return actual.indexOf(expected) !== -1;
  18335. };
  18336. }
  18337. predicateFn = function(item) {
  18338. if (shouldMatchPrimitives && !isObject(item)) {
  18339. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  18340. }
  18341. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18342. };
  18343. return predicateFn;
  18344. }
  18345. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  18346. var actualType = getTypeForFilter(actual);
  18347. var expectedType = getTypeForFilter(expected);
  18348. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  18349. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  18350. } else if (isArray(actual)) {
  18351. // In case `actual` is an array, consider it a match
  18352. // if ANY of it's items matches `expected`
  18353. return actual.some(function(item) {
  18354. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  18355. });
  18356. }
  18357. switch (actualType) {
  18358. case 'object':
  18359. var key;
  18360. if (matchAgainstAnyProp) {
  18361. for (key in actual) {
  18362. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  18363. return true;
  18364. }
  18365. }
  18366. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  18367. } else if (expectedType === 'object') {
  18368. for (key in expected) {
  18369. var expectedVal = expected[key];
  18370. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  18371. continue;
  18372. }
  18373. var matchAnyProperty = key === anyPropertyKey;
  18374. var actualVal = matchAnyProperty ? actual : actual[key];
  18375. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  18376. return false;
  18377. }
  18378. }
  18379. return true;
  18380. } else {
  18381. return comparator(actual, expected);
  18382. }
  18383. break;
  18384. case 'function':
  18385. return false;
  18386. default:
  18387. return comparator(actual, expected);
  18388. }
  18389. }
  18390. // Used for easily differentiating between `null` and actual `object`
  18391. function getTypeForFilter(val) {
  18392. return (val === null) ? 'null' : typeof val;
  18393. }
  18394. var MAX_DIGITS = 22;
  18395. var DECIMAL_SEP = '.';
  18396. var ZERO_CHAR = '0';
  18397. /**
  18398. * @ngdoc filter
  18399. * @name currency
  18400. * @kind function
  18401. *
  18402. * @description
  18403. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  18404. * symbol for current locale is used.
  18405. *
  18406. * @param {number} amount Input to filter.
  18407. * @param {string=} symbol Currency symbol or identifier to be displayed.
  18408. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  18409. * @returns {string} Formatted number.
  18410. *
  18411. *
  18412. * @example
  18413. <example module="currencyExample">
  18414. <file name="index.html">
  18415. <script>
  18416. angular.module('currencyExample', [])
  18417. .controller('ExampleController', ['$scope', function($scope) {
  18418. $scope.amount = 1234.56;
  18419. }]);
  18420. </script>
  18421. <div ng-controller="ExampleController">
  18422. <input type="number" ng-model="amount" aria-label="amount"> <br>
  18423. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  18424. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  18425. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  18426. </div>
  18427. </file>
  18428. <file name="protractor.js" type="protractor">
  18429. it('should init with 1234.56', function() {
  18430. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  18431. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  18432. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  18433. });
  18434. it('should update', function() {
  18435. if (browser.params.browser == 'safari') {
  18436. // Safari does not understand the minus key. See
  18437. // https://github.com/angular/protractor/issues/481
  18438. return;
  18439. }
  18440. element(by.model('amount')).clear();
  18441. element(by.model('amount')).sendKeys('-1234');
  18442. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  18443. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  18444. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  18445. });
  18446. </file>
  18447. </example>
  18448. */
  18449. currencyFilter.$inject = ['$locale'];
  18450. function currencyFilter($locale) {
  18451. var formats = $locale.NUMBER_FORMATS;
  18452. return function(amount, currencySymbol, fractionSize) {
  18453. if (isUndefined(currencySymbol)) {
  18454. currencySymbol = formats.CURRENCY_SYM;
  18455. }
  18456. if (isUndefined(fractionSize)) {
  18457. fractionSize = formats.PATTERNS[1].maxFrac;
  18458. }
  18459. // if null or undefined pass it through
  18460. return (amount == null)
  18461. ? amount
  18462. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  18463. replace(/\u00A4/g, currencySymbol);
  18464. };
  18465. }
  18466. /**
  18467. * @ngdoc filter
  18468. * @name number
  18469. * @kind function
  18470. *
  18471. * @description
  18472. * Formats a number as text.
  18473. *
  18474. * If the input is null or undefined, it will just be returned.
  18475. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  18476. * If the input is not a number an empty string is returned.
  18477. *
  18478. *
  18479. * @param {number|string} number Number to format.
  18480. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  18481. * If this is not provided then the fraction size is computed from the current locale's number
  18482. * formatting pattern. In the case of the default locale, it will be 3.
  18483. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  18484. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  18485. * include "," group separators after each third digit).
  18486. *
  18487. * @example
  18488. <example module="numberFilterExample">
  18489. <file name="index.html">
  18490. <script>
  18491. angular.module('numberFilterExample', [])
  18492. .controller('ExampleController', ['$scope', function($scope) {
  18493. $scope.val = 1234.56789;
  18494. }]);
  18495. </script>
  18496. <div ng-controller="ExampleController">
  18497. <label>Enter number: <input ng-model='val'></label><br>
  18498. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  18499. No fractions: <span>{{val | number:0}}</span><br>
  18500. Negative number: <span>{{-val | number:4}}</span>
  18501. </div>
  18502. </file>
  18503. <file name="protractor.js" type="protractor">
  18504. it('should format numbers', function() {
  18505. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  18506. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  18507. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  18508. });
  18509. it('should update', function() {
  18510. element(by.model('val')).clear();
  18511. element(by.model('val')).sendKeys('3374.333');
  18512. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  18513. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  18514. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  18515. });
  18516. </file>
  18517. </example>
  18518. */
  18519. numberFilter.$inject = ['$locale'];
  18520. function numberFilter($locale) {
  18521. var formats = $locale.NUMBER_FORMATS;
  18522. return function(number, fractionSize) {
  18523. // if null or undefined pass it through
  18524. return (number == null)
  18525. ? number
  18526. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  18527. fractionSize);
  18528. };
  18529. }
  18530. /**
  18531. * Parse a number (as a string) into three components that can be used
  18532. * for formatting the number.
  18533. *
  18534. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  18535. *
  18536. * @param {string} numStr The number to parse
  18537. * @return {object} An object describing this number, containing the following keys:
  18538. * - d : an array of digits containing leading zeros as necessary
  18539. * - i : the number of the digits in `d` that are to the left of the decimal point
  18540. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  18541. *
  18542. */
  18543. function parse(numStr) {
  18544. var exponent = 0, digits, numberOfIntegerDigits;
  18545. var i, j, zeros;
  18546. // Decimal point?
  18547. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  18548. numStr = numStr.replace(DECIMAL_SEP, '');
  18549. }
  18550. // Exponential form?
  18551. if ((i = numStr.search(/e/i)) > 0) {
  18552. // Work out the exponent.
  18553. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  18554. numberOfIntegerDigits += +numStr.slice(i + 1);
  18555. numStr = numStr.substring(0, i);
  18556. } else if (numberOfIntegerDigits < 0) {
  18557. // There was no decimal point or exponent so it is an integer.
  18558. numberOfIntegerDigits = numStr.length;
  18559. }
  18560. // Count the number of leading zeros.
  18561. for (i = 0; numStr.charAt(i) == ZERO_CHAR; i++) {/* jshint noempty: false */}
  18562. if (i == (zeros = numStr.length)) {
  18563. // The digits are all zero.
  18564. digits = [0];
  18565. numberOfIntegerDigits = 1;
  18566. } else {
  18567. // Count the number of trailing zeros
  18568. zeros--;
  18569. while (numStr.charAt(zeros) == ZERO_CHAR) zeros--;
  18570. // Trailing zeros are insignificant so ignore them
  18571. numberOfIntegerDigits -= i;
  18572. digits = [];
  18573. // Convert string to array of digits without leading/trailing zeros.
  18574. for (j = 0; i <= zeros; i++, j++) {
  18575. digits[j] = +numStr.charAt(i);
  18576. }
  18577. }
  18578. // If the number overflows the maximum allowed digits then use an exponent.
  18579. if (numberOfIntegerDigits > MAX_DIGITS) {
  18580. digits = digits.splice(0, MAX_DIGITS - 1);
  18581. exponent = numberOfIntegerDigits - 1;
  18582. numberOfIntegerDigits = 1;
  18583. }
  18584. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  18585. }
  18586. /**
  18587. * Round the parsed number to the specified number of decimal places
  18588. * This function changed the parsedNumber in-place
  18589. */
  18590. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  18591. var digits = parsedNumber.d;
  18592. var fractionLen = digits.length - parsedNumber.i;
  18593. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  18594. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  18595. // The index of the digit to where rounding is to occur
  18596. var roundAt = fractionSize + parsedNumber.i;
  18597. var digit = digits[roundAt];
  18598. if (roundAt > 0) {
  18599. // Drop fractional digits beyond `roundAt`
  18600. digits.splice(Math.max(parsedNumber.i, roundAt));
  18601. // Set non-fractional digits beyond `roundAt` to 0
  18602. for (var j = roundAt; j < digits.length; j++) {
  18603. digits[j] = 0;
  18604. }
  18605. } else {
  18606. // We rounded to zero so reset the parsedNumber
  18607. fractionLen = Math.max(0, fractionLen);
  18608. parsedNumber.i = 1;
  18609. digits.length = Math.max(1, roundAt = fractionSize + 1);
  18610. digits[0] = 0;
  18611. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  18612. }
  18613. if (digit >= 5) {
  18614. if (roundAt - 1 < 0) {
  18615. for (var k = 0; k > roundAt; k--) {
  18616. digits.unshift(0);
  18617. parsedNumber.i++;
  18618. }
  18619. digits.unshift(1);
  18620. parsedNumber.i++;
  18621. } else {
  18622. digits[roundAt - 1]++;
  18623. }
  18624. }
  18625. // Pad out with zeros to get the required fraction length
  18626. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  18627. // Do any carrying, e.g. a digit was rounded up to 10
  18628. var carry = digits.reduceRight(function(carry, d, i, digits) {
  18629. d = d + carry;
  18630. digits[i] = d % 10;
  18631. return Math.floor(d / 10);
  18632. }, 0);
  18633. if (carry) {
  18634. digits.unshift(carry);
  18635. parsedNumber.i++;
  18636. }
  18637. }
  18638. /**
  18639. * Format a number into a string
  18640. * @param {number} number The number to format
  18641. * @param {{
  18642. * minFrac, // the minimum number of digits required in the fraction part of the number
  18643. * maxFrac, // the maximum number of digits required in the fraction part of the number
  18644. * gSize, // number of digits in each group of separated digits
  18645. * lgSize, // number of digits in the last group of digits before the decimal separator
  18646. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  18647. * posPre, // the string to go in front of a positive number
  18648. * negSuf, // the string to go after a negative number (e.g. `)`)
  18649. * posSuf // the string to go after a positive number
  18650. * }} pattern
  18651. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  18652. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  18653. * @param {[type]} fractionSize The size of the fractional part of the number
  18654. * @return {string} The number formatted as a string
  18655. */
  18656. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  18657. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  18658. var isInfinity = !isFinite(number);
  18659. var isZero = false;
  18660. var numStr = Math.abs(number) + '',
  18661. formattedText = '',
  18662. parsedNumber;
  18663. if (isInfinity) {
  18664. formattedText = '\u221e';
  18665. } else {
  18666. parsedNumber = parse(numStr);
  18667. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  18668. var digits = parsedNumber.d;
  18669. var integerLen = parsedNumber.i;
  18670. var exponent = parsedNumber.e;
  18671. var decimals = [];
  18672. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  18673. // pad zeros for small numbers
  18674. while (integerLen < 0) {
  18675. digits.unshift(0);
  18676. integerLen++;
  18677. }
  18678. // extract decimals digits
  18679. if (integerLen > 0) {
  18680. decimals = digits.splice(integerLen, digits.length);
  18681. } else {
  18682. decimals = digits;
  18683. digits = [0];
  18684. }
  18685. // format the integer digits with grouping separators
  18686. var groups = [];
  18687. if (digits.length >= pattern.lgSize) {
  18688. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  18689. }
  18690. while (digits.length > pattern.gSize) {
  18691. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  18692. }
  18693. if (digits.length) {
  18694. groups.unshift(digits.join(''));
  18695. }
  18696. formattedText = groups.join(groupSep);
  18697. // append the decimal digits
  18698. if (decimals.length) {
  18699. formattedText += decimalSep + decimals.join('');
  18700. }
  18701. if (exponent) {
  18702. formattedText += 'e+' + exponent;
  18703. }
  18704. }
  18705. if (number < 0 && !isZero) {
  18706. return pattern.negPre + formattedText + pattern.negSuf;
  18707. } else {
  18708. return pattern.posPre + formattedText + pattern.posSuf;
  18709. }
  18710. }
  18711. function padNumber(num, digits, trim, negWrap) {
  18712. var neg = '';
  18713. if (num < 0 || (negWrap && num <= 0)) {
  18714. if (negWrap) {
  18715. num = -num + 1;
  18716. } else {
  18717. num = -num;
  18718. neg = '-';
  18719. }
  18720. }
  18721. num = '' + num;
  18722. while (num.length < digits) num = ZERO_CHAR + num;
  18723. if (trim) {
  18724. num = num.substr(num.length - digits);
  18725. }
  18726. return neg + num;
  18727. }
  18728. function dateGetter(name, size, offset, trim, negWrap) {
  18729. offset = offset || 0;
  18730. return function(date) {
  18731. var value = date['get' + name]();
  18732. if (offset > 0 || value > -offset) {
  18733. value += offset;
  18734. }
  18735. if (value === 0 && offset == -12) value = 12;
  18736. return padNumber(value, size, trim, negWrap);
  18737. };
  18738. }
  18739. function dateStrGetter(name, shortForm, standAlone) {
  18740. return function(date, formats) {
  18741. var value = date['get' + name]();
  18742. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  18743. var get = uppercase(propPrefix + name);
  18744. return formats[get][value];
  18745. };
  18746. }
  18747. function timeZoneGetter(date, formats, offset) {
  18748. var zone = -1 * offset;
  18749. var paddedZone = (zone >= 0) ? "+" : "";
  18750. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  18751. padNumber(Math.abs(zone % 60), 2);
  18752. return paddedZone;
  18753. }
  18754. function getFirstThursdayOfYear(year) {
  18755. // 0 = index of January
  18756. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  18757. // 4 = index of Thursday (+1 to account for 1st = 5)
  18758. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  18759. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  18760. }
  18761. function getThursdayThisWeek(datetime) {
  18762. return new Date(datetime.getFullYear(), datetime.getMonth(),
  18763. // 4 = index of Thursday
  18764. datetime.getDate() + (4 - datetime.getDay()));
  18765. }
  18766. function weekGetter(size) {
  18767. return function(date) {
  18768. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  18769. thisThurs = getThursdayThisWeek(date);
  18770. var diff = +thisThurs - +firstThurs,
  18771. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  18772. return padNumber(result, size);
  18773. };
  18774. }
  18775. function ampmGetter(date, formats) {
  18776. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  18777. }
  18778. function eraGetter(date, formats) {
  18779. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  18780. }
  18781. function longEraGetter(date, formats) {
  18782. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  18783. }
  18784. var DATE_FORMATS = {
  18785. yyyy: dateGetter('FullYear', 4, 0, false, true),
  18786. yy: dateGetter('FullYear', 2, 0, true, true),
  18787. y: dateGetter('FullYear', 1, 0, false, true),
  18788. MMMM: dateStrGetter('Month'),
  18789. MMM: dateStrGetter('Month', true),
  18790. MM: dateGetter('Month', 2, 1),
  18791. M: dateGetter('Month', 1, 1),
  18792. LLLL: dateStrGetter('Month', false, true),
  18793. dd: dateGetter('Date', 2),
  18794. d: dateGetter('Date', 1),
  18795. HH: dateGetter('Hours', 2),
  18796. H: dateGetter('Hours', 1),
  18797. hh: dateGetter('Hours', 2, -12),
  18798. h: dateGetter('Hours', 1, -12),
  18799. mm: dateGetter('Minutes', 2),
  18800. m: dateGetter('Minutes', 1),
  18801. ss: dateGetter('Seconds', 2),
  18802. s: dateGetter('Seconds', 1),
  18803. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  18804. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  18805. sss: dateGetter('Milliseconds', 3),
  18806. EEEE: dateStrGetter('Day'),
  18807. EEE: dateStrGetter('Day', true),
  18808. a: ampmGetter,
  18809. Z: timeZoneGetter,
  18810. ww: weekGetter(2),
  18811. w: weekGetter(1),
  18812. G: eraGetter,
  18813. GG: eraGetter,
  18814. GGG: eraGetter,
  18815. GGGG: longEraGetter
  18816. };
  18817. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  18818. NUMBER_STRING = /^\-?\d+$/;
  18819. /**
  18820. * @ngdoc filter
  18821. * @name date
  18822. * @kind function
  18823. *
  18824. * @description
  18825. * Formats `date` to a string based on the requested `format`.
  18826. *
  18827. * `format` string can be composed of the following elements:
  18828. *
  18829. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  18830. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  18831. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  18832. * * `'MMMM'`: Month in year (January-December)
  18833. * * `'MMM'`: Month in year (Jan-Dec)
  18834. * * `'MM'`: Month in year, padded (01-12)
  18835. * * `'M'`: Month in year (1-12)
  18836. * * `'LLLL'`: Stand-alone month in year (January-December)
  18837. * * `'dd'`: Day in month, padded (01-31)
  18838. * * `'d'`: Day in month (1-31)
  18839. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  18840. * * `'EEE'`: Day in Week, (Sun-Sat)
  18841. * * `'HH'`: Hour in day, padded (00-23)
  18842. * * `'H'`: Hour in day (0-23)
  18843. * * `'hh'`: Hour in AM/PM, padded (01-12)
  18844. * * `'h'`: Hour in AM/PM, (1-12)
  18845. * * `'mm'`: Minute in hour, padded (00-59)
  18846. * * `'m'`: Minute in hour (0-59)
  18847. * * `'ss'`: Second in minute, padded (00-59)
  18848. * * `'s'`: Second in minute (0-59)
  18849. * * `'sss'`: Millisecond in second, padded (000-999)
  18850. * * `'a'`: AM/PM marker
  18851. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  18852. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  18853. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  18854. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  18855. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  18856. *
  18857. * `format` string can also be one of the following predefined
  18858. * {@link guide/i18n localizable formats}:
  18859. *
  18860. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  18861. * (e.g. Sep 3, 2010 12:05:08 PM)
  18862. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  18863. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  18864. * (e.g. Friday, September 3, 2010)
  18865. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  18866. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  18867. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  18868. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  18869. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  18870. *
  18871. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  18872. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  18873. * (e.g. `"h 'o''clock'"`).
  18874. *
  18875. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  18876. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  18877. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  18878. * specified in the string input, the time is considered to be in the local timezone.
  18879. * @param {string=} format Formatting rules (see Description). If not specified,
  18880. * `mediumDate` is used.
  18881. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  18882. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  18883. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  18884. * If not specified, the timezone of the browser will be used.
  18885. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  18886. *
  18887. * @example
  18888. <example>
  18889. <file name="index.html">
  18890. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  18891. <span>{{1288323623006 | date:'medium'}}</span><br>
  18892. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  18893. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  18894. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  18895. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  18896. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  18897. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  18898. </file>
  18899. <file name="protractor.js" type="protractor">
  18900. it('should format date', function() {
  18901. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  18902. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  18903. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  18904. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  18905. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  18906. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  18907. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  18908. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  18909. });
  18910. </file>
  18911. </example>
  18912. */
  18913. dateFilter.$inject = ['$locale'];
  18914. function dateFilter($locale) {
  18915. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  18916. // 1 2 3 4 5 6 7 8 9 10 11
  18917. function jsonStringToDate(string) {
  18918. var match;
  18919. if (match = string.match(R_ISO8601_STR)) {
  18920. var date = new Date(0),
  18921. tzHour = 0,
  18922. tzMin = 0,
  18923. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  18924. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  18925. if (match[9]) {
  18926. tzHour = toInt(match[9] + match[10]);
  18927. tzMin = toInt(match[9] + match[11]);
  18928. }
  18929. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  18930. var h = toInt(match[4] || 0) - tzHour;
  18931. var m = toInt(match[5] || 0) - tzMin;
  18932. var s = toInt(match[6] || 0);
  18933. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  18934. timeSetter.call(date, h, m, s, ms);
  18935. return date;
  18936. }
  18937. return string;
  18938. }
  18939. return function(date, format, timezone) {
  18940. var text = '',
  18941. parts = [],
  18942. fn, match;
  18943. format = format || 'mediumDate';
  18944. format = $locale.DATETIME_FORMATS[format] || format;
  18945. if (isString(date)) {
  18946. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  18947. }
  18948. if (isNumber(date)) {
  18949. date = new Date(date);
  18950. }
  18951. if (!isDate(date) || !isFinite(date.getTime())) {
  18952. return date;
  18953. }
  18954. while (format) {
  18955. match = DATE_FORMATS_SPLIT.exec(format);
  18956. if (match) {
  18957. parts = concat(parts, match, 1);
  18958. format = parts.pop();
  18959. } else {
  18960. parts.push(format);
  18961. format = null;
  18962. }
  18963. }
  18964. var dateTimezoneOffset = date.getTimezoneOffset();
  18965. if (timezone) {
  18966. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  18967. date = convertTimezoneToLocal(date, timezone, true);
  18968. }
  18969. forEach(parts, function(value) {
  18970. fn = DATE_FORMATS[value];
  18971. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  18972. : value === "''" ? "'" : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  18973. });
  18974. return text;
  18975. };
  18976. }
  18977. /**
  18978. * @ngdoc filter
  18979. * @name json
  18980. * @kind function
  18981. *
  18982. * @description
  18983. * Allows you to convert a JavaScript object into JSON string.
  18984. *
  18985. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  18986. * the binding is automatically converted to JSON.
  18987. *
  18988. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  18989. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  18990. * @returns {string} JSON string.
  18991. *
  18992. *
  18993. * @example
  18994. <example>
  18995. <file name="index.html">
  18996. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  18997. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  18998. </file>
  18999. <file name="protractor.js" type="protractor">
  19000. it('should jsonify filtered objects', function() {
  19001. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  19002. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  19003. });
  19004. </file>
  19005. </example>
  19006. *
  19007. */
  19008. function jsonFilter() {
  19009. return function(object, spacing) {
  19010. if (isUndefined(spacing)) {
  19011. spacing = 2;
  19012. }
  19013. return toJson(object, spacing);
  19014. };
  19015. }
  19016. /**
  19017. * @ngdoc filter
  19018. * @name lowercase
  19019. * @kind function
  19020. * @description
  19021. * Converts string to lowercase.
  19022. * @see angular.lowercase
  19023. */
  19024. var lowercaseFilter = valueFn(lowercase);
  19025. /**
  19026. * @ngdoc filter
  19027. * @name uppercase
  19028. * @kind function
  19029. * @description
  19030. * Converts string to uppercase.
  19031. * @see angular.uppercase
  19032. */
  19033. var uppercaseFilter = valueFn(uppercase);
  19034. /**
  19035. * @ngdoc filter
  19036. * @name limitTo
  19037. * @kind function
  19038. *
  19039. * @description
  19040. * Creates a new array or string containing only a specified number of elements. The elements are
  19041. * taken from either the beginning or the end of the source array, string or number, as specified by
  19042. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  19043. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  19044. * it is converted to a string.
  19045. *
  19046. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  19047. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  19048. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  19049. * If the number is negative, `limit` number of items from the end of the source array/string
  19050. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  19051. * the input will be returned unchanged.
  19052. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  19053. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  19054. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  19055. * less than `limit` elements.
  19056. *
  19057. * @example
  19058. <example module="limitToExample">
  19059. <file name="index.html">
  19060. <script>
  19061. angular.module('limitToExample', [])
  19062. .controller('ExampleController', ['$scope', function($scope) {
  19063. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  19064. $scope.letters = "abcdefghi";
  19065. $scope.longNumber = 2345432342;
  19066. $scope.numLimit = 3;
  19067. $scope.letterLimit = 3;
  19068. $scope.longNumberLimit = 3;
  19069. }]);
  19070. </script>
  19071. <div ng-controller="ExampleController">
  19072. <label>
  19073. Limit {{numbers}} to:
  19074. <input type="number" step="1" ng-model="numLimit">
  19075. </label>
  19076. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  19077. <label>
  19078. Limit {{letters}} to:
  19079. <input type="number" step="1" ng-model="letterLimit">
  19080. </label>
  19081. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  19082. <label>
  19083. Limit {{longNumber}} to:
  19084. <input type="number" step="1" ng-model="longNumberLimit">
  19085. </label>
  19086. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  19087. </div>
  19088. </file>
  19089. <file name="protractor.js" type="protractor">
  19090. var numLimitInput = element(by.model('numLimit'));
  19091. var letterLimitInput = element(by.model('letterLimit'));
  19092. var longNumberLimitInput = element(by.model('longNumberLimit'));
  19093. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  19094. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  19095. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  19096. it('should limit the number array to first three items', function() {
  19097. expect(numLimitInput.getAttribute('value')).toBe('3');
  19098. expect(letterLimitInput.getAttribute('value')).toBe('3');
  19099. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  19100. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  19101. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  19102. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  19103. });
  19104. // There is a bug in safari and protractor that doesn't like the minus key
  19105. // it('should update the output when -3 is entered', function() {
  19106. // numLimitInput.clear();
  19107. // numLimitInput.sendKeys('-3');
  19108. // letterLimitInput.clear();
  19109. // letterLimitInput.sendKeys('-3');
  19110. // longNumberLimitInput.clear();
  19111. // longNumberLimitInput.sendKeys('-3');
  19112. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  19113. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  19114. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  19115. // });
  19116. it('should not exceed the maximum size of input array', function() {
  19117. numLimitInput.clear();
  19118. numLimitInput.sendKeys('100');
  19119. letterLimitInput.clear();
  19120. letterLimitInput.sendKeys('100');
  19121. longNumberLimitInput.clear();
  19122. longNumberLimitInput.sendKeys('100');
  19123. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  19124. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  19125. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  19126. });
  19127. </file>
  19128. </example>
  19129. */
  19130. function limitToFilter() {
  19131. return function(input, limit, begin) {
  19132. if (Math.abs(Number(limit)) === Infinity) {
  19133. limit = Number(limit);
  19134. } else {
  19135. limit = toInt(limit);
  19136. }
  19137. if (isNaN(limit)) return input;
  19138. if (isNumber(input)) input = input.toString();
  19139. if (!isArrayLike(input)) return input;
  19140. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  19141. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  19142. if (limit >= 0) {
  19143. return sliceFn(input, begin, begin + limit);
  19144. } else {
  19145. if (begin === 0) {
  19146. return sliceFn(input, limit, input.length);
  19147. } else {
  19148. return sliceFn(input, Math.max(0, begin + limit), begin);
  19149. }
  19150. }
  19151. };
  19152. }
  19153. function sliceFn(input, begin, end) {
  19154. if (isString(input)) return input.slice(begin, end);
  19155. return slice.call(input, begin, end);
  19156. }
  19157. /**
  19158. * @ngdoc filter
  19159. * @name orderBy
  19160. * @kind function
  19161. *
  19162. * @description
  19163. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  19164. * function based on the values computed using the `expression` predicate.
  19165. *
  19166. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  19167. * `[{id: 'bar'}, {id: 'foo'}]`.
  19168. *
  19169. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  19170. * String, etc).
  19171. *
  19172. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  19173. * for the preceeding one. The `expression` is evaluated against each item and the output is used
  19174. * for comparing with other items.
  19175. *
  19176. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  19177. * ascending order.
  19178. *
  19179. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  19180. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  19181. * strings alphabetically).
  19182. *
  19183. * ### Under the hood
  19184. *
  19185. * Ordering the specified `collection` happens in two phases:
  19186. *
  19187. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  19188. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  19189. * through a predicate that extracts the value of the `label` property, would be transformed to:
  19190. * ```
  19191. * {
  19192. * value: 'foo',
  19193. * type: 'string',
  19194. * index: ...
  19195. * }
  19196. * ```
  19197. * 2. The comparator function is used to sort the items, based on the derived values, types and
  19198. * indices.
  19199. *
  19200. * If you use a custom comparator, it will be called with pairs of objects of the form
  19201. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  19202. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  19203. * second, or `1` otherwise.
  19204. *
  19205. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  19206. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  19207. * dummy predicate that returns the item's index as `value`.
  19208. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  19209. *
  19210. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  19211. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  19212. * it to the comparator. The following rules govern the conversion:
  19213. *
  19214. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  19215. * used instead.<br />
  19216. * (If the object has a `valueOf()` method that returns another object, then the returned object
  19217. * will be used in subsequent steps.)
  19218. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  19219. * returns a primitive, its return value will be used instead.<br />
  19220. * (If the object has a `toString()` method that returns another object, then the returned object
  19221. * will be used in subsequent steps.)
  19222. * 3. No conversion; the object itself is used.
  19223. *
  19224. * ### The default comparator
  19225. *
  19226. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  19227. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  19228. * using their index in the original collection, and sorts values of different types by type.
  19229. *
  19230. * More specifically, it follows these steps to determine the relative order of items:
  19231. *
  19232. * 1. If the compared values are of different types, compare the types themselves alphabetically.
  19233. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  19234. * locale-insensitive way.
  19235. * 3. If both values are objects, compare their indices instead.
  19236. * 4. Otherwise, return:
  19237. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  19238. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  19239. * - `1`, otherwise.
  19240. *
  19241. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  19242. * saved as numbers and not strings.
  19243. *
  19244. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  19245. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  19246. * predicates) to be used by the comparator to determine the order of elements.
  19247. *
  19248. * Can be one of:
  19249. *
  19250. * - `Function`: A getter function. This function will be called with each item as argument and
  19251. * the return value will be used for sorting.
  19252. * - `string`: An Angular expression. This expression will be evaluated against each item and the
  19253. * result will be used for sorting. For example, use `'label'` to sort by a property called
  19254. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  19255. * property.<br />
  19256. * (The result of a constant expression is interpreted as a property name to be used for
  19257. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  19258. * property called `special name`.)<br />
  19259. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  19260. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  19261. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  19262. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  19263. * relative order of two items, the next predicate is used as a tie-breaker.
  19264. *
  19265. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  19266. *
  19267. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  19268. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  19269. * value pairs. If omitted, the built-in comparator will be used.
  19270. *
  19271. * @returns {Array} - The sorted array.
  19272. *
  19273. *
  19274. * @example
  19275. * ### Ordering a table with `ngRepeat`
  19276. *
  19277. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  19278. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  19279. * it defaults to the built-in comparator.
  19280. *
  19281. <example name="orderBy-static" module="orderByExample1">
  19282. <file name="index.html">
  19283. <div ng-controller="ExampleController">
  19284. <table class="friends">
  19285. <tr>
  19286. <th>Name</th>
  19287. <th>Phone Number</th>
  19288. <th>Age</th>
  19289. </tr>
  19290. <tr ng-repeat="friend in friends | orderBy:'-age'">
  19291. <td>{{friend.name}}</td>
  19292. <td>{{friend.phone}}</td>
  19293. <td>{{friend.age}}</td>
  19294. </tr>
  19295. </table>
  19296. </div>
  19297. </file>
  19298. <file name="script.js">
  19299. angular.module('orderByExample1', [])
  19300. .controller('ExampleController', ['$scope', function($scope) {
  19301. $scope.friends = [
  19302. {name: 'John', phone: '555-1212', age: 10},
  19303. {name: 'Mary', phone: '555-9876', age: 19},
  19304. {name: 'Mike', phone: '555-4321', age: 21},
  19305. {name: 'Adam', phone: '555-5678', age: 35},
  19306. {name: 'Julie', phone: '555-8765', age: 29}
  19307. ];
  19308. }]);
  19309. </file>
  19310. <file name="style.css">
  19311. .friends {
  19312. border-collapse: collapse;
  19313. }
  19314. .friends th {
  19315. border-bottom: 1px solid;
  19316. }
  19317. .friends td, .friends th {
  19318. border-left: 1px solid;
  19319. padding: 5px 10px;
  19320. }
  19321. .friends td:first-child, .friends th:first-child {
  19322. border-left: none;
  19323. }
  19324. </file>
  19325. <file name="protractor.js" type="protractor">
  19326. // Element locators
  19327. var names = element.all(by.repeater('friends').column('friend.name'));
  19328. it('should sort friends by age in reverse order', function() {
  19329. expect(names.get(0).getText()).toBe('Adam');
  19330. expect(names.get(1).getText()).toBe('Julie');
  19331. expect(names.get(2).getText()).toBe('Mike');
  19332. expect(names.get(3).getText()).toBe('Mary');
  19333. expect(names.get(4).getText()).toBe('John');
  19334. });
  19335. </file>
  19336. </example>
  19337. * <hr />
  19338. *
  19339. * @example
  19340. * ### Changing parameters dynamically
  19341. *
  19342. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  19343. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  19344. *
  19345. <example name="orderBy-dynamic" module="orderByExample2">
  19346. <file name="index.html">
  19347. <div ng-controller="ExampleController">
  19348. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19349. <hr/>
  19350. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  19351. <hr/>
  19352. <table class="friends">
  19353. <tr>
  19354. <th>
  19355. <button ng-click="sortBy('name')">Name</button>
  19356. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19357. </th>
  19358. <th>
  19359. <button ng-click="sortBy('phone')">Phone Number</button>
  19360. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19361. </th>
  19362. <th>
  19363. <button ng-click="sortBy('age')">Age</button>
  19364. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19365. </th>
  19366. </tr>
  19367. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  19368. <td>{{friend.name}}</td>
  19369. <td>{{friend.phone}}</td>
  19370. <td>{{friend.age}}</td>
  19371. </tr>
  19372. </table>
  19373. </div>
  19374. </file>
  19375. <file name="script.js">
  19376. angular.module('orderByExample2', [])
  19377. .controller('ExampleController', ['$scope', function($scope) {
  19378. var friends = [
  19379. {name: 'John', phone: '555-1212', age: 10},
  19380. {name: 'Mary', phone: '555-9876', age: 19},
  19381. {name: 'Mike', phone: '555-4321', age: 21},
  19382. {name: 'Adam', phone: '555-5678', age: 35},
  19383. {name: 'Julie', phone: '555-8765', age: 29}
  19384. ];
  19385. $scope.propertyName = 'age';
  19386. $scope.reverse = true;
  19387. $scope.friends = friends;
  19388. $scope.sortBy = function(propertyName) {
  19389. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  19390. $scope.propertyName = propertyName;
  19391. };
  19392. }]);
  19393. </file>
  19394. <file name="style.css">
  19395. .friends {
  19396. border-collapse: collapse;
  19397. }
  19398. .friends th {
  19399. border-bottom: 1px solid;
  19400. }
  19401. .friends td, .friends th {
  19402. border-left: 1px solid;
  19403. padding: 5px 10px;
  19404. }
  19405. .friends td:first-child, .friends th:first-child {
  19406. border-left: none;
  19407. }
  19408. .sortorder:after {
  19409. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19410. }
  19411. .sortorder.reverse:after {
  19412. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19413. }
  19414. </file>
  19415. <file name="protractor.js" type="protractor">
  19416. // Element locators
  19417. var unsortButton = element(by.partialButtonText('unsorted'));
  19418. var nameHeader = element(by.partialButtonText('Name'));
  19419. var phoneHeader = element(by.partialButtonText('Phone'));
  19420. var ageHeader = element(by.partialButtonText('Age'));
  19421. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19422. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19423. it('should sort friends by some property, when clicking on the column header', function() {
  19424. expect(firstName.getText()).toBe('Adam');
  19425. expect(lastName.getText()).toBe('John');
  19426. phoneHeader.click();
  19427. expect(firstName.getText()).toBe('John');
  19428. expect(lastName.getText()).toBe('Mary');
  19429. nameHeader.click();
  19430. expect(firstName.getText()).toBe('Adam');
  19431. expect(lastName.getText()).toBe('Mike');
  19432. ageHeader.click();
  19433. expect(firstName.getText()).toBe('John');
  19434. expect(lastName.getText()).toBe('Adam');
  19435. });
  19436. it('should sort friends in reverse order, when clicking on the same column', function() {
  19437. expect(firstName.getText()).toBe('Adam');
  19438. expect(lastName.getText()).toBe('John');
  19439. ageHeader.click();
  19440. expect(firstName.getText()).toBe('John');
  19441. expect(lastName.getText()).toBe('Adam');
  19442. ageHeader.click();
  19443. expect(firstName.getText()).toBe('Adam');
  19444. expect(lastName.getText()).toBe('John');
  19445. });
  19446. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19447. expect(firstName.getText()).toBe('Adam');
  19448. expect(lastName.getText()).toBe('John');
  19449. unsortButton.click();
  19450. expect(firstName.getText()).toBe('John');
  19451. expect(lastName.getText()).toBe('Julie');
  19452. });
  19453. </file>
  19454. </example>
  19455. * <hr />
  19456. *
  19457. * @example
  19458. * ### Using `orderBy` inside a controller
  19459. *
  19460. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  19461. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  19462. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  19463. *
  19464. <example name="orderBy-call-manually" module="orderByExample3">
  19465. <file name="index.html">
  19466. <div ng-controller="ExampleController">
  19467. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19468. <hr/>
  19469. <button ng-click="sortBy(null)">Set to unsorted</button>
  19470. <hr/>
  19471. <table class="friends">
  19472. <tr>
  19473. <th>
  19474. <button ng-click="sortBy('name')">Name</button>
  19475. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19476. </th>
  19477. <th>
  19478. <button ng-click="sortBy('phone')">Phone Number</button>
  19479. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19480. </th>
  19481. <th>
  19482. <button ng-click="sortBy('age')">Age</button>
  19483. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19484. </th>
  19485. </tr>
  19486. <tr ng-repeat="friend in friends">
  19487. <td>{{friend.name}}</td>
  19488. <td>{{friend.phone}}</td>
  19489. <td>{{friend.age}}</td>
  19490. </tr>
  19491. </table>
  19492. </div>
  19493. </file>
  19494. <file name="script.js">
  19495. angular.module('orderByExample3', [])
  19496. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  19497. var friends = [
  19498. {name: 'John', phone: '555-1212', age: 10},
  19499. {name: 'Mary', phone: '555-9876', age: 19},
  19500. {name: 'Mike', phone: '555-4321', age: 21},
  19501. {name: 'Adam', phone: '555-5678', age: 35},
  19502. {name: 'Julie', phone: '555-8765', age: 29}
  19503. ];
  19504. $scope.propertyName = 'age';
  19505. $scope.reverse = true;
  19506. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19507. $scope.sortBy = function(propertyName) {
  19508. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  19509. ? !$scope.reverse : false;
  19510. $scope.propertyName = propertyName;
  19511. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19512. };
  19513. }]);
  19514. </file>
  19515. <file name="style.css">
  19516. .friends {
  19517. border-collapse: collapse;
  19518. }
  19519. .friends th {
  19520. border-bottom: 1px solid;
  19521. }
  19522. .friends td, .friends th {
  19523. border-left: 1px solid;
  19524. padding: 5px 10px;
  19525. }
  19526. .friends td:first-child, .friends th:first-child {
  19527. border-left: none;
  19528. }
  19529. .sortorder:after {
  19530. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19531. }
  19532. .sortorder.reverse:after {
  19533. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19534. }
  19535. </file>
  19536. <file name="protractor.js" type="protractor">
  19537. // Element locators
  19538. var unsortButton = element(by.partialButtonText('unsorted'));
  19539. var nameHeader = element(by.partialButtonText('Name'));
  19540. var phoneHeader = element(by.partialButtonText('Phone'));
  19541. var ageHeader = element(by.partialButtonText('Age'));
  19542. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19543. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19544. it('should sort friends by some property, when clicking on the column header', function() {
  19545. expect(firstName.getText()).toBe('Adam');
  19546. expect(lastName.getText()).toBe('John');
  19547. phoneHeader.click();
  19548. expect(firstName.getText()).toBe('John');
  19549. expect(lastName.getText()).toBe('Mary');
  19550. nameHeader.click();
  19551. expect(firstName.getText()).toBe('Adam');
  19552. expect(lastName.getText()).toBe('Mike');
  19553. ageHeader.click();
  19554. expect(firstName.getText()).toBe('John');
  19555. expect(lastName.getText()).toBe('Adam');
  19556. });
  19557. it('should sort friends in reverse order, when clicking on the same column', function() {
  19558. expect(firstName.getText()).toBe('Adam');
  19559. expect(lastName.getText()).toBe('John');
  19560. ageHeader.click();
  19561. expect(firstName.getText()).toBe('John');
  19562. expect(lastName.getText()).toBe('Adam');
  19563. ageHeader.click();
  19564. expect(firstName.getText()).toBe('Adam');
  19565. expect(lastName.getText()).toBe('John');
  19566. });
  19567. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19568. expect(firstName.getText()).toBe('Adam');
  19569. expect(lastName.getText()).toBe('John');
  19570. unsortButton.click();
  19571. expect(firstName.getText()).toBe('John');
  19572. expect(lastName.getText()).toBe('Julie');
  19573. });
  19574. </file>
  19575. </example>
  19576. * <hr />
  19577. *
  19578. * @example
  19579. * ### Using a custom comparator
  19580. *
  19581. * If you have very specific requirements about the way items are sorted, you can pass your own
  19582. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  19583. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  19584. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  19585. *
  19586. <example name="orderBy-custom-comparator" module="orderByExample4">
  19587. <file name="index.html">
  19588. <div ng-controller="ExampleController">
  19589. <div class="friends-container custom-comparator">
  19590. <h3>Locale-sensitive Comparator</h3>
  19591. <table class="friends">
  19592. <tr>
  19593. <th>Name</th>
  19594. <th>Favorite Letter</th>
  19595. </tr>
  19596. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  19597. <td>{{friend.name}}</td>
  19598. <td>{{friend.favoriteLetter}}</td>
  19599. </tr>
  19600. </table>
  19601. </div>
  19602. <div class="friends-container default-comparator">
  19603. <h3>Default Comparator</h3>
  19604. <table class="friends">
  19605. <tr>
  19606. <th>Name</th>
  19607. <th>Favorite Letter</th>
  19608. </tr>
  19609. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  19610. <td>{{friend.name}}</td>
  19611. <td>{{friend.favoriteLetter}}</td>
  19612. </tr>
  19613. </table>
  19614. </div>
  19615. </div>
  19616. </file>
  19617. <file name="script.js">
  19618. angular.module('orderByExample4', [])
  19619. .controller('ExampleController', ['$scope', function($scope) {
  19620. $scope.friends = [
  19621. {name: 'John', favoriteLetter: 'Ä'},
  19622. {name: 'Mary', favoriteLetter: 'Ü'},
  19623. {name: 'Mike', favoriteLetter: 'Ö'},
  19624. {name: 'Adam', favoriteLetter: 'H'},
  19625. {name: 'Julie', favoriteLetter: 'Z'}
  19626. ];
  19627. $scope.localeSensitiveComparator = function(v1, v2) {
  19628. // If we don't get strings, just compare by index
  19629. if (v1.type !== 'string' || v2.type !== 'string') {
  19630. return (v1.index < v2.index) ? -1 : 1;
  19631. }
  19632. // Compare strings alphabetically, taking locale into account
  19633. return v1.value.localeCompare(v2.value);
  19634. };
  19635. }]);
  19636. </file>
  19637. <file name="style.css">
  19638. .friends-container {
  19639. display: inline-block;
  19640. margin: 0 30px;
  19641. }
  19642. .friends {
  19643. border-collapse: collapse;
  19644. }
  19645. .friends th {
  19646. border-bottom: 1px solid;
  19647. }
  19648. .friends td, .friends th {
  19649. border-left: 1px solid;
  19650. padding: 5px 10px;
  19651. }
  19652. .friends td:first-child, .friends th:first-child {
  19653. border-left: none;
  19654. }
  19655. </file>
  19656. <file name="protractor.js" type="protractor">
  19657. // Element locators
  19658. var container = element(by.css('.custom-comparator'));
  19659. var names = container.all(by.repeater('friends').column('friend.name'));
  19660. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  19661. expect(names.get(0).getText()).toBe('John');
  19662. expect(names.get(1).getText()).toBe('Adam');
  19663. expect(names.get(2).getText()).toBe('Mike');
  19664. expect(names.get(3).getText()).toBe('Mary');
  19665. expect(names.get(4).getText()).toBe('Julie');
  19666. });
  19667. </file>
  19668. </example>
  19669. *
  19670. */
  19671. orderByFilter.$inject = ['$parse'];
  19672. function orderByFilter($parse) {
  19673. return function(array, sortPredicate, reverseOrder, compareFn) {
  19674. if (array == null) return array;
  19675. if (!isArrayLike(array)) {
  19676. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  19677. }
  19678. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  19679. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  19680. var predicates = processPredicates(sortPredicate);
  19681. var descending = reverseOrder ? -1 : 1;
  19682. // Define the `compare()` function. Use a default comparator if none is specified.
  19683. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  19684. // The next three lines are a version of a Swartzian Transform idiom from Perl
  19685. // (sometimes called the Decorate-Sort-Undecorate idiom)
  19686. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  19687. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  19688. compareValues.sort(doComparison);
  19689. array = compareValues.map(function(item) { return item.value; });
  19690. return array;
  19691. function getComparisonObject(value, index) {
  19692. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  19693. // This will be used to keep the sort stable when none of the input predicates can
  19694. // distinguish between two elements.
  19695. return {
  19696. value: value,
  19697. tieBreaker: {value: index, type: 'number', index: index},
  19698. predicateValues: predicates.map(function(predicate) {
  19699. return getPredicateValue(predicate.get(value), index);
  19700. })
  19701. };
  19702. }
  19703. function doComparison(v1, v2) {
  19704. for (var i = 0, ii = predicates.length; i < ii; i++) {
  19705. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  19706. if (result) {
  19707. return result * predicates[i].descending * descending;
  19708. }
  19709. }
  19710. return compare(v1.tieBreaker, v2.tieBreaker) * descending;
  19711. }
  19712. };
  19713. function processPredicates(sortPredicates) {
  19714. return sortPredicates.map(function(predicate) {
  19715. var descending = 1, get = identity;
  19716. if (isFunction(predicate)) {
  19717. get = predicate;
  19718. } else if (isString(predicate)) {
  19719. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  19720. descending = predicate.charAt(0) == '-' ? -1 : 1;
  19721. predicate = predicate.substring(1);
  19722. }
  19723. if (predicate !== '') {
  19724. get = $parse(predicate);
  19725. if (get.constant) {
  19726. var key = get();
  19727. get = function(value) { return value[key]; };
  19728. }
  19729. }
  19730. }
  19731. return {get: get, descending: descending};
  19732. });
  19733. }
  19734. function isPrimitive(value) {
  19735. switch (typeof value) {
  19736. case 'number': /* falls through */
  19737. case 'boolean': /* falls through */
  19738. case 'string':
  19739. return true;
  19740. default:
  19741. return false;
  19742. }
  19743. }
  19744. function objectValue(value) {
  19745. // If `valueOf` is a valid function use that
  19746. if (isFunction(value.valueOf)) {
  19747. value = value.valueOf();
  19748. if (isPrimitive(value)) return value;
  19749. }
  19750. // If `toString` is a valid function and not the one from `Object.prototype` use that
  19751. if (hasCustomToString(value)) {
  19752. value = value.toString();
  19753. if (isPrimitive(value)) return value;
  19754. }
  19755. return value;
  19756. }
  19757. function getPredicateValue(value, index) {
  19758. var type = typeof value;
  19759. if (value === null) {
  19760. type = 'string';
  19761. value = 'null';
  19762. } else if (type === 'object') {
  19763. value = objectValue(value);
  19764. }
  19765. return {value: value, type: type, index: index};
  19766. }
  19767. function defaultCompare(v1, v2) {
  19768. var result = 0;
  19769. var type1 = v1.type;
  19770. var type2 = v2.type;
  19771. if (type1 === type2) {
  19772. var value1 = v1.value;
  19773. var value2 = v2.value;
  19774. if (type1 === 'string') {
  19775. // Compare strings case-insensitively
  19776. value1 = value1.toLowerCase();
  19777. value2 = value2.toLowerCase();
  19778. } else if (type1 === 'object') {
  19779. // For basic objects, use the position of the object
  19780. // in the collection instead of the value
  19781. if (isObject(value1)) value1 = v1.index;
  19782. if (isObject(value2)) value2 = v2.index;
  19783. }
  19784. if (value1 !== value2) {
  19785. result = value1 < value2 ? -1 : 1;
  19786. }
  19787. } else {
  19788. result = type1 < type2 ? -1 : 1;
  19789. }
  19790. return result;
  19791. }
  19792. }
  19793. function ngDirective(directive) {
  19794. if (isFunction(directive)) {
  19795. directive = {
  19796. link: directive
  19797. };
  19798. }
  19799. directive.restrict = directive.restrict || 'AC';
  19800. return valueFn(directive);
  19801. }
  19802. /**
  19803. * @ngdoc directive
  19804. * @name a
  19805. * @restrict E
  19806. *
  19807. * @description
  19808. * Modifies the default behavior of the html A tag so that the default action is prevented when
  19809. * the href attribute is empty.
  19810. *
  19811. * This change permits the easy creation of action links with the `ngClick` directive
  19812. * without changing the location or causing page reloads, e.g.:
  19813. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  19814. */
  19815. var htmlAnchorDirective = valueFn({
  19816. restrict: 'E',
  19817. compile: function(element, attr) {
  19818. if (!attr.href && !attr.xlinkHref) {
  19819. return function(scope, element) {
  19820. // If the linked element is not an anchor tag anymore, do nothing
  19821. if (element[0].nodeName.toLowerCase() !== 'a') return;
  19822. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  19823. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  19824. 'xlink:href' : 'href';
  19825. element.on('click', function(event) {
  19826. // if we have no href url, then don't navigate anywhere.
  19827. if (!element.attr(href)) {
  19828. event.preventDefault();
  19829. }
  19830. });
  19831. };
  19832. }
  19833. }
  19834. });
  19835. /**
  19836. * @ngdoc directive
  19837. * @name ngHref
  19838. * @restrict A
  19839. * @priority 99
  19840. *
  19841. * @description
  19842. * Using Angular markup like `{{hash}}` in an href attribute will
  19843. * make the link go to the wrong URL if the user clicks it before
  19844. * Angular has a chance to replace the `{{hash}}` markup with its
  19845. * value. Until Angular replaces the markup the link will be broken
  19846. * and will most likely return a 404 error. The `ngHref` directive
  19847. * solves this problem.
  19848. *
  19849. * The wrong way to write it:
  19850. * ```html
  19851. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  19852. * ```
  19853. *
  19854. * The correct way to write it:
  19855. * ```html
  19856. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  19857. * ```
  19858. *
  19859. * @element A
  19860. * @param {template} ngHref any string which can contain `{{}}` markup.
  19861. *
  19862. * @example
  19863. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  19864. * in links and their different behaviors:
  19865. <example>
  19866. <file name="index.html">
  19867. <input ng-model="value" /><br />
  19868. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  19869. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  19870. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  19871. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  19872. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  19873. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  19874. </file>
  19875. <file name="protractor.js" type="protractor">
  19876. it('should execute ng-click but not reload when href without value', function() {
  19877. element(by.id('link-1')).click();
  19878. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  19879. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  19880. });
  19881. it('should execute ng-click but not reload when href empty string', function() {
  19882. element(by.id('link-2')).click();
  19883. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  19884. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  19885. });
  19886. it('should execute ng-click and change url when ng-href specified', function() {
  19887. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  19888. element(by.id('link-3')).click();
  19889. // At this point, we navigate away from an Angular page, so we need
  19890. // to use browser.driver to get the base webdriver.
  19891. browser.wait(function() {
  19892. return browser.driver.getCurrentUrl().then(function(url) {
  19893. return url.match(/\/123$/);
  19894. });
  19895. }, 5000, 'page should navigate to /123');
  19896. });
  19897. it('should execute ng-click but not reload when href empty string and name specified', function() {
  19898. element(by.id('link-4')).click();
  19899. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  19900. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  19901. });
  19902. it('should execute ng-click but not reload when no href but name specified', function() {
  19903. element(by.id('link-5')).click();
  19904. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  19905. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  19906. });
  19907. it('should only change url when only ng-href', function() {
  19908. element(by.model('value')).clear();
  19909. element(by.model('value')).sendKeys('6');
  19910. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  19911. element(by.id('link-6')).click();
  19912. // At this point, we navigate away from an Angular page, so we need
  19913. // to use browser.driver to get the base webdriver.
  19914. browser.wait(function() {
  19915. return browser.driver.getCurrentUrl().then(function(url) {
  19916. return url.match(/\/6$/);
  19917. });
  19918. }, 5000, 'page should navigate to /6');
  19919. });
  19920. </file>
  19921. </example>
  19922. */
  19923. /**
  19924. * @ngdoc directive
  19925. * @name ngSrc
  19926. * @restrict A
  19927. * @priority 99
  19928. *
  19929. * @description
  19930. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  19931. * work right: The browser will fetch from the URL with the literal
  19932. * text `{{hash}}` until Angular replaces the expression inside
  19933. * `{{hash}}`. The `ngSrc` directive solves this problem.
  19934. *
  19935. * The buggy way to write it:
  19936. * ```html
  19937. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  19938. * ```
  19939. *
  19940. * The correct way to write it:
  19941. * ```html
  19942. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  19943. * ```
  19944. *
  19945. * @element IMG
  19946. * @param {template} ngSrc any string which can contain `{{}}` markup.
  19947. */
  19948. /**
  19949. * @ngdoc directive
  19950. * @name ngSrcset
  19951. * @restrict A
  19952. * @priority 99
  19953. *
  19954. * @description
  19955. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  19956. * work right: The browser will fetch from the URL with the literal
  19957. * text `{{hash}}` until Angular replaces the expression inside
  19958. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  19959. *
  19960. * The buggy way to write it:
  19961. * ```html
  19962. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  19963. * ```
  19964. *
  19965. * The correct way to write it:
  19966. * ```html
  19967. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  19968. * ```
  19969. *
  19970. * @element IMG
  19971. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  19972. */
  19973. /**
  19974. * @ngdoc directive
  19975. * @name ngDisabled
  19976. * @restrict A
  19977. * @priority 100
  19978. *
  19979. * @description
  19980. *
  19981. * This directive sets the `disabled` attribute on the element if the
  19982. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  19983. *
  19984. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  19985. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19986. *
  19987. * @example
  19988. <example>
  19989. <file name="index.html">
  19990. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  19991. <button ng-model="button" ng-disabled="checked">Button</button>
  19992. </file>
  19993. <file name="protractor.js" type="protractor">
  19994. it('should toggle button', function() {
  19995. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  19996. element(by.model('checked')).click();
  19997. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  19998. });
  19999. </file>
  20000. </example>
  20001. *
  20002. * @element INPUT
  20003. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  20004. * then the `disabled` attribute will be set on the element
  20005. */
  20006. /**
  20007. * @ngdoc directive
  20008. * @name ngChecked
  20009. * @restrict A
  20010. * @priority 100
  20011. *
  20012. * @description
  20013. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  20014. *
  20015. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  20016. * as this can lead to unexpected behavior.
  20017. *
  20018. * A special directive is necessary because we cannot use interpolation inside the `checked`
  20019. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20020. *
  20021. * @example
  20022. <example>
  20023. <file name="index.html">
  20024. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  20025. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  20026. </file>
  20027. <file name="protractor.js" type="protractor">
  20028. it('should check both checkBoxes', function() {
  20029. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  20030. element(by.model('master')).click();
  20031. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  20032. });
  20033. </file>
  20034. </example>
  20035. *
  20036. * @element INPUT
  20037. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  20038. * then the `checked` attribute will be set on the element
  20039. */
  20040. /**
  20041. * @ngdoc directive
  20042. * @name ngReadonly
  20043. * @restrict A
  20044. * @priority 100
  20045. *
  20046. * @description
  20047. *
  20048. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  20049. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  20050. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  20051. *
  20052. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  20053. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20054. *
  20055. * @example
  20056. <example>
  20057. <file name="index.html">
  20058. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  20059. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  20060. </file>
  20061. <file name="protractor.js" type="protractor">
  20062. it('should toggle readonly attr', function() {
  20063. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  20064. element(by.model('checked')).click();
  20065. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  20066. });
  20067. </file>
  20068. </example>
  20069. *
  20070. * @element INPUT
  20071. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  20072. * then special attribute "readonly" will be set on the element
  20073. */
  20074. /**
  20075. * @ngdoc directive
  20076. * @name ngSelected
  20077. * @restrict A
  20078. * @priority 100
  20079. *
  20080. * @description
  20081. *
  20082. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  20083. *
  20084. * A special directive is necessary because we cannot use interpolation inside the `selected`
  20085. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20086. *
  20087. * <div class="alert alert-warning">
  20088. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  20089. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  20090. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  20091. * selected options.
  20092. * </div>
  20093. *
  20094. * @example
  20095. <example>
  20096. <file name="index.html">
  20097. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  20098. <select aria-label="ngSelected demo">
  20099. <option>Hello!</option>
  20100. <option id="greet" ng-selected="selected">Greetings!</option>
  20101. </select>
  20102. </file>
  20103. <file name="protractor.js" type="protractor">
  20104. it('should select Greetings!', function() {
  20105. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  20106. element(by.model('selected')).click();
  20107. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  20108. });
  20109. </file>
  20110. </example>
  20111. *
  20112. * @element OPTION
  20113. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  20114. * then special attribute "selected" will be set on the element
  20115. */
  20116. /**
  20117. * @ngdoc directive
  20118. * @name ngOpen
  20119. * @restrict A
  20120. * @priority 100
  20121. *
  20122. * @description
  20123. *
  20124. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  20125. *
  20126. * A special directive is necessary because we cannot use interpolation inside the `open`
  20127. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20128. *
  20129. * ## A note about browser compatibility
  20130. *
  20131. * Edge, Firefox, and Internet Explorer do not support the `details` element, it is
  20132. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  20133. *
  20134. * @example
  20135. <example>
  20136. <file name="index.html">
  20137. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  20138. <details id="details" ng-open="open">
  20139. <summary>Show/Hide me</summary>
  20140. </details>
  20141. </file>
  20142. <file name="protractor.js" type="protractor">
  20143. it('should toggle open', function() {
  20144. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  20145. element(by.model('open')).click();
  20146. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  20147. });
  20148. </file>
  20149. </example>
  20150. *
  20151. * @element DETAILS
  20152. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  20153. * then special attribute "open" will be set on the element
  20154. */
  20155. var ngAttributeAliasDirectives = {};
  20156. // boolean attrs are evaluated
  20157. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  20158. // binding to multiple is not supported
  20159. if (propName == "multiple") return;
  20160. function defaultLinkFn(scope, element, attr) {
  20161. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  20162. attr.$set(attrName, !!value);
  20163. });
  20164. }
  20165. var normalized = directiveNormalize('ng-' + attrName);
  20166. var linkFn = defaultLinkFn;
  20167. if (propName === 'checked') {
  20168. linkFn = function(scope, element, attr) {
  20169. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  20170. if (attr.ngModel !== attr[normalized]) {
  20171. defaultLinkFn(scope, element, attr);
  20172. }
  20173. };
  20174. }
  20175. ngAttributeAliasDirectives[normalized] = function() {
  20176. return {
  20177. restrict: 'A',
  20178. priority: 100,
  20179. link: linkFn
  20180. };
  20181. };
  20182. });
  20183. // aliased input attrs are evaluated
  20184. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  20185. ngAttributeAliasDirectives[ngAttr] = function() {
  20186. return {
  20187. priority: 100,
  20188. link: function(scope, element, attr) {
  20189. //special case ngPattern when a literal regular expression value
  20190. //is used as the expression (this way we don't have to watch anything).
  20191. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  20192. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  20193. if (match) {
  20194. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  20195. return;
  20196. }
  20197. }
  20198. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  20199. attr.$set(ngAttr, value);
  20200. });
  20201. }
  20202. };
  20203. };
  20204. });
  20205. // ng-src, ng-srcset, ng-href are interpolated
  20206. forEach(['src', 'srcset', 'href'], function(attrName) {
  20207. var normalized = directiveNormalize('ng-' + attrName);
  20208. ngAttributeAliasDirectives[normalized] = function() {
  20209. return {
  20210. priority: 99, // it needs to run after the attributes are interpolated
  20211. link: function(scope, element, attr) {
  20212. var propName = attrName,
  20213. name = attrName;
  20214. if (attrName === 'href' &&
  20215. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  20216. name = 'xlinkHref';
  20217. attr.$attr[name] = 'xlink:href';
  20218. propName = null;
  20219. }
  20220. attr.$observe(normalized, function(value) {
  20221. if (!value) {
  20222. if (attrName === 'href') {
  20223. attr.$set(name, null);
  20224. }
  20225. return;
  20226. }
  20227. attr.$set(name, value);
  20228. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  20229. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  20230. // to set the property as well to achieve the desired effect.
  20231. // we use attr[attrName] value since $set can sanitize the url.
  20232. if (msie && propName) element.prop(propName, attr[name]);
  20233. });
  20234. }
  20235. };
  20236. };
  20237. });
  20238. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  20239. */
  20240. var nullFormCtrl = {
  20241. $addControl: noop,
  20242. $$renameControl: nullFormRenameControl,
  20243. $removeControl: noop,
  20244. $setValidity: noop,
  20245. $setDirty: noop,
  20246. $setPristine: noop,
  20247. $setSubmitted: noop
  20248. },
  20249. SUBMITTED_CLASS = 'ng-submitted';
  20250. function nullFormRenameControl(control, name) {
  20251. control.$name = name;
  20252. }
  20253. /**
  20254. * @ngdoc type
  20255. * @name form.FormController
  20256. *
  20257. * @property {boolean} $pristine True if user has not interacted with the form yet.
  20258. * @property {boolean} $dirty True if user has already interacted with the form.
  20259. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  20260. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  20261. * @property {boolean} $pending True if at least one containing control or form is pending.
  20262. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  20263. *
  20264. * @property {Object} $error Is an object hash, containing references to controls or
  20265. * forms with failing validators, where:
  20266. *
  20267. * - keys are validation tokens (error names),
  20268. * - values are arrays of controls or forms that have a failing validator for given error name.
  20269. *
  20270. * Built-in validation tokens:
  20271. *
  20272. * - `email`
  20273. * - `max`
  20274. * - `maxlength`
  20275. * - `min`
  20276. * - `minlength`
  20277. * - `number`
  20278. * - `pattern`
  20279. * - `required`
  20280. * - `url`
  20281. * - `date`
  20282. * - `datetimelocal`
  20283. * - `time`
  20284. * - `week`
  20285. * - `month`
  20286. *
  20287. * @description
  20288. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  20289. * such as being valid/invalid or dirty/pristine.
  20290. *
  20291. * Each {@link ng.directive:form form} directive creates an instance
  20292. * of `FormController`.
  20293. *
  20294. */
  20295. //asks for $scope to fool the BC controller module
  20296. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  20297. function FormController(element, attrs, $scope, $animate, $interpolate) {
  20298. var form = this,
  20299. controls = [];
  20300. // init state
  20301. form.$error = {};
  20302. form.$$success = {};
  20303. form.$pending = undefined;
  20304. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  20305. form.$dirty = false;
  20306. form.$pristine = true;
  20307. form.$valid = true;
  20308. form.$invalid = false;
  20309. form.$submitted = false;
  20310. form.$$parentForm = nullFormCtrl;
  20311. /**
  20312. * @ngdoc method
  20313. * @name form.FormController#$rollbackViewValue
  20314. *
  20315. * @description
  20316. * Rollback all form controls pending updates to the `$modelValue`.
  20317. *
  20318. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20319. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  20320. * a form that uses `ng-model-options` to pend updates.
  20321. */
  20322. form.$rollbackViewValue = function() {
  20323. forEach(controls, function(control) {
  20324. control.$rollbackViewValue();
  20325. });
  20326. };
  20327. /**
  20328. * @ngdoc method
  20329. * @name form.FormController#$commitViewValue
  20330. *
  20331. * @description
  20332. * Commit all form controls pending updates to the `$modelValue`.
  20333. *
  20334. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20335. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  20336. * usually handles calling this in response to input events.
  20337. */
  20338. form.$commitViewValue = function() {
  20339. forEach(controls, function(control) {
  20340. control.$commitViewValue();
  20341. });
  20342. };
  20343. /**
  20344. * @ngdoc method
  20345. * @name form.FormController#$addControl
  20346. * @param {object} control control object, either a {@link form.FormController} or an
  20347. * {@link ngModel.NgModelController}
  20348. *
  20349. * @description
  20350. * Register a control with the form. Input elements using ngModelController do this automatically
  20351. * when they are linked.
  20352. *
  20353. * Note that the current state of the control will not be reflected on the new parent form. This
  20354. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  20355. * state.
  20356. *
  20357. * However, if the method is used programmatically, for example by adding dynamically created controls,
  20358. * or controls that have been previously removed without destroying their corresponding DOM element,
  20359. * it's the developers responsibility to make sure the current state propagates to the parent form.
  20360. *
  20361. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  20362. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  20363. */
  20364. form.$addControl = function(control) {
  20365. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  20366. // and not added to the scope. Now we throw an error.
  20367. assertNotHasOwnProperty(control.$name, 'input');
  20368. controls.push(control);
  20369. if (control.$name) {
  20370. form[control.$name] = control;
  20371. }
  20372. control.$$parentForm = form;
  20373. };
  20374. // Private API: rename a form control
  20375. form.$$renameControl = function(control, newName) {
  20376. var oldName = control.$name;
  20377. if (form[oldName] === control) {
  20378. delete form[oldName];
  20379. }
  20380. form[newName] = control;
  20381. control.$name = newName;
  20382. };
  20383. /**
  20384. * @ngdoc method
  20385. * @name form.FormController#$removeControl
  20386. * @param {object} control control object, either a {@link form.FormController} or an
  20387. * {@link ngModel.NgModelController}
  20388. *
  20389. * @description
  20390. * Deregister a control from the form.
  20391. *
  20392. * Input elements using ngModelController do this automatically when they are destroyed.
  20393. *
  20394. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  20395. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  20396. * different from case to case. For example, removing the only `$dirty` control from a form may or
  20397. * may not mean that the form is still `$dirty`.
  20398. */
  20399. form.$removeControl = function(control) {
  20400. if (control.$name && form[control.$name] === control) {
  20401. delete form[control.$name];
  20402. }
  20403. forEach(form.$pending, function(value, name) {
  20404. form.$setValidity(name, null, control);
  20405. });
  20406. forEach(form.$error, function(value, name) {
  20407. form.$setValidity(name, null, control);
  20408. });
  20409. forEach(form.$$success, function(value, name) {
  20410. form.$setValidity(name, null, control);
  20411. });
  20412. arrayRemove(controls, control);
  20413. control.$$parentForm = nullFormCtrl;
  20414. };
  20415. /**
  20416. * @ngdoc method
  20417. * @name form.FormController#$setValidity
  20418. *
  20419. * @description
  20420. * Sets the validity of a form control.
  20421. *
  20422. * This method will also propagate to parent forms.
  20423. */
  20424. addSetValidityMethod({
  20425. ctrl: this,
  20426. $element: element,
  20427. set: function(object, property, controller) {
  20428. var list = object[property];
  20429. if (!list) {
  20430. object[property] = [controller];
  20431. } else {
  20432. var index = list.indexOf(controller);
  20433. if (index === -1) {
  20434. list.push(controller);
  20435. }
  20436. }
  20437. },
  20438. unset: function(object, property, controller) {
  20439. var list = object[property];
  20440. if (!list) {
  20441. return;
  20442. }
  20443. arrayRemove(list, controller);
  20444. if (list.length === 0) {
  20445. delete object[property];
  20446. }
  20447. },
  20448. $animate: $animate
  20449. });
  20450. /**
  20451. * @ngdoc method
  20452. * @name form.FormController#$setDirty
  20453. *
  20454. * @description
  20455. * Sets the form to a dirty state.
  20456. *
  20457. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  20458. * state (ng-dirty class). This method will also propagate to parent forms.
  20459. */
  20460. form.$setDirty = function() {
  20461. $animate.removeClass(element, PRISTINE_CLASS);
  20462. $animate.addClass(element, DIRTY_CLASS);
  20463. form.$dirty = true;
  20464. form.$pristine = false;
  20465. form.$$parentForm.$setDirty();
  20466. };
  20467. /**
  20468. * @ngdoc method
  20469. * @name form.FormController#$setPristine
  20470. *
  20471. * @description
  20472. * Sets the form to its pristine state.
  20473. *
  20474. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  20475. * state (ng-pristine class). This method will also propagate to all the controls contained
  20476. * in this form.
  20477. *
  20478. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  20479. * saving or resetting it.
  20480. */
  20481. form.$setPristine = function() {
  20482. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  20483. form.$dirty = false;
  20484. form.$pristine = true;
  20485. form.$submitted = false;
  20486. forEach(controls, function(control) {
  20487. control.$setPristine();
  20488. });
  20489. };
  20490. /**
  20491. * @ngdoc method
  20492. * @name form.FormController#$setUntouched
  20493. *
  20494. * @description
  20495. * Sets the form to its untouched state.
  20496. *
  20497. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  20498. * untouched state (ng-untouched class).
  20499. *
  20500. * Setting a form controls back to their untouched state is often useful when setting the form
  20501. * back to its pristine state.
  20502. */
  20503. form.$setUntouched = function() {
  20504. forEach(controls, function(control) {
  20505. control.$setUntouched();
  20506. });
  20507. };
  20508. /**
  20509. * @ngdoc method
  20510. * @name form.FormController#$setSubmitted
  20511. *
  20512. * @description
  20513. * Sets the form to its submitted state.
  20514. */
  20515. form.$setSubmitted = function() {
  20516. $animate.addClass(element, SUBMITTED_CLASS);
  20517. form.$submitted = true;
  20518. form.$$parentForm.$setSubmitted();
  20519. };
  20520. }
  20521. /**
  20522. * @ngdoc directive
  20523. * @name ngForm
  20524. * @restrict EAC
  20525. *
  20526. * @description
  20527. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  20528. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  20529. * sub-group of controls needs to be determined.
  20530. *
  20531. * Note: the purpose of `ngForm` is to group controls,
  20532. * but not to be a replacement for the `<form>` tag with all of its capabilities
  20533. * (e.g. posting to the server, ...).
  20534. *
  20535. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  20536. * related scope, under this name.
  20537. *
  20538. */
  20539. /**
  20540. * @ngdoc directive
  20541. * @name form
  20542. * @restrict E
  20543. *
  20544. * @description
  20545. * Directive that instantiates
  20546. * {@link form.FormController FormController}.
  20547. *
  20548. * If the `name` attribute is specified, the form controller is published onto the current scope under
  20549. * this name.
  20550. *
  20551. * # Alias: {@link ng.directive:ngForm `ngForm`}
  20552. *
  20553. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  20554. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  20555. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  20556. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  20557. * of controls needs to be determined.
  20558. *
  20559. * # CSS classes
  20560. * - `ng-valid` is set if the form is valid.
  20561. * - `ng-invalid` is set if the form is invalid.
  20562. * - `ng-pending` is set if the form is pending.
  20563. * - `ng-pristine` is set if the form is pristine.
  20564. * - `ng-dirty` is set if the form is dirty.
  20565. * - `ng-submitted` is set if the form was submitted.
  20566. *
  20567. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  20568. *
  20569. *
  20570. * # Submitting a form and preventing the default action
  20571. *
  20572. * Since the role of forms in client-side Angular applications is different than in classical
  20573. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  20574. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  20575. * to handle the form submission in an application-specific way.
  20576. *
  20577. * For this reason, Angular prevents the default action (form submission to the server) unless the
  20578. * `<form>` element has an `action` attribute specified.
  20579. *
  20580. * You can use one of the following two ways to specify what javascript method should be called when
  20581. * a form is submitted:
  20582. *
  20583. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  20584. * - {@link ng.directive:ngClick ngClick} directive on the first
  20585. * button or input field of type submit (input[type=submit])
  20586. *
  20587. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  20588. * or {@link ng.directive:ngClick ngClick} directives.
  20589. * This is because of the following form submission rules in the HTML specification:
  20590. *
  20591. * - If a form has only one input field then hitting enter in this field triggers form submit
  20592. * (`ngSubmit`)
  20593. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  20594. * doesn't trigger submit
  20595. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  20596. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  20597. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  20598. *
  20599. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  20600. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  20601. * to have access to the updated model.
  20602. *
  20603. * ## Animation Hooks
  20604. *
  20605. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  20606. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  20607. * other validations that are performed within the form. Animations in ngForm are similar to how
  20608. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  20609. * as JS animations.
  20610. *
  20611. * The following example shows a simple way to utilize CSS transitions to style a form element
  20612. * that has been rendered as invalid after it has been validated:
  20613. *
  20614. * <pre>
  20615. * //be sure to include ngAnimate as a module to hook into more
  20616. * //advanced animations
  20617. * .my-form {
  20618. * transition:0.5s linear all;
  20619. * background: white;
  20620. * }
  20621. * .my-form.ng-invalid {
  20622. * background: red;
  20623. * color:white;
  20624. * }
  20625. * </pre>
  20626. *
  20627. * @example
  20628. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  20629. <file name="index.html">
  20630. <script>
  20631. angular.module('formExample', [])
  20632. .controller('FormController', ['$scope', function($scope) {
  20633. $scope.userType = 'guest';
  20634. }]);
  20635. </script>
  20636. <style>
  20637. .my-form {
  20638. transition:all linear 0.5s;
  20639. background: transparent;
  20640. }
  20641. .my-form.ng-invalid {
  20642. background: red;
  20643. }
  20644. </style>
  20645. <form name="myForm" ng-controller="FormController" class="my-form">
  20646. userType: <input name="input" ng-model="userType" required>
  20647. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  20648. <code>userType = {{userType}}</code><br>
  20649. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  20650. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  20651. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  20652. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  20653. </form>
  20654. </file>
  20655. <file name="protractor.js" type="protractor">
  20656. it('should initialize to model', function() {
  20657. var userType = element(by.binding('userType'));
  20658. var valid = element(by.binding('myForm.input.$valid'));
  20659. expect(userType.getText()).toContain('guest');
  20660. expect(valid.getText()).toContain('true');
  20661. });
  20662. it('should be invalid if empty', function() {
  20663. var userType = element(by.binding('userType'));
  20664. var valid = element(by.binding('myForm.input.$valid'));
  20665. var userInput = element(by.model('userType'));
  20666. userInput.clear();
  20667. userInput.sendKeys('');
  20668. expect(userType.getText()).toEqual('userType =');
  20669. expect(valid.getText()).toContain('false');
  20670. });
  20671. </file>
  20672. </example>
  20673. *
  20674. * @param {string=} name Name of the form. If specified, the form controller will be published into
  20675. * related scope, under this name.
  20676. */
  20677. var formDirectiveFactory = function(isNgForm) {
  20678. return ['$timeout', '$parse', function($timeout, $parse) {
  20679. var formDirective = {
  20680. name: 'form',
  20681. restrict: isNgForm ? 'EAC' : 'E',
  20682. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  20683. controller: FormController,
  20684. compile: function ngFormCompile(formElement, attr) {
  20685. // Setup initial state of the control
  20686. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  20687. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  20688. return {
  20689. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  20690. var controller = ctrls[0];
  20691. // if `action` attr is not present on the form, prevent the default action (submission)
  20692. if (!('action' in attr)) {
  20693. // we can't use jq events because if a form is destroyed during submission the default
  20694. // action is not prevented. see #1238
  20695. //
  20696. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  20697. // page reload if the form was destroyed by submission of the form via a click handler
  20698. // on a button in the form. Looks like an IE9 specific bug.
  20699. var handleFormSubmission = function(event) {
  20700. scope.$apply(function() {
  20701. controller.$commitViewValue();
  20702. controller.$setSubmitted();
  20703. });
  20704. event.preventDefault();
  20705. };
  20706. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  20707. // unregister the preventDefault listener so that we don't not leak memory but in a
  20708. // way that will achieve the prevention of the default action.
  20709. formElement.on('$destroy', function() {
  20710. $timeout(function() {
  20711. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  20712. }, 0, false);
  20713. });
  20714. }
  20715. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  20716. parentFormCtrl.$addControl(controller);
  20717. var setter = nameAttr ? getSetter(controller.$name) : noop;
  20718. if (nameAttr) {
  20719. setter(scope, controller);
  20720. attr.$observe(nameAttr, function(newValue) {
  20721. if (controller.$name === newValue) return;
  20722. setter(scope, undefined);
  20723. controller.$$parentForm.$$renameControl(controller, newValue);
  20724. setter = getSetter(controller.$name);
  20725. setter(scope, controller);
  20726. });
  20727. }
  20728. formElement.on('$destroy', function() {
  20729. controller.$$parentForm.$removeControl(controller);
  20730. setter(scope, undefined);
  20731. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  20732. });
  20733. }
  20734. };
  20735. }
  20736. };
  20737. return formDirective;
  20738. function getSetter(expression) {
  20739. if (expression === '') {
  20740. //create an assignable expression, so forms with an empty name can be renamed later
  20741. return $parse('this[""]').assign;
  20742. }
  20743. return $parse(expression).assign || noop;
  20744. }
  20745. }];
  20746. };
  20747. var formDirective = formDirectiveFactory();
  20748. var ngFormDirective = formDirectiveFactory(true);
  20749. /* global VALID_CLASS: false,
  20750. INVALID_CLASS: false,
  20751. PRISTINE_CLASS: false,
  20752. DIRTY_CLASS: false,
  20753. UNTOUCHED_CLASS: false,
  20754. TOUCHED_CLASS: false,
  20755. ngModelMinErr: false,
  20756. */
  20757. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  20758. 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)$/;
  20759. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  20760. // Note: We are being more lenient, because browsers are too.
  20761. // 1. Scheme
  20762. // 2. Slashes
  20763. // 3. Username
  20764. // 4. Password
  20765. // 5. Hostname
  20766. // 6. Port
  20767. // 7. Path
  20768. // 8. Query
  20769. // 9. Fragment
  20770. // 1111111111111111 222 333333 44444 555555555555555555555555 666 77777777 8888888 999
  20771. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  20772. /* jshint maxlen:220 */
  20773. 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])?)*$/;
  20774. /* jshint maxlen:200 */
  20775. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  20776. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  20777. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  20778. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  20779. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  20780. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  20781. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  20782. var PARTIAL_VALIDATION_TYPES = createMap();
  20783. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  20784. PARTIAL_VALIDATION_TYPES[type] = true;
  20785. });
  20786. var inputType = {
  20787. /**
  20788. * @ngdoc input
  20789. * @name input[text]
  20790. *
  20791. * @description
  20792. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  20793. *
  20794. *
  20795. * @param {string} ngModel Assignable angular expression to data-bind to.
  20796. * @param {string=} name Property name of the form under which the control is published.
  20797. * @param {string=} required Adds `required` validation error key if the value is not entered.
  20798. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20799. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20800. * `required` when you want to data-bind to the `required` attribute.
  20801. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20802. * minlength.
  20803. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20804. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  20805. * any length.
  20806. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  20807. * that contains the regular expression body that will be converted to a regular expression
  20808. * as in the ngPattern directive.
  20809. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20810. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20811. * If the expression evaluates to a RegExp object, then this is used directly.
  20812. * If the expression evaluates to a string, then it will be converted to a RegExp
  20813. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20814. * `new RegExp('^abc$')`.<br />
  20815. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20816. * start at the index of the last search's match, thus not taking the whole input value into
  20817. * account.
  20818. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20819. * interaction with the input element.
  20820. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  20821. * This parameter is ignored for input[type=password] controls, which will never trim the
  20822. * input.
  20823. *
  20824. * @example
  20825. <example name="text-input-directive" module="textInputExample">
  20826. <file name="index.html">
  20827. <script>
  20828. angular.module('textInputExample', [])
  20829. .controller('ExampleController', ['$scope', function($scope) {
  20830. $scope.example = {
  20831. text: 'guest',
  20832. word: /^\s*\w*\s*$/
  20833. };
  20834. }]);
  20835. </script>
  20836. <form name="myForm" ng-controller="ExampleController">
  20837. <label>Single word:
  20838. <input type="text" name="input" ng-model="example.text"
  20839. ng-pattern="example.word" required ng-trim="false">
  20840. </label>
  20841. <div role="alert">
  20842. <span class="error" ng-show="myForm.input.$error.required">
  20843. Required!</span>
  20844. <span class="error" ng-show="myForm.input.$error.pattern">
  20845. Single word only!</span>
  20846. </div>
  20847. <code>text = {{example.text}}</code><br/>
  20848. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  20849. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  20850. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  20851. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  20852. </form>
  20853. </file>
  20854. <file name="protractor.js" type="protractor">
  20855. var text = element(by.binding('example.text'));
  20856. var valid = element(by.binding('myForm.input.$valid'));
  20857. var input = element(by.model('example.text'));
  20858. it('should initialize to model', function() {
  20859. expect(text.getText()).toContain('guest');
  20860. expect(valid.getText()).toContain('true');
  20861. });
  20862. it('should be invalid if empty', function() {
  20863. input.clear();
  20864. input.sendKeys('');
  20865. expect(text.getText()).toEqual('text =');
  20866. expect(valid.getText()).toContain('false');
  20867. });
  20868. it('should be invalid if multi word', function() {
  20869. input.clear();
  20870. input.sendKeys('hello world');
  20871. expect(valid.getText()).toContain('false');
  20872. });
  20873. </file>
  20874. </example>
  20875. */
  20876. 'text': textInputType,
  20877. /**
  20878. * @ngdoc input
  20879. * @name input[date]
  20880. *
  20881. * @description
  20882. * Input with date validation and transformation. In browsers that do not yet support
  20883. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  20884. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  20885. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  20886. * expected input format via a placeholder or label.
  20887. *
  20888. * The model must always be a Date object, otherwise Angular will throw an error.
  20889. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20890. *
  20891. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20892. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20893. *
  20894. * @param {string} ngModel Assignable angular expression to data-bind to.
  20895. * @param {string=} name Property name of the form under which the control is published.
  20896. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  20897. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  20898. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  20899. * constraint validation.
  20900. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  20901. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  20902. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  20903. * constraint validation.
  20904. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  20905. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20906. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  20907. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20908. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20909. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20910. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20911. * `required` when you want to data-bind to the `required` attribute.
  20912. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20913. * interaction with the input element.
  20914. *
  20915. * @example
  20916. <example name="date-input-directive" module="dateInputExample">
  20917. <file name="index.html">
  20918. <script>
  20919. angular.module('dateInputExample', [])
  20920. .controller('DateController', ['$scope', function($scope) {
  20921. $scope.example = {
  20922. value: new Date(2013, 9, 22)
  20923. };
  20924. }]);
  20925. </script>
  20926. <form name="myForm" ng-controller="DateController as dateCtrl">
  20927. <label for="exampleInput">Pick a date in 2013:</label>
  20928. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  20929. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  20930. <div role="alert">
  20931. <span class="error" ng-show="myForm.input.$error.required">
  20932. Required!</span>
  20933. <span class="error" ng-show="myForm.input.$error.date">
  20934. Not a valid date!</span>
  20935. </div>
  20936. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  20937. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20938. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20939. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20940. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20941. </form>
  20942. </file>
  20943. <file name="protractor.js" type="protractor">
  20944. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  20945. var valid = element(by.binding('myForm.input.$valid'));
  20946. var input = element(by.model('example.value'));
  20947. // currently protractor/webdriver does not support
  20948. // sending keys to all known HTML5 input controls
  20949. // for various browsers (see https://github.com/angular/protractor/issues/562).
  20950. function setInput(val) {
  20951. // set the value of the element and force validation.
  20952. var scr = "var ipt = document.getElementById('exampleInput'); " +
  20953. "ipt.value = '" + val + "';" +
  20954. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  20955. browser.executeScript(scr);
  20956. }
  20957. it('should initialize to model', function() {
  20958. expect(value.getText()).toContain('2013-10-22');
  20959. expect(valid.getText()).toContain('myForm.input.$valid = true');
  20960. });
  20961. it('should be invalid if empty', function() {
  20962. setInput('');
  20963. expect(value.getText()).toEqual('value =');
  20964. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20965. });
  20966. it('should be invalid if over max', function() {
  20967. setInput('2015-01-01');
  20968. expect(value.getText()).toContain('');
  20969. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20970. });
  20971. </file>
  20972. </example>
  20973. */
  20974. 'date': createDateInputType('date', DATE_REGEXP,
  20975. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  20976. 'yyyy-MM-dd'),
  20977. /**
  20978. * @ngdoc input
  20979. * @name input[datetime-local]
  20980. *
  20981. * @description
  20982. * Input with datetime validation and transformation. In browsers that do not yet support
  20983. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  20984. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  20985. *
  20986. * The model must always be a Date object, otherwise Angular will throw an error.
  20987. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20988. *
  20989. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20990. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20991. *
  20992. * @param {string} ngModel Assignable angular expression to data-bind to.
  20993. * @param {string=} name Property name of the form under which the control is published.
  20994. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20995. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  20996. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  20997. * Note that `min` will also add native HTML5 constraint validation.
  20998. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20999. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21000. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21001. * Note that `max` will also add native HTML5 constraint validation.
  21002. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  21003. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21004. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  21005. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21006. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21007. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21008. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21009. * `required` when you want to data-bind to the `required` attribute.
  21010. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21011. * interaction with the input element.
  21012. *
  21013. * @example
  21014. <example name="datetimelocal-input-directive" module="dateExample">
  21015. <file name="index.html">
  21016. <script>
  21017. angular.module('dateExample', [])
  21018. .controller('DateController', ['$scope', function($scope) {
  21019. $scope.example = {
  21020. value: new Date(2010, 11, 28, 14, 57)
  21021. };
  21022. }]);
  21023. </script>
  21024. <form name="myForm" ng-controller="DateController as dateCtrl">
  21025. <label for="exampleInput">Pick a date between in 2013:</label>
  21026. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  21027. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  21028. <div role="alert">
  21029. <span class="error" ng-show="myForm.input.$error.required">
  21030. Required!</span>
  21031. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  21032. Not a valid date!</span>
  21033. </div>
  21034. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  21035. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21036. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21037. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21038. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21039. </form>
  21040. </file>
  21041. <file name="protractor.js" type="protractor">
  21042. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  21043. var valid = element(by.binding('myForm.input.$valid'));
  21044. var input = element(by.model('example.value'));
  21045. // currently protractor/webdriver does not support
  21046. // sending keys to all known HTML5 input controls
  21047. // for various browsers (https://github.com/angular/protractor/issues/562).
  21048. function setInput(val) {
  21049. // set the value of the element and force validation.
  21050. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21051. "ipt.value = '" + val + "';" +
  21052. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21053. browser.executeScript(scr);
  21054. }
  21055. it('should initialize to model', function() {
  21056. expect(value.getText()).toContain('2010-12-28T14:57:00');
  21057. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21058. });
  21059. it('should be invalid if empty', function() {
  21060. setInput('');
  21061. expect(value.getText()).toEqual('value =');
  21062. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21063. });
  21064. it('should be invalid if over max', function() {
  21065. setInput('2015-01-01T23:59:00');
  21066. expect(value.getText()).toContain('');
  21067. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21068. });
  21069. </file>
  21070. </example>
  21071. */
  21072. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  21073. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  21074. 'yyyy-MM-ddTHH:mm:ss.sss'),
  21075. /**
  21076. * @ngdoc input
  21077. * @name input[time]
  21078. *
  21079. * @description
  21080. * Input with time validation and transformation. In browsers that do not yet support
  21081. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21082. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  21083. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  21084. *
  21085. * The model must always be a Date object, otherwise Angular will throw an error.
  21086. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21087. *
  21088. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21089. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21090. *
  21091. * @param {string} ngModel Assignable angular expression to data-bind to.
  21092. * @param {string=} name Property name of the form under which the control is published.
  21093. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21094. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21095. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  21096. * native HTML5 constraint validation.
  21097. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21098. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21099. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  21100. * native HTML5 constraint validation.
  21101. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  21102. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21103. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  21104. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21105. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21106. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21107. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21108. * `required` when you want to data-bind to the `required` attribute.
  21109. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21110. * interaction with the input element.
  21111. *
  21112. * @example
  21113. <example name="time-input-directive" module="timeExample">
  21114. <file name="index.html">
  21115. <script>
  21116. angular.module('timeExample', [])
  21117. .controller('DateController', ['$scope', function($scope) {
  21118. $scope.example = {
  21119. value: new Date(1970, 0, 1, 14, 57, 0)
  21120. };
  21121. }]);
  21122. </script>
  21123. <form name="myForm" ng-controller="DateController as dateCtrl">
  21124. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  21125. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  21126. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  21127. <div role="alert">
  21128. <span class="error" ng-show="myForm.input.$error.required">
  21129. Required!</span>
  21130. <span class="error" ng-show="myForm.input.$error.time">
  21131. Not a valid date!</span>
  21132. </div>
  21133. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  21134. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21135. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21136. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21137. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21138. </form>
  21139. </file>
  21140. <file name="protractor.js" type="protractor">
  21141. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  21142. var valid = element(by.binding('myForm.input.$valid'));
  21143. var input = element(by.model('example.value'));
  21144. // currently protractor/webdriver does not support
  21145. // sending keys to all known HTML5 input controls
  21146. // for various browsers (https://github.com/angular/protractor/issues/562).
  21147. function setInput(val) {
  21148. // set the value of the element and force validation.
  21149. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21150. "ipt.value = '" + val + "';" +
  21151. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21152. browser.executeScript(scr);
  21153. }
  21154. it('should initialize to model', function() {
  21155. expect(value.getText()).toContain('14:57:00');
  21156. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21157. });
  21158. it('should be invalid if empty', function() {
  21159. setInput('');
  21160. expect(value.getText()).toEqual('value =');
  21161. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21162. });
  21163. it('should be invalid if over max', function() {
  21164. setInput('23:59:00');
  21165. expect(value.getText()).toContain('');
  21166. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21167. });
  21168. </file>
  21169. </example>
  21170. */
  21171. 'time': createDateInputType('time', TIME_REGEXP,
  21172. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  21173. 'HH:mm:ss.sss'),
  21174. /**
  21175. * @ngdoc input
  21176. * @name input[week]
  21177. *
  21178. * @description
  21179. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  21180. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21181. * week format (yyyy-W##), for example: `2013-W02`.
  21182. *
  21183. * The model must always be a Date object, otherwise Angular will throw an error.
  21184. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21185. *
  21186. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21187. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21188. *
  21189. * @param {string} ngModel Assignable angular expression to data-bind to.
  21190. * @param {string=} name Property name of the form under which the control is published.
  21191. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21192. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21193. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  21194. * native HTML5 constraint validation.
  21195. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21196. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21197. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  21198. * native HTML5 constraint validation.
  21199. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21200. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21201. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21202. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21203. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21204. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21205. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21206. * `required` when you want to data-bind to the `required` attribute.
  21207. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21208. * interaction with the input element.
  21209. *
  21210. * @example
  21211. <example name="week-input-directive" module="weekExample">
  21212. <file name="index.html">
  21213. <script>
  21214. angular.module('weekExample', [])
  21215. .controller('DateController', ['$scope', function($scope) {
  21216. $scope.example = {
  21217. value: new Date(2013, 0, 3)
  21218. };
  21219. }]);
  21220. </script>
  21221. <form name="myForm" ng-controller="DateController as dateCtrl">
  21222. <label>Pick a date between in 2013:
  21223. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  21224. placeholder="YYYY-W##" min="2012-W32"
  21225. max="2013-W52" required />
  21226. </label>
  21227. <div role="alert">
  21228. <span class="error" ng-show="myForm.input.$error.required">
  21229. Required!</span>
  21230. <span class="error" ng-show="myForm.input.$error.week">
  21231. Not a valid date!</span>
  21232. </div>
  21233. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  21234. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21235. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21236. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21237. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21238. </form>
  21239. </file>
  21240. <file name="protractor.js" type="protractor">
  21241. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  21242. var valid = element(by.binding('myForm.input.$valid'));
  21243. var input = element(by.model('example.value'));
  21244. // currently protractor/webdriver does not support
  21245. // sending keys to all known HTML5 input controls
  21246. // for various browsers (https://github.com/angular/protractor/issues/562).
  21247. function setInput(val) {
  21248. // set the value of the element and force validation.
  21249. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21250. "ipt.value = '" + val + "';" +
  21251. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21252. browser.executeScript(scr);
  21253. }
  21254. it('should initialize to model', function() {
  21255. expect(value.getText()).toContain('2013-W01');
  21256. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21257. });
  21258. it('should be invalid if empty', function() {
  21259. setInput('');
  21260. expect(value.getText()).toEqual('value =');
  21261. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21262. });
  21263. it('should be invalid if over max', function() {
  21264. setInput('2015-W01');
  21265. expect(value.getText()).toContain('');
  21266. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21267. });
  21268. </file>
  21269. </example>
  21270. */
  21271. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  21272. /**
  21273. * @ngdoc input
  21274. * @name input[month]
  21275. *
  21276. * @description
  21277. * Input with month validation and transformation. In browsers that do not yet support
  21278. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21279. * month format (yyyy-MM), for example: `2009-01`.
  21280. *
  21281. * The model must always be a Date object, otherwise Angular will throw an error.
  21282. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21283. * If the model is not set to the first of the month, the next view to model update will set it
  21284. * to the first of the month.
  21285. *
  21286. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21287. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21288. *
  21289. * @param {string} ngModel Assignable angular expression to data-bind to.
  21290. * @param {string=} name Property name of the form under which the control is published.
  21291. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21292. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21293. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  21294. * native HTML5 constraint validation.
  21295. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21296. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21297. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  21298. * native HTML5 constraint validation.
  21299. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21300. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21301. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21302. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21303. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21304. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21305. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21306. * `required` when you want to data-bind to the `required` attribute.
  21307. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21308. * interaction with the input element.
  21309. *
  21310. * @example
  21311. <example name="month-input-directive" module="monthExample">
  21312. <file name="index.html">
  21313. <script>
  21314. angular.module('monthExample', [])
  21315. .controller('DateController', ['$scope', function($scope) {
  21316. $scope.example = {
  21317. value: new Date(2013, 9, 1)
  21318. };
  21319. }]);
  21320. </script>
  21321. <form name="myForm" ng-controller="DateController as dateCtrl">
  21322. <label for="exampleInput">Pick a month in 2013:</label>
  21323. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  21324. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  21325. <div role="alert">
  21326. <span class="error" ng-show="myForm.input.$error.required">
  21327. Required!</span>
  21328. <span class="error" ng-show="myForm.input.$error.month">
  21329. Not a valid month!</span>
  21330. </div>
  21331. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  21332. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21333. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21334. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21335. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21336. </form>
  21337. </file>
  21338. <file name="protractor.js" type="protractor">
  21339. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  21340. var valid = element(by.binding('myForm.input.$valid'));
  21341. var input = element(by.model('example.value'));
  21342. // currently protractor/webdriver does not support
  21343. // sending keys to all known HTML5 input controls
  21344. // for various browsers (https://github.com/angular/protractor/issues/562).
  21345. function setInput(val) {
  21346. // set the value of the element and force validation.
  21347. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21348. "ipt.value = '" + val + "';" +
  21349. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21350. browser.executeScript(scr);
  21351. }
  21352. it('should initialize to model', function() {
  21353. expect(value.getText()).toContain('2013-10');
  21354. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21355. });
  21356. it('should be invalid if empty', function() {
  21357. setInput('');
  21358. expect(value.getText()).toEqual('value =');
  21359. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21360. });
  21361. it('should be invalid if over max', function() {
  21362. setInput('2015-01');
  21363. expect(value.getText()).toContain('');
  21364. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21365. });
  21366. </file>
  21367. </example>
  21368. */
  21369. 'month': createDateInputType('month', MONTH_REGEXP,
  21370. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  21371. 'yyyy-MM'),
  21372. /**
  21373. * @ngdoc input
  21374. * @name input[number]
  21375. *
  21376. * @description
  21377. * Text input with number validation and transformation. Sets the `number` validation
  21378. * error if not a valid number.
  21379. *
  21380. * <div class="alert alert-warning">
  21381. * The model must always be of type `number` otherwise Angular will throw an error.
  21382. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  21383. * error docs for more information and an example of how to convert your model if necessary.
  21384. * </div>
  21385. *
  21386. * ## Issues with HTML5 constraint validation
  21387. *
  21388. * In browsers that follow the
  21389. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  21390. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  21391. * If a non-number is entered in the input, the browser will report the value as an empty string,
  21392. * which means the view / model values in `ngModel` and subsequently the scope value
  21393. * will also be an empty string.
  21394. *
  21395. *
  21396. * @param {string} ngModel Assignable angular expression to data-bind to.
  21397. * @param {string=} name Property name of the form under which the control is published.
  21398. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21399. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21400. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21401. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21402. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21403. * `required` when you want to data-bind to the `required` attribute.
  21404. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21405. * minlength.
  21406. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21407. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21408. * any length.
  21409. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21410. * that contains the regular expression body that will be converted to a regular expression
  21411. * as in the ngPattern directive.
  21412. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21413. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21414. * If the expression evaluates to a RegExp object, then this is used directly.
  21415. * If the expression evaluates to a string, then it will be converted to a RegExp
  21416. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21417. * `new RegExp('^abc$')`.<br />
  21418. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21419. * start at the index of the last search's match, thus not taking the whole input value into
  21420. * account.
  21421. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21422. * interaction with the input element.
  21423. *
  21424. * @example
  21425. <example name="number-input-directive" module="numberExample">
  21426. <file name="index.html">
  21427. <script>
  21428. angular.module('numberExample', [])
  21429. .controller('ExampleController', ['$scope', function($scope) {
  21430. $scope.example = {
  21431. value: 12
  21432. };
  21433. }]);
  21434. </script>
  21435. <form name="myForm" ng-controller="ExampleController">
  21436. <label>Number:
  21437. <input type="number" name="input" ng-model="example.value"
  21438. min="0" max="99" required>
  21439. </label>
  21440. <div role="alert">
  21441. <span class="error" ng-show="myForm.input.$error.required">
  21442. Required!</span>
  21443. <span class="error" ng-show="myForm.input.$error.number">
  21444. Not valid number!</span>
  21445. </div>
  21446. <tt>value = {{example.value}}</tt><br/>
  21447. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21448. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21449. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21450. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21451. </form>
  21452. </file>
  21453. <file name="protractor.js" type="protractor">
  21454. var value = element(by.binding('example.value'));
  21455. var valid = element(by.binding('myForm.input.$valid'));
  21456. var input = element(by.model('example.value'));
  21457. it('should initialize to model', function() {
  21458. expect(value.getText()).toContain('12');
  21459. expect(valid.getText()).toContain('true');
  21460. });
  21461. it('should be invalid if empty', function() {
  21462. input.clear();
  21463. input.sendKeys('');
  21464. expect(value.getText()).toEqual('value =');
  21465. expect(valid.getText()).toContain('false');
  21466. });
  21467. it('should be invalid if over max', function() {
  21468. input.clear();
  21469. input.sendKeys('123');
  21470. expect(value.getText()).toEqual('value =');
  21471. expect(valid.getText()).toContain('false');
  21472. });
  21473. </file>
  21474. </example>
  21475. */
  21476. 'number': numberInputType,
  21477. /**
  21478. * @ngdoc input
  21479. * @name input[url]
  21480. *
  21481. * @description
  21482. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  21483. * valid URL.
  21484. *
  21485. * <div class="alert alert-warning">
  21486. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  21487. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  21488. * the built-in validators (see the {@link guide/forms Forms guide})
  21489. * </div>
  21490. *
  21491. * @param {string} ngModel Assignable angular expression to data-bind to.
  21492. * @param {string=} name Property name of the form under which the control is published.
  21493. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21494. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21495. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21496. * `required` when you want to data-bind to the `required` attribute.
  21497. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21498. * minlength.
  21499. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21500. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21501. * any length.
  21502. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21503. * that contains the regular expression body that will be converted to a regular expression
  21504. * as in the ngPattern directive.
  21505. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21506. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21507. * If the expression evaluates to a RegExp object, then this is used directly.
  21508. * If the expression evaluates to a string, then it will be converted to a RegExp
  21509. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21510. * `new RegExp('^abc$')`.<br />
  21511. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21512. * start at the index of the last search's match, thus not taking the whole input value into
  21513. * account.
  21514. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21515. * interaction with the input element.
  21516. *
  21517. * @example
  21518. <example name="url-input-directive" module="urlExample">
  21519. <file name="index.html">
  21520. <script>
  21521. angular.module('urlExample', [])
  21522. .controller('ExampleController', ['$scope', function($scope) {
  21523. $scope.url = {
  21524. text: 'http://google.com'
  21525. };
  21526. }]);
  21527. </script>
  21528. <form name="myForm" ng-controller="ExampleController">
  21529. <label>URL:
  21530. <input type="url" name="input" ng-model="url.text" required>
  21531. <label>
  21532. <div role="alert">
  21533. <span class="error" ng-show="myForm.input.$error.required">
  21534. Required!</span>
  21535. <span class="error" ng-show="myForm.input.$error.url">
  21536. Not valid url!</span>
  21537. </div>
  21538. <tt>text = {{url.text}}</tt><br/>
  21539. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21540. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21541. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21542. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21543. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  21544. </form>
  21545. </file>
  21546. <file name="protractor.js" type="protractor">
  21547. var text = element(by.binding('url.text'));
  21548. var valid = element(by.binding('myForm.input.$valid'));
  21549. var input = element(by.model('url.text'));
  21550. it('should initialize to model', function() {
  21551. expect(text.getText()).toContain('http://google.com');
  21552. expect(valid.getText()).toContain('true');
  21553. });
  21554. it('should be invalid if empty', function() {
  21555. input.clear();
  21556. input.sendKeys('');
  21557. expect(text.getText()).toEqual('text =');
  21558. expect(valid.getText()).toContain('false');
  21559. });
  21560. it('should be invalid if not url', function() {
  21561. input.clear();
  21562. input.sendKeys('box');
  21563. expect(valid.getText()).toContain('false');
  21564. });
  21565. </file>
  21566. </example>
  21567. */
  21568. 'url': urlInputType,
  21569. /**
  21570. * @ngdoc input
  21571. * @name input[email]
  21572. *
  21573. * @description
  21574. * Text input with email validation. Sets the `email` validation error key if not a valid email
  21575. * address.
  21576. *
  21577. * <div class="alert alert-warning">
  21578. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  21579. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  21580. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  21581. * </div>
  21582. *
  21583. * @param {string} ngModel Assignable angular expression to data-bind to.
  21584. * @param {string=} name Property name of the form under which the control is published.
  21585. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21586. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21587. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21588. * `required` when you want to data-bind to the `required` attribute.
  21589. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21590. * minlength.
  21591. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21592. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21593. * any length.
  21594. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21595. * that contains the regular expression body that will be converted to a regular expression
  21596. * as in the ngPattern directive.
  21597. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21598. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21599. * If the expression evaluates to a RegExp object, then this is used directly.
  21600. * If the expression evaluates to a string, then it will be converted to a RegExp
  21601. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21602. * `new RegExp('^abc$')`.<br />
  21603. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21604. * start at the index of the last search's match, thus not taking the whole input value into
  21605. * account.
  21606. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21607. * interaction with the input element.
  21608. *
  21609. * @example
  21610. <example name="email-input-directive" module="emailExample">
  21611. <file name="index.html">
  21612. <script>
  21613. angular.module('emailExample', [])
  21614. .controller('ExampleController', ['$scope', function($scope) {
  21615. $scope.email = {
  21616. text: 'me@example.com'
  21617. };
  21618. }]);
  21619. </script>
  21620. <form name="myForm" ng-controller="ExampleController">
  21621. <label>Email:
  21622. <input type="email" name="input" ng-model="email.text" required>
  21623. </label>
  21624. <div role="alert">
  21625. <span class="error" ng-show="myForm.input.$error.required">
  21626. Required!</span>
  21627. <span class="error" ng-show="myForm.input.$error.email">
  21628. Not valid email!</span>
  21629. </div>
  21630. <tt>text = {{email.text}}</tt><br/>
  21631. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21632. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21633. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21634. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21635. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  21636. </form>
  21637. </file>
  21638. <file name="protractor.js" type="protractor">
  21639. var text = element(by.binding('email.text'));
  21640. var valid = element(by.binding('myForm.input.$valid'));
  21641. var input = element(by.model('email.text'));
  21642. it('should initialize to model', function() {
  21643. expect(text.getText()).toContain('me@example.com');
  21644. expect(valid.getText()).toContain('true');
  21645. });
  21646. it('should be invalid if empty', function() {
  21647. input.clear();
  21648. input.sendKeys('');
  21649. expect(text.getText()).toEqual('text =');
  21650. expect(valid.getText()).toContain('false');
  21651. });
  21652. it('should be invalid if not email', function() {
  21653. input.clear();
  21654. input.sendKeys('xxx');
  21655. expect(valid.getText()).toContain('false');
  21656. });
  21657. </file>
  21658. </example>
  21659. */
  21660. 'email': emailInputType,
  21661. /**
  21662. * @ngdoc input
  21663. * @name input[radio]
  21664. *
  21665. * @description
  21666. * HTML radio button.
  21667. *
  21668. * @param {string} ngModel Assignable angular expression to data-bind to.
  21669. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  21670. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  21671. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  21672. * @param {string=} name Property name of the form under which the control is published.
  21673. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21674. * interaction with the input element.
  21675. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  21676. * is selected. Should be used instead of the `value` attribute if you need
  21677. * a non-string `ngModel` (`boolean`, `array`, ...).
  21678. *
  21679. * @example
  21680. <example name="radio-input-directive" module="radioExample">
  21681. <file name="index.html">
  21682. <script>
  21683. angular.module('radioExample', [])
  21684. .controller('ExampleController', ['$scope', function($scope) {
  21685. $scope.color = {
  21686. name: 'blue'
  21687. };
  21688. $scope.specialValue = {
  21689. "id": "12345",
  21690. "value": "green"
  21691. };
  21692. }]);
  21693. </script>
  21694. <form name="myForm" ng-controller="ExampleController">
  21695. <label>
  21696. <input type="radio" ng-model="color.name" value="red">
  21697. Red
  21698. </label><br/>
  21699. <label>
  21700. <input type="radio" ng-model="color.name" ng-value="specialValue">
  21701. Green
  21702. </label><br/>
  21703. <label>
  21704. <input type="radio" ng-model="color.name" value="blue">
  21705. Blue
  21706. </label><br/>
  21707. <tt>color = {{color.name | json}}</tt><br/>
  21708. </form>
  21709. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  21710. </file>
  21711. <file name="protractor.js" type="protractor">
  21712. it('should change state', function() {
  21713. var color = element(by.binding('color.name'));
  21714. expect(color.getText()).toContain('blue');
  21715. element.all(by.model('color.name')).get(0).click();
  21716. expect(color.getText()).toContain('red');
  21717. });
  21718. </file>
  21719. </example>
  21720. */
  21721. 'radio': radioInputType,
  21722. /**
  21723. * @ngdoc input
  21724. * @name input[checkbox]
  21725. *
  21726. * @description
  21727. * HTML checkbox.
  21728. *
  21729. * @param {string} ngModel Assignable angular expression to data-bind to.
  21730. * @param {string=} name Property name of the form under which the control is published.
  21731. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  21732. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  21733. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21734. * interaction with the input element.
  21735. *
  21736. * @example
  21737. <example name="checkbox-input-directive" module="checkboxExample">
  21738. <file name="index.html">
  21739. <script>
  21740. angular.module('checkboxExample', [])
  21741. .controller('ExampleController', ['$scope', function($scope) {
  21742. $scope.checkboxModel = {
  21743. value1 : true,
  21744. value2 : 'YES'
  21745. };
  21746. }]);
  21747. </script>
  21748. <form name="myForm" ng-controller="ExampleController">
  21749. <label>Value1:
  21750. <input type="checkbox" ng-model="checkboxModel.value1">
  21751. </label><br/>
  21752. <label>Value2:
  21753. <input type="checkbox" ng-model="checkboxModel.value2"
  21754. ng-true-value="'YES'" ng-false-value="'NO'">
  21755. </label><br/>
  21756. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  21757. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  21758. </form>
  21759. </file>
  21760. <file name="protractor.js" type="protractor">
  21761. it('should change state', function() {
  21762. var value1 = element(by.binding('checkboxModel.value1'));
  21763. var value2 = element(by.binding('checkboxModel.value2'));
  21764. expect(value1.getText()).toContain('true');
  21765. expect(value2.getText()).toContain('YES');
  21766. element(by.model('checkboxModel.value1')).click();
  21767. element(by.model('checkboxModel.value2')).click();
  21768. expect(value1.getText()).toContain('false');
  21769. expect(value2.getText()).toContain('NO');
  21770. });
  21771. </file>
  21772. </example>
  21773. */
  21774. 'checkbox': checkboxInputType,
  21775. 'hidden': noop,
  21776. 'button': noop,
  21777. 'submit': noop,
  21778. 'reset': noop,
  21779. 'file': noop
  21780. };
  21781. function stringBasedInputType(ctrl) {
  21782. ctrl.$formatters.push(function(value) {
  21783. return ctrl.$isEmpty(value) ? value : value.toString();
  21784. });
  21785. }
  21786. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  21787. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  21788. stringBasedInputType(ctrl);
  21789. }
  21790. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  21791. var type = lowercase(element[0].type);
  21792. // In composition mode, users are still inputing intermediate text buffer,
  21793. // hold the listener until composition is done.
  21794. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  21795. if (!$sniffer.android) {
  21796. var composing = false;
  21797. element.on('compositionstart', function() {
  21798. composing = true;
  21799. });
  21800. element.on('compositionend', function() {
  21801. composing = false;
  21802. listener();
  21803. });
  21804. }
  21805. var timeout;
  21806. var listener = function(ev) {
  21807. if (timeout) {
  21808. $browser.defer.cancel(timeout);
  21809. timeout = null;
  21810. }
  21811. if (composing) return;
  21812. var value = element.val(),
  21813. event = ev && ev.type;
  21814. // By default we will trim the value
  21815. // If the attribute ng-trim exists we will avoid trimming
  21816. // If input type is 'password', the value is never trimmed
  21817. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  21818. value = trim(value);
  21819. }
  21820. // If a control is suffering from bad input (due to native validators), browsers discard its
  21821. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  21822. // control's value is the same empty value twice in a row.
  21823. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  21824. ctrl.$setViewValue(value, event);
  21825. }
  21826. };
  21827. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  21828. // input event on backspace, delete or cut
  21829. if ($sniffer.hasEvent('input')) {
  21830. element.on('input', listener);
  21831. } else {
  21832. var deferListener = function(ev, input, origValue) {
  21833. if (!timeout) {
  21834. timeout = $browser.defer(function() {
  21835. timeout = null;
  21836. if (!input || input.value !== origValue) {
  21837. listener(ev);
  21838. }
  21839. });
  21840. }
  21841. };
  21842. element.on('keydown', function(event) {
  21843. var key = event.keyCode;
  21844. // ignore
  21845. // command modifiers arrows
  21846. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  21847. deferListener(event, this, this.value);
  21848. });
  21849. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  21850. if ($sniffer.hasEvent('paste')) {
  21851. element.on('paste cut', deferListener);
  21852. }
  21853. }
  21854. // if user paste into input using mouse on older browser
  21855. // or form autocomplete on newer browser, we need "change" event to catch it
  21856. element.on('change', listener);
  21857. // Some native input types (date-family) have the ability to change validity without
  21858. // firing any input/change events.
  21859. // For these event types, when native validators are present and the browser supports the type,
  21860. // check for validity changes on various DOM events.
  21861. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  21862. element.on(PARTIAL_VALIDATION_EVENTS, function(ev) {
  21863. if (!timeout) {
  21864. var validity = this[VALIDITY_STATE_PROPERTY];
  21865. var origBadInput = validity.badInput;
  21866. var origTypeMismatch = validity.typeMismatch;
  21867. timeout = $browser.defer(function() {
  21868. timeout = null;
  21869. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  21870. listener(ev);
  21871. }
  21872. });
  21873. }
  21874. });
  21875. }
  21876. ctrl.$render = function() {
  21877. // Workaround for Firefox validation #12102.
  21878. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  21879. if (element.val() !== value) {
  21880. element.val(value);
  21881. }
  21882. };
  21883. }
  21884. function weekParser(isoWeek, existingDate) {
  21885. if (isDate(isoWeek)) {
  21886. return isoWeek;
  21887. }
  21888. if (isString(isoWeek)) {
  21889. WEEK_REGEXP.lastIndex = 0;
  21890. var parts = WEEK_REGEXP.exec(isoWeek);
  21891. if (parts) {
  21892. var year = +parts[1],
  21893. week = +parts[2],
  21894. hours = 0,
  21895. minutes = 0,
  21896. seconds = 0,
  21897. milliseconds = 0,
  21898. firstThurs = getFirstThursdayOfYear(year),
  21899. addDays = (week - 1) * 7;
  21900. if (existingDate) {
  21901. hours = existingDate.getHours();
  21902. minutes = existingDate.getMinutes();
  21903. seconds = existingDate.getSeconds();
  21904. milliseconds = existingDate.getMilliseconds();
  21905. }
  21906. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  21907. }
  21908. }
  21909. return NaN;
  21910. }
  21911. function createDateParser(regexp, mapping) {
  21912. return function(iso, date) {
  21913. var parts, map;
  21914. if (isDate(iso)) {
  21915. return iso;
  21916. }
  21917. if (isString(iso)) {
  21918. // When a date is JSON'ified to wraps itself inside of an extra
  21919. // set of double quotes. This makes the date parsing code unable
  21920. // to match the date string and parse it as a date.
  21921. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  21922. iso = iso.substring(1, iso.length - 1);
  21923. }
  21924. if (ISO_DATE_REGEXP.test(iso)) {
  21925. return new Date(iso);
  21926. }
  21927. regexp.lastIndex = 0;
  21928. parts = regexp.exec(iso);
  21929. if (parts) {
  21930. parts.shift();
  21931. if (date) {
  21932. map = {
  21933. yyyy: date.getFullYear(),
  21934. MM: date.getMonth() + 1,
  21935. dd: date.getDate(),
  21936. HH: date.getHours(),
  21937. mm: date.getMinutes(),
  21938. ss: date.getSeconds(),
  21939. sss: date.getMilliseconds() / 1000
  21940. };
  21941. } else {
  21942. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  21943. }
  21944. forEach(parts, function(part, index) {
  21945. if (index < mapping.length) {
  21946. map[mapping[index]] = +part;
  21947. }
  21948. });
  21949. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  21950. }
  21951. }
  21952. return NaN;
  21953. };
  21954. }
  21955. function createDateInputType(type, regexp, parseDate, format) {
  21956. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  21957. badInputChecker(scope, element, attr, ctrl);
  21958. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  21959. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  21960. var previousDate;
  21961. ctrl.$$parserName = type;
  21962. ctrl.$parsers.push(function(value) {
  21963. if (ctrl.$isEmpty(value)) return null;
  21964. if (regexp.test(value)) {
  21965. // Note: We cannot read ctrl.$modelValue, as there might be a different
  21966. // parser/formatter in the processing chain so that the model
  21967. // contains some different data format!
  21968. var parsedDate = parseDate(value, previousDate);
  21969. if (timezone) {
  21970. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  21971. }
  21972. return parsedDate;
  21973. }
  21974. return undefined;
  21975. });
  21976. ctrl.$formatters.push(function(value) {
  21977. if (value && !isDate(value)) {
  21978. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  21979. }
  21980. if (isValidDate(value)) {
  21981. previousDate = value;
  21982. if (previousDate && timezone) {
  21983. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  21984. }
  21985. return $filter('date')(value, format, timezone);
  21986. } else {
  21987. previousDate = null;
  21988. return '';
  21989. }
  21990. });
  21991. if (isDefined(attr.min) || attr.ngMin) {
  21992. var minVal;
  21993. ctrl.$validators.min = function(value) {
  21994. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  21995. };
  21996. attr.$observe('min', function(val) {
  21997. minVal = parseObservedDateValue(val);
  21998. ctrl.$validate();
  21999. });
  22000. }
  22001. if (isDefined(attr.max) || attr.ngMax) {
  22002. var maxVal;
  22003. ctrl.$validators.max = function(value) {
  22004. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  22005. };
  22006. attr.$observe('max', function(val) {
  22007. maxVal = parseObservedDateValue(val);
  22008. ctrl.$validate();
  22009. });
  22010. }
  22011. function isValidDate(value) {
  22012. // Invalid Date: getTime() returns NaN
  22013. return value && !(value.getTime && value.getTime() !== value.getTime());
  22014. }
  22015. function parseObservedDateValue(val) {
  22016. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  22017. }
  22018. };
  22019. }
  22020. function badInputChecker(scope, element, attr, ctrl) {
  22021. var node = element[0];
  22022. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  22023. if (nativeValidation) {
  22024. ctrl.$parsers.push(function(value) {
  22025. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  22026. return validity.badInput || validity.typeMismatch ? undefined : value;
  22027. });
  22028. }
  22029. }
  22030. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22031. badInputChecker(scope, element, attr, ctrl);
  22032. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22033. ctrl.$$parserName = 'number';
  22034. ctrl.$parsers.push(function(value) {
  22035. if (ctrl.$isEmpty(value)) return null;
  22036. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  22037. return undefined;
  22038. });
  22039. ctrl.$formatters.push(function(value) {
  22040. if (!ctrl.$isEmpty(value)) {
  22041. if (!isNumber(value)) {
  22042. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  22043. }
  22044. value = value.toString();
  22045. }
  22046. return value;
  22047. });
  22048. if (isDefined(attr.min) || attr.ngMin) {
  22049. var minVal;
  22050. ctrl.$validators.min = function(value) {
  22051. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  22052. };
  22053. attr.$observe('min', function(val) {
  22054. if (isDefined(val) && !isNumber(val)) {
  22055. val = parseFloat(val);
  22056. }
  22057. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  22058. // TODO(matsko): implement validateLater to reduce number of validations
  22059. ctrl.$validate();
  22060. });
  22061. }
  22062. if (isDefined(attr.max) || attr.ngMax) {
  22063. var maxVal;
  22064. ctrl.$validators.max = function(value) {
  22065. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  22066. };
  22067. attr.$observe('max', function(val) {
  22068. if (isDefined(val) && !isNumber(val)) {
  22069. val = parseFloat(val);
  22070. }
  22071. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  22072. // TODO(matsko): implement validateLater to reduce number of validations
  22073. ctrl.$validate();
  22074. });
  22075. }
  22076. }
  22077. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22078. // Note: no badInputChecker here by purpose as `url` is only a validation
  22079. // in browsers, i.e. we can always read out input.value even if it is not valid!
  22080. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22081. stringBasedInputType(ctrl);
  22082. ctrl.$$parserName = 'url';
  22083. ctrl.$validators.url = function(modelValue, viewValue) {
  22084. var value = modelValue || viewValue;
  22085. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  22086. };
  22087. }
  22088. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22089. // Note: no badInputChecker here by purpose as `url` is only a validation
  22090. // in browsers, i.e. we can always read out input.value even if it is not valid!
  22091. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22092. stringBasedInputType(ctrl);
  22093. ctrl.$$parserName = 'email';
  22094. ctrl.$validators.email = function(modelValue, viewValue) {
  22095. var value = modelValue || viewValue;
  22096. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  22097. };
  22098. }
  22099. function radioInputType(scope, element, attr, ctrl) {
  22100. // make the name unique, if not defined
  22101. if (isUndefined(attr.name)) {
  22102. element.attr('name', nextUid());
  22103. }
  22104. var listener = function(ev) {
  22105. if (element[0].checked) {
  22106. ctrl.$setViewValue(attr.value, ev && ev.type);
  22107. }
  22108. };
  22109. element.on('click', listener);
  22110. ctrl.$render = function() {
  22111. var value = attr.value;
  22112. element[0].checked = (value == ctrl.$viewValue);
  22113. };
  22114. attr.$observe('value', ctrl.$render);
  22115. }
  22116. function parseConstantExpr($parse, context, name, expression, fallback) {
  22117. var parseFn;
  22118. if (isDefined(expression)) {
  22119. parseFn = $parse(expression);
  22120. if (!parseFn.constant) {
  22121. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  22122. '`{1}`.', name, expression);
  22123. }
  22124. return parseFn(context);
  22125. }
  22126. return fallback;
  22127. }
  22128. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  22129. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  22130. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  22131. var listener = function(ev) {
  22132. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  22133. };
  22134. element.on('click', listener);
  22135. ctrl.$render = function() {
  22136. element[0].checked = ctrl.$viewValue;
  22137. };
  22138. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  22139. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  22140. // it to a boolean.
  22141. ctrl.$isEmpty = function(value) {
  22142. return value === false;
  22143. };
  22144. ctrl.$formatters.push(function(value) {
  22145. return equals(value, trueValue);
  22146. });
  22147. ctrl.$parsers.push(function(value) {
  22148. return value ? trueValue : falseValue;
  22149. });
  22150. }
  22151. /**
  22152. * @ngdoc directive
  22153. * @name textarea
  22154. * @restrict E
  22155. *
  22156. * @description
  22157. * HTML textarea element control with angular data-binding. The data-binding and validation
  22158. * properties of this element are exactly the same as those of the
  22159. * {@link ng.directive:input input element}.
  22160. *
  22161. * @param {string} ngModel Assignable angular expression to data-bind to.
  22162. * @param {string=} name Property name of the form under which the control is published.
  22163. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22164. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22165. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22166. * `required` when you want to data-bind to the `required` attribute.
  22167. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22168. * minlength.
  22169. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22170. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  22171. * length.
  22172. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22173. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22174. * If the expression evaluates to a RegExp object, then this is used directly.
  22175. * If the expression evaluates to a string, then it will be converted to a RegExp
  22176. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22177. * `new RegExp('^abc$')`.<br />
  22178. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22179. * start at the index of the last search's match, thus not taking the whole input value into
  22180. * account.
  22181. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22182. * interaction with the input element.
  22183. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  22184. */
  22185. /**
  22186. * @ngdoc directive
  22187. * @name input
  22188. * @restrict E
  22189. *
  22190. * @description
  22191. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  22192. * input state control, and validation.
  22193. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  22194. *
  22195. * <div class="alert alert-warning">
  22196. * **Note:** Not every feature offered is available for all input types.
  22197. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  22198. * </div>
  22199. *
  22200. * @param {string} ngModel Assignable angular expression to data-bind to.
  22201. * @param {string=} name Property name of the form under which the control is published.
  22202. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22203. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  22204. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22205. * minlength.
  22206. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22207. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  22208. * length.
  22209. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22210. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22211. * If the expression evaluates to a RegExp object, then this is used directly.
  22212. * If the expression evaluates to a string, then it will be converted to a RegExp
  22213. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22214. * `new RegExp('^abc$')`.<br />
  22215. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22216. * start at the index of the last search's match, thus not taking the whole input value into
  22217. * account.
  22218. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22219. * interaction with the input element.
  22220. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  22221. * This parameter is ignored for input[type=password] controls, which will never trim the
  22222. * input.
  22223. *
  22224. * @example
  22225. <example name="input-directive" module="inputExample">
  22226. <file name="index.html">
  22227. <script>
  22228. angular.module('inputExample', [])
  22229. .controller('ExampleController', ['$scope', function($scope) {
  22230. $scope.user = {name: 'guest', last: 'visitor'};
  22231. }]);
  22232. </script>
  22233. <div ng-controller="ExampleController">
  22234. <form name="myForm">
  22235. <label>
  22236. User name:
  22237. <input type="text" name="userName" ng-model="user.name" required>
  22238. </label>
  22239. <div role="alert">
  22240. <span class="error" ng-show="myForm.userName.$error.required">
  22241. Required!</span>
  22242. </div>
  22243. <label>
  22244. Last name:
  22245. <input type="text" name="lastName" ng-model="user.last"
  22246. ng-minlength="3" ng-maxlength="10">
  22247. </label>
  22248. <div role="alert">
  22249. <span class="error" ng-show="myForm.lastName.$error.minlength">
  22250. Too short!</span>
  22251. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  22252. Too long!</span>
  22253. </div>
  22254. </form>
  22255. <hr>
  22256. <tt>user = {{user}}</tt><br/>
  22257. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  22258. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  22259. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  22260. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  22261. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22262. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22263. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  22264. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  22265. </div>
  22266. </file>
  22267. <file name="protractor.js" type="protractor">
  22268. var user = element(by.exactBinding('user'));
  22269. var userNameValid = element(by.binding('myForm.userName.$valid'));
  22270. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  22271. var lastNameError = element(by.binding('myForm.lastName.$error'));
  22272. var formValid = element(by.binding('myForm.$valid'));
  22273. var userNameInput = element(by.model('user.name'));
  22274. var userLastInput = element(by.model('user.last'));
  22275. it('should initialize to model', function() {
  22276. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  22277. expect(userNameValid.getText()).toContain('true');
  22278. expect(formValid.getText()).toContain('true');
  22279. });
  22280. it('should be invalid if empty when required', function() {
  22281. userNameInput.clear();
  22282. userNameInput.sendKeys('');
  22283. expect(user.getText()).toContain('{"last":"visitor"}');
  22284. expect(userNameValid.getText()).toContain('false');
  22285. expect(formValid.getText()).toContain('false');
  22286. });
  22287. it('should be valid if empty when min length is set', function() {
  22288. userLastInput.clear();
  22289. userLastInput.sendKeys('');
  22290. expect(user.getText()).toContain('{"name":"guest","last":""}');
  22291. expect(lastNameValid.getText()).toContain('true');
  22292. expect(formValid.getText()).toContain('true');
  22293. });
  22294. it('should be invalid if less than required min length', function() {
  22295. userLastInput.clear();
  22296. userLastInput.sendKeys('xx');
  22297. expect(user.getText()).toContain('{"name":"guest"}');
  22298. expect(lastNameValid.getText()).toContain('false');
  22299. expect(lastNameError.getText()).toContain('minlength');
  22300. expect(formValid.getText()).toContain('false');
  22301. });
  22302. it('should be invalid if longer than max length', function() {
  22303. userLastInput.clear();
  22304. userLastInput.sendKeys('some ridiculously long name');
  22305. expect(user.getText()).toContain('{"name":"guest"}');
  22306. expect(lastNameValid.getText()).toContain('false');
  22307. expect(lastNameError.getText()).toContain('maxlength');
  22308. expect(formValid.getText()).toContain('false');
  22309. });
  22310. </file>
  22311. </example>
  22312. */
  22313. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  22314. function($browser, $sniffer, $filter, $parse) {
  22315. return {
  22316. restrict: 'E',
  22317. require: ['?ngModel'],
  22318. link: {
  22319. pre: function(scope, element, attr, ctrls) {
  22320. if (ctrls[0]) {
  22321. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  22322. $browser, $filter, $parse);
  22323. }
  22324. }
  22325. }
  22326. };
  22327. }];
  22328. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  22329. /**
  22330. * @ngdoc directive
  22331. * @name ngValue
  22332. *
  22333. * @description
  22334. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  22335. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  22336. * the bound value.
  22337. *
  22338. * `ngValue` is useful when dynamically generating lists of radio buttons using
  22339. * {@link ngRepeat `ngRepeat`}, as shown below.
  22340. *
  22341. * Likewise, `ngValue` can be used to generate `<option>` elements for
  22342. * the {@link select `select`} element. In that case however, only strings are supported
  22343. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  22344. * Support for `select` models with non-string values is available via `ngOptions`.
  22345. *
  22346. * @element input
  22347. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  22348. * of the `input` element
  22349. *
  22350. * @example
  22351. <example name="ngValue-directive" module="valueExample">
  22352. <file name="index.html">
  22353. <script>
  22354. angular.module('valueExample', [])
  22355. .controller('ExampleController', ['$scope', function($scope) {
  22356. $scope.names = ['pizza', 'unicorns', 'robots'];
  22357. $scope.my = { favorite: 'unicorns' };
  22358. }]);
  22359. </script>
  22360. <form ng-controller="ExampleController">
  22361. <h2>Which is your favorite?</h2>
  22362. <label ng-repeat="name in names" for="{{name}}">
  22363. {{name}}
  22364. <input type="radio"
  22365. ng-model="my.favorite"
  22366. ng-value="name"
  22367. id="{{name}}"
  22368. name="favorite">
  22369. </label>
  22370. <div>You chose {{my.favorite}}</div>
  22371. </form>
  22372. </file>
  22373. <file name="protractor.js" type="protractor">
  22374. var favorite = element(by.binding('my.favorite'));
  22375. it('should initialize to model', function() {
  22376. expect(favorite.getText()).toContain('unicorns');
  22377. });
  22378. it('should bind the values to the inputs', function() {
  22379. element.all(by.model('my.favorite')).get(0).click();
  22380. expect(favorite.getText()).toContain('pizza');
  22381. });
  22382. </file>
  22383. </example>
  22384. */
  22385. var ngValueDirective = function() {
  22386. return {
  22387. restrict: 'A',
  22388. priority: 100,
  22389. compile: function(tpl, tplAttr) {
  22390. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  22391. return function ngValueConstantLink(scope, elm, attr) {
  22392. attr.$set('value', scope.$eval(attr.ngValue));
  22393. };
  22394. } else {
  22395. return function ngValueLink(scope, elm, attr) {
  22396. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  22397. attr.$set('value', value);
  22398. });
  22399. };
  22400. }
  22401. }
  22402. };
  22403. };
  22404. /**
  22405. * @ngdoc directive
  22406. * @name ngBind
  22407. * @restrict AC
  22408. *
  22409. * @description
  22410. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  22411. * with the value of a given expression, and to update the text content when the value of that
  22412. * expression changes.
  22413. *
  22414. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  22415. * `{{ expression }}` which is similar but less verbose.
  22416. *
  22417. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  22418. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  22419. * element attribute, it makes the bindings invisible to the user while the page is loading.
  22420. *
  22421. * An alternative solution to this problem would be using the
  22422. * {@link ng.directive:ngCloak ngCloak} directive.
  22423. *
  22424. *
  22425. * @element ANY
  22426. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  22427. *
  22428. * @example
  22429. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  22430. <example module="bindExample">
  22431. <file name="index.html">
  22432. <script>
  22433. angular.module('bindExample', [])
  22434. .controller('ExampleController', ['$scope', function($scope) {
  22435. $scope.name = 'Whirled';
  22436. }]);
  22437. </script>
  22438. <div ng-controller="ExampleController">
  22439. <label>Enter name: <input type="text" ng-model="name"></label><br>
  22440. Hello <span ng-bind="name"></span>!
  22441. </div>
  22442. </file>
  22443. <file name="protractor.js" type="protractor">
  22444. it('should check ng-bind', function() {
  22445. var nameInput = element(by.model('name'));
  22446. expect(element(by.binding('name')).getText()).toBe('Whirled');
  22447. nameInput.clear();
  22448. nameInput.sendKeys('world');
  22449. expect(element(by.binding('name')).getText()).toBe('world');
  22450. });
  22451. </file>
  22452. </example>
  22453. */
  22454. var ngBindDirective = ['$compile', function($compile) {
  22455. return {
  22456. restrict: 'AC',
  22457. compile: function ngBindCompile(templateElement) {
  22458. $compile.$$addBindingClass(templateElement);
  22459. return function ngBindLink(scope, element, attr) {
  22460. $compile.$$addBindingInfo(element, attr.ngBind);
  22461. element = element[0];
  22462. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  22463. element.textContent = isUndefined(value) ? '' : value;
  22464. });
  22465. };
  22466. }
  22467. };
  22468. }];
  22469. /**
  22470. * @ngdoc directive
  22471. * @name ngBindTemplate
  22472. *
  22473. * @description
  22474. * The `ngBindTemplate` directive specifies that the element
  22475. * text content should be replaced with the interpolation of the template
  22476. * in the `ngBindTemplate` attribute.
  22477. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  22478. * expressions. This directive is needed since some HTML elements
  22479. * (such as TITLE and OPTION) cannot contain SPAN elements.
  22480. *
  22481. * @element ANY
  22482. * @param {string} ngBindTemplate template of form
  22483. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  22484. *
  22485. * @example
  22486. * Try it here: enter text in text box and watch the greeting change.
  22487. <example module="bindExample">
  22488. <file name="index.html">
  22489. <script>
  22490. angular.module('bindExample', [])
  22491. .controller('ExampleController', ['$scope', function($scope) {
  22492. $scope.salutation = 'Hello';
  22493. $scope.name = 'World';
  22494. }]);
  22495. </script>
  22496. <div ng-controller="ExampleController">
  22497. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  22498. <label>Name: <input type="text" ng-model="name"></label><br>
  22499. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  22500. </div>
  22501. </file>
  22502. <file name="protractor.js" type="protractor">
  22503. it('should check ng-bind', function() {
  22504. var salutationElem = element(by.binding('salutation'));
  22505. var salutationInput = element(by.model('salutation'));
  22506. var nameInput = element(by.model('name'));
  22507. expect(salutationElem.getText()).toBe('Hello World!');
  22508. salutationInput.clear();
  22509. salutationInput.sendKeys('Greetings');
  22510. nameInput.clear();
  22511. nameInput.sendKeys('user');
  22512. expect(salutationElem.getText()).toBe('Greetings user!');
  22513. });
  22514. </file>
  22515. </example>
  22516. */
  22517. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  22518. return {
  22519. compile: function ngBindTemplateCompile(templateElement) {
  22520. $compile.$$addBindingClass(templateElement);
  22521. return function ngBindTemplateLink(scope, element, attr) {
  22522. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  22523. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  22524. element = element[0];
  22525. attr.$observe('ngBindTemplate', function(value) {
  22526. element.textContent = isUndefined(value) ? '' : value;
  22527. });
  22528. };
  22529. }
  22530. };
  22531. }];
  22532. /**
  22533. * @ngdoc directive
  22534. * @name ngBindHtml
  22535. *
  22536. * @description
  22537. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  22538. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  22539. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  22540. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  22541. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  22542. *
  22543. * You may also bypass sanitization for values you know are safe. To do so, bind to
  22544. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  22545. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  22546. *
  22547. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  22548. * will have an exception (instead of an exploit.)
  22549. *
  22550. * @element ANY
  22551. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  22552. *
  22553. * @example
  22554. <example module="bindHtmlExample" deps="angular-sanitize.js">
  22555. <file name="index.html">
  22556. <div ng-controller="ExampleController">
  22557. <p ng-bind-html="myHTML"></p>
  22558. </div>
  22559. </file>
  22560. <file name="script.js">
  22561. angular.module('bindHtmlExample', ['ngSanitize'])
  22562. .controller('ExampleController', ['$scope', function($scope) {
  22563. $scope.myHTML =
  22564. 'I am an <code>HTML</code>string with ' +
  22565. '<a href="#">links!</a> and other <em>stuff</em>';
  22566. }]);
  22567. </file>
  22568. <file name="protractor.js" type="protractor">
  22569. it('should check ng-bind-html', function() {
  22570. expect(element(by.binding('myHTML')).getText()).toBe(
  22571. 'I am an HTMLstring with links! and other stuff');
  22572. });
  22573. </file>
  22574. </example>
  22575. */
  22576. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  22577. return {
  22578. restrict: 'A',
  22579. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  22580. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  22581. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  22582. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  22583. return $sce.valueOf(val);
  22584. });
  22585. $compile.$$addBindingClass(tElement);
  22586. return function ngBindHtmlLink(scope, element, attr) {
  22587. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  22588. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  22589. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  22590. var value = ngBindHtmlGetter(scope);
  22591. element.html($sce.getTrustedHtml(value) || '');
  22592. });
  22593. };
  22594. }
  22595. };
  22596. }];
  22597. /**
  22598. * @ngdoc directive
  22599. * @name ngChange
  22600. *
  22601. * @description
  22602. * Evaluate the given expression when the user changes the input.
  22603. * The expression is evaluated immediately, unlike the JavaScript onchange event
  22604. * which only triggers at the end of a change (usually, when the user leaves the
  22605. * form element or presses the return key).
  22606. *
  22607. * The `ngChange` expression is only evaluated when a change in the input value causes
  22608. * a new value to be committed to the model.
  22609. *
  22610. * It will not be evaluated:
  22611. * * if the value returned from the `$parsers` transformation pipeline has not changed
  22612. * * if the input has continued to be invalid since the model will stay `null`
  22613. * * if the model is changed programmatically and not by a change to the input value
  22614. *
  22615. *
  22616. * Note, this directive requires `ngModel` to be present.
  22617. *
  22618. * @element input
  22619. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  22620. * in input value.
  22621. *
  22622. * @example
  22623. * <example name="ngChange-directive" module="changeExample">
  22624. * <file name="index.html">
  22625. * <script>
  22626. * angular.module('changeExample', [])
  22627. * .controller('ExampleController', ['$scope', function($scope) {
  22628. * $scope.counter = 0;
  22629. * $scope.change = function() {
  22630. * $scope.counter++;
  22631. * };
  22632. * }]);
  22633. * </script>
  22634. * <div ng-controller="ExampleController">
  22635. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  22636. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  22637. * <label for="ng-change-example2">Confirmed</label><br />
  22638. * <tt>debug = {{confirmed}}</tt><br/>
  22639. * <tt>counter = {{counter}}</tt><br/>
  22640. * </div>
  22641. * </file>
  22642. * <file name="protractor.js" type="protractor">
  22643. * var counter = element(by.binding('counter'));
  22644. * var debug = element(by.binding('confirmed'));
  22645. *
  22646. * it('should evaluate the expression if changing from view', function() {
  22647. * expect(counter.getText()).toContain('0');
  22648. *
  22649. * element(by.id('ng-change-example1')).click();
  22650. *
  22651. * expect(counter.getText()).toContain('1');
  22652. * expect(debug.getText()).toContain('true');
  22653. * });
  22654. *
  22655. * it('should not evaluate the expression if changing from model', function() {
  22656. * element(by.id('ng-change-example2')).click();
  22657. * expect(counter.getText()).toContain('0');
  22658. * expect(debug.getText()).toContain('true');
  22659. * });
  22660. * </file>
  22661. * </example>
  22662. */
  22663. var ngChangeDirective = valueFn({
  22664. restrict: 'A',
  22665. require: 'ngModel',
  22666. link: function(scope, element, attr, ctrl) {
  22667. ctrl.$viewChangeListeners.push(function() {
  22668. scope.$eval(attr.ngChange);
  22669. });
  22670. }
  22671. });
  22672. function classDirective(name, selector) {
  22673. name = 'ngClass' + name;
  22674. return ['$animate', function($animate) {
  22675. return {
  22676. restrict: 'AC',
  22677. link: function(scope, element, attr) {
  22678. var oldVal;
  22679. scope.$watch(attr[name], ngClassWatchAction, true);
  22680. attr.$observe('class', function(value) {
  22681. ngClassWatchAction(scope.$eval(attr[name]));
  22682. });
  22683. if (name !== 'ngClass') {
  22684. scope.$watch('$index', function($index, old$index) {
  22685. // jshint bitwise: false
  22686. var mod = $index & 1;
  22687. if (mod !== (old$index & 1)) {
  22688. var classes = arrayClasses(scope.$eval(attr[name]));
  22689. mod === selector ?
  22690. addClasses(classes) :
  22691. removeClasses(classes);
  22692. }
  22693. });
  22694. }
  22695. function addClasses(classes) {
  22696. var newClasses = digestClassCounts(classes, 1);
  22697. attr.$addClass(newClasses);
  22698. }
  22699. function removeClasses(classes) {
  22700. var newClasses = digestClassCounts(classes, -1);
  22701. attr.$removeClass(newClasses);
  22702. }
  22703. function digestClassCounts(classes, count) {
  22704. // Use createMap() to prevent class assumptions involving property
  22705. // names in Object.prototype
  22706. var classCounts = element.data('$classCounts') || createMap();
  22707. var classesToUpdate = [];
  22708. forEach(classes, function(className) {
  22709. if (count > 0 || classCounts[className]) {
  22710. classCounts[className] = (classCounts[className] || 0) + count;
  22711. if (classCounts[className] === +(count > 0)) {
  22712. classesToUpdate.push(className);
  22713. }
  22714. }
  22715. });
  22716. element.data('$classCounts', classCounts);
  22717. return classesToUpdate.join(' ');
  22718. }
  22719. function updateClasses(oldClasses, newClasses) {
  22720. var toAdd = arrayDifference(newClasses, oldClasses);
  22721. var toRemove = arrayDifference(oldClasses, newClasses);
  22722. toAdd = digestClassCounts(toAdd, 1);
  22723. toRemove = digestClassCounts(toRemove, -1);
  22724. if (toAdd && toAdd.length) {
  22725. $animate.addClass(element, toAdd);
  22726. }
  22727. if (toRemove && toRemove.length) {
  22728. $animate.removeClass(element, toRemove);
  22729. }
  22730. }
  22731. function ngClassWatchAction(newVal) {
  22732. // jshint bitwise: false
  22733. if (selector === true || (scope.$index & 1) === selector) {
  22734. // jshint bitwise: true
  22735. var newClasses = arrayClasses(newVal || []);
  22736. if (!oldVal) {
  22737. addClasses(newClasses);
  22738. } else if (!equals(newVal,oldVal)) {
  22739. var oldClasses = arrayClasses(oldVal);
  22740. updateClasses(oldClasses, newClasses);
  22741. }
  22742. }
  22743. if (isArray(newVal)) {
  22744. oldVal = newVal.map(function(v) { return shallowCopy(v); });
  22745. } else {
  22746. oldVal = shallowCopy(newVal);
  22747. }
  22748. }
  22749. }
  22750. };
  22751. function arrayDifference(tokens1, tokens2) {
  22752. var values = [];
  22753. outer:
  22754. for (var i = 0; i < tokens1.length; i++) {
  22755. var token = tokens1[i];
  22756. for (var j = 0; j < tokens2.length; j++) {
  22757. if (token == tokens2[j]) continue outer;
  22758. }
  22759. values.push(token);
  22760. }
  22761. return values;
  22762. }
  22763. function arrayClasses(classVal) {
  22764. var classes = [];
  22765. if (isArray(classVal)) {
  22766. forEach(classVal, function(v) {
  22767. classes = classes.concat(arrayClasses(v));
  22768. });
  22769. return classes;
  22770. } else if (isString(classVal)) {
  22771. return classVal.split(' ');
  22772. } else if (isObject(classVal)) {
  22773. forEach(classVal, function(v, k) {
  22774. if (v) {
  22775. classes = classes.concat(k.split(' '));
  22776. }
  22777. });
  22778. return classes;
  22779. }
  22780. return classVal;
  22781. }
  22782. }];
  22783. }
  22784. /**
  22785. * @ngdoc directive
  22786. * @name ngClass
  22787. * @restrict AC
  22788. *
  22789. * @description
  22790. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  22791. * an expression that represents all classes to be added.
  22792. *
  22793. * The directive operates in three different ways, depending on which of three types the expression
  22794. * evaluates to:
  22795. *
  22796. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  22797. * names.
  22798. *
  22799. * 2. If the expression evaluates to an object, then for each key-value pair of the
  22800. * object with a truthy value the corresponding key is used as a class name.
  22801. *
  22802. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  22803. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  22804. * to give you more control over what CSS classes appear. See the code below for an example of this.
  22805. *
  22806. *
  22807. * The directive won't add duplicate classes if a particular class was already set.
  22808. *
  22809. * When the expression changes, the previously added classes are removed and only then are the
  22810. * new classes added.
  22811. *
  22812. * @knownIssue
  22813. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  22814. * attribute, when using the `ngClass` directive on the same element.
  22815. * See {@link guide/interpolation#known-issues here} for more info.
  22816. *
  22817. * @animations
  22818. * | Animation | Occurs |
  22819. * |----------------------------------|-------------------------------------|
  22820. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  22821. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  22822. *
  22823. * @element ANY
  22824. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  22825. * of the evaluation can be a string representing space delimited class
  22826. * names, an array, or a map of class names to boolean values. In the case of a map, the
  22827. * names of the properties whose values are truthy will be added as css classes to the
  22828. * element.
  22829. *
  22830. * @example Example that demonstrates basic bindings via ngClass directive.
  22831. <example>
  22832. <file name="index.html">
  22833. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  22834. <label>
  22835. <input type="checkbox" ng-model="deleted">
  22836. deleted (apply "strike" class)
  22837. </label><br>
  22838. <label>
  22839. <input type="checkbox" ng-model="important">
  22840. important (apply "bold" class)
  22841. </label><br>
  22842. <label>
  22843. <input type="checkbox" ng-model="error">
  22844. error (apply "has-error" class)
  22845. </label>
  22846. <hr>
  22847. <p ng-class="style">Using String Syntax</p>
  22848. <input type="text" ng-model="style"
  22849. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  22850. <hr>
  22851. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  22852. <input ng-model="style1"
  22853. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  22854. <input ng-model="style2"
  22855. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  22856. <input ng-model="style3"
  22857. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  22858. <hr>
  22859. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  22860. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  22861. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  22862. </file>
  22863. <file name="style.css">
  22864. .strike {
  22865. text-decoration: line-through;
  22866. }
  22867. .bold {
  22868. font-weight: bold;
  22869. }
  22870. .red {
  22871. color: red;
  22872. }
  22873. .has-error {
  22874. color: red;
  22875. background-color: yellow;
  22876. }
  22877. .orange {
  22878. color: orange;
  22879. }
  22880. </file>
  22881. <file name="protractor.js" type="protractor">
  22882. var ps = element.all(by.css('p'));
  22883. it('should let you toggle the class', function() {
  22884. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  22885. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  22886. element(by.model('important')).click();
  22887. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  22888. element(by.model('error')).click();
  22889. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  22890. });
  22891. it('should let you toggle string example', function() {
  22892. expect(ps.get(1).getAttribute('class')).toBe('');
  22893. element(by.model('style')).clear();
  22894. element(by.model('style')).sendKeys('red');
  22895. expect(ps.get(1).getAttribute('class')).toBe('red');
  22896. });
  22897. it('array example should have 3 classes', function() {
  22898. expect(ps.get(2).getAttribute('class')).toBe('');
  22899. element(by.model('style1')).sendKeys('bold');
  22900. element(by.model('style2')).sendKeys('strike');
  22901. element(by.model('style3')).sendKeys('red');
  22902. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  22903. });
  22904. it('array with map example should have 2 classes', function() {
  22905. expect(ps.last().getAttribute('class')).toBe('');
  22906. element(by.model('style4')).sendKeys('bold');
  22907. element(by.model('warning')).click();
  22908. expect(ps.last().getAttribute('class')).toBe('bold orange');
  22909. });
  22910. </file>
  22911. </example>
  22912. ## Animations
  22913. The example below demonstrates how to perform animations using ngClass.
  22914. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22915. <file name="index.html">
  22916. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  22917. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  22918. <br>
  22919. <span class="base-class" ng-class="myVar">Sample Text</span>
  22920. </file>
  22921. <file name="style.css">
  22922. .base-class {
  22923. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22924. }
  22925. .base-class.my-class {
  22926. color: red;
  22927. font-size:3em;
  22928. }
  22929. </file>
  22930. <file name="protractor.js" type="protractor">
  22931. it('should check ng-class', function() {
  22932. expect(element(by.css('.base-class')).getAttribute('class')).not.
  22933. toMatch(/my-class/);
  22934. element(by.id('setbtn')).click();
  22935. expect(element(by.css('.base-class')).getAttribute('class')).
  22936. toMatch(/my-class/);
  22937. element(by.id('clearbtn')).click();
  22938. expect(element(by.css('.base-class')).getAttribute('class')).not.
  22939. toMatch(/my-class/);
  22940. });
  22941. </file>
  22942. </example>
  22943. ## ngClass and pre-existing CSS3 Transitions/Animations
  22944. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  22945. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  22946. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  22947. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  22948. {@link $animate#removeClass $animate.removeClass}.
  22949. */
  22950. var ngClassDirective = classDirective('', true);
  22951. /**
  22952. * @ngdoc directive
  22953. * @name ngClassOdd
  22954. * @restrict AC
  22955. *
  22956. * @description
  22957. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  22958. * {@link ng.directive:ngClass ngClass}, except they work in
  22959. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  22960. *
  22961. * This directive can be applied only within the scope of an
  22962. * {@link ng.directive:ngRepeat ngRepeat}.
  22963. *
  22964. * @element ANY
  22965. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  22966. * of the evaluation can be a string representing space delimited class names or an array.
  22967. *
  22968. * @example
  22969. <example>
  22970. <file name="index.html">
  22971. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  22972. <li ng-repeat="name in names">
  22973. <span ng-class-odd="'odd'" ng-class-even="'even'">
  22974. {{name}}
  22975. </span>
  22976. </li>
  22977. </ol>
  22978. </file>
  22979. <file name="style.css">
  22980. .odd {
  22981. color: red;
  22982. }
  22983. .even {
  22984. color: blue;
  22985. }
  22986. </file>
  22987. <file name="protractor.js" type="protractor">
  22988. it('should check ng-class-odd and ng-class-even', function() {
  22989. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  22990. toMatch(/odd/);
  22991. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  22992. toMatch(/even/);
  22993. });
  22994. </file>
  22995. </example>
  22996. */
  22997. var ngClassOddDirective = classDirective('Odd', 0);
  22998. /**
  22999. * @ngdoc directive
  23000. * @name ngClassEven
  23001. * @restrict AC
  23002. *
  23003. * @description
  23004. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23005. * {@link ng.directive:ngClass ngClass}, except they work in
  23006. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23007. *
  23008. * This directive can be applied only within the scope of an
  23009. * {@link ng.directive:ngRepeat ngRepeat}.
  23010. *
  23011. * @element ANY
  23012. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  23013. * result of the evaluation can be a string representing space delimited class names or an array.
  23014. *
  23015. * @example
  23016. <example>
  23017. <file name="index.html">
  23018. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23019. <li ng-repeat="name in names">
  23020. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23021. {{name}} &nbsp; &nbsp; &nbsp;
  23022. </span>
  23023. </li>
  23024. </ol>
  23025. </file>
  23026. <file name="style.css">
  23027. .odd {
  23028. color: red;
  23029. }
  23030. .even {
  23031. color: blue;
  23032. }
  23033. </file>
  23034. <file name="protractor.js" type="protractor">
  23035. it('should check ng-class-odd and ng-class-even', function() {
  23036. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  23037. toMatch(/odd/);
  23038. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  23039. toMatch(/even/);
  23040. });
  23041. </file>
  23042. </example>
  23043. */
  23044. var ngClassEvenDirective = classDirective('Even', 1);
  23045. /**
  23046. * @ngdoc directive
  23047. * @name ngCloak
  23048. * @restrict AC
  23049. *
  23050. * @description
  23051. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  23052. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  23053. * directive to avoid the undesirable flicker effect caused by the html template display.
  23054. *
  23055. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  23056. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  23057. * of the browser view.
  23058. *
  23059. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  23060. * `angular.min.js`.
  23061. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  23062. *
  23063. * ```css
  23064. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  23065. * display: none !important;
  23066. * }
  23067. * ```
  23068. *
  23069. * When this css rule is loaded by the browser, all html elements (including their children) that
  23070. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  23071. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  23072. * the compiled element visible.
  23073. *
  23074. * For the best result, the `angular.js` script must be loaded in the head section of the html
  23075. * document; alternatively, the css rule above must be included in the external stylesheet of the
  23076. * application.
  23077. *
  23078. * @element ANY
  23079. *
  23080. * @example
  23081. <example>
  23082. <file name="index.html">
  23083. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  23084. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  23085. </file>
  23086. <file name="protractor.js" type="protractor">
  23087. it('should remove the template directive and css class', function() {
  23088. expect($('#template1').getAttribute('ng-cloak')).
  23089. toBeNull();
  23090. expect($('#template2').getAttribute('ng-cloak')).
  23091. toBeNull();
  23092. });
  23093. </file>
  23094. </example>
  23095. *
  23096. */
  23097. var ngCloakDirective = ngDirective({
  23098. compile: function(element, attr) {
  23099. attr.$set('ngCloak', undefined);
  23100. element.removeClass('ng-cloak');
  23101. }
  23102. });
  23103. /**
  23104. * @ngdoc directive
  23105. * @name ngController
  23106. *
  23107. * @description
  23108. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  23109. * supports the principles behind the Model-View-Controller design pattern.
  23110. *
  23111. * MVC components in angular:
  23112. *
  23113. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  23114. * are accessed through bindings.
  23115. * * View — The template (HTML with data bindings) that is rendered into the View.
  23116. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  23117. * logic behind the application to decorate the scope with functions and values
  23118. *
  23119. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  23120. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  23121. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  23122. * and executed twice.
  23123. *
  23124. * @element ANY
  23125. * @scope
  23126. * @priority 500
  23127. * @param {expression} ngController Name of a constructor function registered with the current
  23128. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  23129. * that on the current scope evaluates to a constructor function.
  23130. *
  23131. * The controller instance can be published into a scope property by specifying
  23132. * `ng-controller="as propertyName"`.
  23133. *
  23134. * If the current `$controllerProvider` is configured to use globals (via
  23135. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  23136. * also be the name of a globally accessible constructor function (not recommended).
  23137. *
  23138. * @example
  23139. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  23140. * greeting are methods declared on the controller (see source tab). These methods can
  23141. * easily be called from the angular markup. Any changes to the data are automatically reflected
  23142. * in the View without the need for a manual update.
  23143. *
  23144. * Two different declaration styles are included below:
  23145. *
  23146. * * one binds methods and properties directly onto the controller using `this`:
  23147. * `ng-controller="SettingsController1 as settings"`
  23148. * * one injects `$scope` into the controller:
  23149. * `ng-controller="SettingsController2"`
  23150. *
  23151. * The second option is more common in the Angular community, and is generally used in boilerplates
  23152. * and in this guide. However, there are advantages to binding properties directly to the controller
  23153. * and avoiding scope.
  23154. *
  23155. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  23156. * multiple controllers apply to an element.
  23157. * * If you are writing your controllers as classes you have easier access to the properties and
  23158. * methods, which will appear on the scope, from inside the controller code.
  23159. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  23160. * inheritance masking primitives.
  23161. *
  23162. * This example demonstrates the `controller as` syntax.
  23163. *
  23164. * <example name="ngControllerAs" module="controllerAsExample">
  23165. * <file name="index.html">
  23166. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  23167. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  23168. * <button ng-click="settings.greet()">greet</button><br/>
  23169. * Contact:
  23170. * <ul>
  23171. * <li ng-repeat="contact in settings.contacts">
  23172. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  23173. * <option>phone</option>
  23174. * <option>email</option>
  23175. * </select>
  23176. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  23177. * <button ng-click="settings.clearContact(contact)">clear</button>
  23178. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  23179. * </li>
  23180. * <li><button ng-click="settings.addContact()">add</button></li>
  23181. * </ul>
  23182. * </div>
  23183. * </file>
  23184. * <file name="app.js">
  23185. * angular.module('controllerAsExample', [])
  23186. * .controller('SettingsController1', SettingsController1);
  23187. *
  23188. * function SettingsController1() {
  23189. * this.name = "John Smith";
  23190. * this.contacts = [
  23191. * {type: 'phone', value: '408 555 1212'},
  23192. * {type: 'email', value: 'john.smith@example.org'} ];
  23193. * }
  23194. *
  23195. * SettingsController1.prototype.greet = function() {
  23196. * alert(this.name);
  23197. * };
  23198. *
  23199. * SettingsController1.prototype.addContact = function() {
  23200. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  23201. * };
  23202. *
  23203. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  23204. * var index = this.contacts.indexOf(contactToRemove);
  23205. * this.contacts.splice(index, 1);
  23206. * };
  23207. *
  23208. * SettingsController1.prototype.clearContact = function(contact) {
  23209. * contact.type = 'phone';
  23210. * contact.value = '';
  23211. * };
  23212. * </file>
  23213. * <file name="protractor.js" type="protractor">
  23214. * it('should check controller as', function() {
  23215. * var container = element(by.id('ctrl-as-exmpl'));
  23216. * expect(container.element(by.model('settings.name'))
  23217. * .getAttribute('value')).toBe('John Smith');
  23218. *
  23219. * var firstRepeat =
  23220. * container.element(by.repeater('contact in settings.contacts').row(0));
  23221. * var secondRepeat =
  23222. * container.element(by.repeater('contact in settings.contacts').row(1));
  23223. *
  23224. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23225. * .toBe('408 555 1212');
  23226. *
  23227. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  23228. * .toBe('john.smith@example.org');
  23229. *
  23230. * firstRepeat.element(by.buttonText('clear')).click();
  23231. *
  23232. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23233. * .toBe('');
  23234. *
  23235. * container.element(by.buttonText('add')).click();
  23236. *
  23237. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  23238. * .element(by.model('contact.value'))
  23239. * .getAttribute('value'))
  23240. * .toBe('yourname@example.org');
  23241. * });
  23242. * </file>
  23243. * </example>
  23244. *
  23245. * This example demonstrates the "attach to `$scope`" style of controller.
  23246. *
  23247. * <example name="ngController" module="controllerExample">
  23248. * <file name="index.html">
  23249. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  23250. * <label>Name: <input type="text" ng-model="name"/></label>
  23251. * <button ng-click="greet()">greet</button><br/>
  23252. * Contact:
  23253. * <ul>
  23254. * <li ng-repeat="contact in contacts">
  23255. * <select ng-model="contact.type" id="select_{{$index}}">
  23256. * <option>phone</option>
  23257. * <option>email</option>
  23258. * </select>
  23259. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  23260. * <button ng-click="clearContact(contact)">clear</button>
  23261. * <button ng-click="removeContact(contact)">X</button>
  23262. * </li>
  23263. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  23264. * </ul>
  23265. * </div>
  23266. * </file>
  23267. * <file name="app.js">
  23268. * angular.module('controllerExample', [])
  23269. * .controller('SettingsController2', ['$scope', SettingsController2]);
  23270. *
  23271. * function SettingsController2($scope) {
  23272. * $scope.name = "John Smith";
  23273. * $scope.contacts = [
  23274. * {type:'phone', value:'408 555 1212'},
  23275. * {type:'email', value:'john.smith@example.org'} ];
  23276. *
  23277. * $scope.greet = function() {
  23278. * alert($scope.name);
  23279. * };
  23280. *
  23281. * $scope.addContact = function() {
  23282. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  23283. * };
  23284. *
  23285. * $scope.removeContact = function(contactToRemove) {
  23286. * var index = $scope.contacts.indexOf(contactToRemove);
  23287. * $scope.contacts.splice(index, 1);
  23288. * };
  23289. *
  23290. * $scope.clearContact = function(contact) {
  23291. * contact.type = 'phone';
  23292. * contact.value = '';
  23293. * };
  23294. * }
  23295. * </file>
  23296. * <file name="protractor.js" type="protractor">
  23297. * it('should check controller', function() {
  23298. * var container = element(by.id('ctrl-exmpl'));
  23299. *
  23300. * expect(container.element(by.model('name'))
  23301. * .getAttribute('value')).toBe('John Smith');
  23302. *
  23303. * var firstRepeat =
  23304. * container.element(by.repeater('contact in contacts').row(0));
  23305. * var secondRepeat =
  23306. * container.element(by.repeater('contact in contacts').row(1));
  23307. *
  23308. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23309. * .toBe('408 555 1212');
  23310. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  23311. * .toBe('john.smith@example.org');
  23312. *
  23313. * firstRepeat.element(by.buttonText('clear')).click();
  23314. *
  23315. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23316. * .toBe('');
  23317. *
  23318. * container.element(by.buttonText('add')).click();
  23319. *
  23320. * expect(container.element(by.repeater('contact in contacts').row(2))
  23321. * .element(by.model('contact.value'))
  23322. * .getAttribute('value'))
  23323. * .toBe('yourname@example.org');
  23324. * });
  23325. * </file>
  23326. *</example>
  23327. */
  23328. var ngControllerDirective = [function() {
  23329. return {
  23330. restrict: 'A',
  23331. scope: true,
  23332. controller: '@',
  23333. priority: 500
  23334. };
  23335. }];
  23336. /**
  23337. * @ngdoc directive
  23338. * @name ngCsp
  23339. *
  23340. * @element html
  23341. * @description
  23342. *
  23343. * Angular has some features that can break certain
  23344. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  23345. *
  23346. * If you intend to implement these rules then you must tell Angular not to use these features.
  23347. *
  23348. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  23349. *
  23350. *
  23351. * The following rules affect Angular:
  23352. *
  23353. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  23354. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  23355. * increase in the speed of evaluating Angular expressions.
  23356. *
  23357. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  23358. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  23359. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  23360. * `angular-csp.css` in your HTML manually.
  23361. *
  23362. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  23363. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  23364. * however, triggers a CSP error to be logged in the console:
  23365. *
  23366. * ```
  23367. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  23368. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  23369. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  23370. * ```
  23371. *
  23372. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  23373. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  23374. * the `angular.js` file.
  23375. *
  23376. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  23377. *
  23378. * You can specify which of the CSP related Angular features should be deactivated by providing
  23379. * a value for the `ng-csp` attribute. The options are as follows:
  23380. *
  23381. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  23382. *
  23383. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  23384. *
  23385. * You can use these values in the following combinations:
  23386. *
  23387. *
  23388. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  23389. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  23390. * of Angular.
  23391. *
  23392. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  23393. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  23394. * of Angular.
  23395. *
  23396. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  23397. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  23398. *
  23399. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  23400. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  23401. *
  23402. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  23403. * styles nor use eval, which is the same as an empty: ng-csp.
  23404. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  23405. *
  23406. * @example
  23407. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  23408. ```html
  23409. <!doctype html>
  23410. <html ng-app ng-csp>
  23411. ...
  23412. ...
  23413. </html>
  23414. ```
  23415. * @example
  23416. // Note: the suffix `.csp` in the example name triggers
  23417. // csp mode in our http server!
  23418. <example name="example.csp" module="cspExample" ng-csp="true">
  23419. <file name="index.html">
  23420. <div ng-controller="MainController as ctrl">
  23421. <div>
  23422. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  23423. <span id="counter">
  23424. {{ctrl.counter}}
  23425. </span>
  23426. </div>
  23427. <div>
  23428. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  23429. <span id="evilError">
  23430. {{ctrl.evilError}}
  23431. </span>
  23432. </div>
  23433. </div>
  23434. </file>
  23435. <file name="script.js">
  23436. angular.module('cspExample', [])
  23437. .controller('MainController', function() {
  23438. this.counter = 0;
  23439. this.inc = function() {
  23440. this.counter++;
  23441. };
  23442. this.evil = function() {
  23443. // jshint evil:true
  23444. try {
  23445. eval('1+2');
  23446. } catch (e) {
  23447. this.evilError = e.message;
  23448. }
  23449. };
  23450. });
  23451. </file>
  23452. <file name="protractor.js" type="protractor">
  23453. var util, webdriver;
  23454. var incBtn = element(by.id('inc'));
  23455. var counter = element(by.id('counter'));
  23456. var evilBtn = element(by.id('evil'));
  23457. var evilError = element(by.id('evilError'));
  23458. function getAndClearSevereErrors() {
  23459. return browser.manage().logs().get('browser').then(function(browserLog) {
  23460. return browserLog.filter(function(logEntry) {
  23461. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  23462. });
  23463. });
  23464. }
  23465. function clearErrors() {
  23466. getAndClearSevereErrors();
  23467. }
  23468. function expectNoErrors() {
  23469. getAndClearSevereErrors().then(function(filteredLog) {
  23470. expect(filteredLog.length).toEqual(0);
  23471. if (filteredLog.length) {
  23472. console.log('browser console errors: ' + util.inspect(filteredLog));
  23473. }
  23474. });
  23475. }
  23476. function expectError(regex) {
  23477. getAndClearSevereErrors().then(function(filteredLog) {
  23478. var found = false;
  23479. filteredLog.forEach(function(log) {
  23480. if (log.message.match(regex)) {
  23481. found = true;
  23482. }
  23483. });
  23484. if (!found) {
  23485. throw new Error('expected an error that matches ' + regex);
  23486. }
  23487. });
  23488. }
  23489. beforeEach(function() {
  23490. util = require('util');
  23491. webdriver = require('protractor/node_modules/selenium-webdriver');
  23492. });
  23493. // For now, we only test on Chrome,
  23494. // as Safari does not load the page with Protractor's injected scripts,
  23495. // and Firefox webdriver always disables content security policy (#6358)
  23496. if (browser.params.browser !== 'chrome') {
  23497. return;
  23498. }
  23499. it('should not report errors when the page is loaded', function() {
  23500. // clear errors so we are not dependent on previous tests
  23501. clearErrors();
  23502. // Need to reload the page as the page is already loaded when
  23503. // we come here
  23504. browser.driver.getCurrentUrl().then(function(url) {
  23505. browser.get(url);
  23506. });
  23507. expectNoErrors();
  23508. });
  23509. it('should evaluate expressions', function() {
  23510. expect(counter.getText()).toEqual('0');
  23511. incBtn.click();
  23512. expect(counter.getText()).toEqual('1');
  23513. expectNoErrors();
  23514. });
  23515. it('should throw and report an error when using "eval"', function() {
  23516. evilBtn.click();
  23517. expect(evilError.getText()).toMatch(/Content Security Policy/);
  23518. expectError(/Content Security Policy/);
  23519. });
  23520. </file>
  23521. </example>
  23522. */
  23523. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  23524. // bootstrap the system (before $parse is instantiated), for this reason we just have
  23525. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  23526. /**
  23527. * @ngdoc directive
  23528. * @name ngClick
  23529. *
  23530. * @description
  23531. * The ngClick directive allows you to specify custom behavior when
  23532. * an element is clicked.
  23533. *
  23534. * @element ANY
  23535. * @priority 0
  23536. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  23537. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  23538. *
  23539. * @example
  23540. <example>
  23541. <file name="index.html">
  23542. <button ng-click="count = count + 1" ng-init="count=0">
  23543. Increment
  23544. </button>
  23545. <span>
  23546. count: {{count}}
  23547. </span>
  23548. </file>
  23549. <file name="protractor.js" type="protractor">
  23550. it('should check ng-click', function() {
  23551. expect(element(by.binding('count')).getText()).toMatch('0');
  23552. element(by.css('button')).click();
  23553. expect(element(by.binding('count')).getText()).toMatch('1');
  23554. });
  23555. </file>
  23556. </example>
  23557. */
  23558. /*
  23559. * A collection of directives that allows creation of custom event handlers that are defined as
  23560. * angular expressions and are compiled and executed within the current scope.
  23561. */
  23562. var ngEventDirectives = {};
  23563. // For events that might fire synchronously during DOM manipulation
  23564. // we need to execute their event handlers asynchronously using $evalAsync,
  23565. // so that they are not executed in an inconsistent state.
  23566. var forceAsyncEvents = {
  23567. 'blur': true,
  23568. 'focus': true
  23569. };
  23570. forEach(
  23571. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  23572. function(eventName) {
  23573. var directiveName = directiveNormalize('ng-' + eventName);
  23574. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  23575. return {
  23576. restrict: 'A',
  23577. compile: function($element, attr) {
  23578. // We expose the powerful $event object on the scope that provides access to the Window,
  23579. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  23580. // checks at the cost of speed since event handler expressions are not executed as
  23581. // frequently as regular change detection.
  23582. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  23583. return function ngEventHandler(scope, element) {
  23584. element.on(eventName, function(event) {
  23585. var callback = function() {
  23586. fn(scope, {$event:event});
  23587. };
  23588. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  23589. scope.$evalAsync(callback);
  23590. } else {
  23591. scope.$apply(callback);
  23592. }
  23593. });
  23594. };
  23595. }
  23596. };
  23597. }];
  23598. }
  23599. );
  23600. /**
  23601. * @ngdoc directive
  23602. * @name ngDblclick
  23603. *
  23604. * @description
  23605. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  23606. *
  23607. * @element ANY
  23608. * @priority 0
  23609. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  23610. * a dblclick. (The Event object is available as `$event`)
  23611. *
  23612. * @example
  23613. <example>
  23614. <file name="index.html">
  23615. <button ng-dblclick="count = count + 1" ng-init="count=0">
  23616. Increment (on double click)
  23617. </button>
  23618. count: {{count}}
  23619. </file>
  23620. </example>
  23621. */
  23622. /**
  23623. * @ngdoc directive
  23624. * @name ngMousedown
  23625. *
  23626. * @description
  23627. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  23628. *
  23629. * @element ANY
  23630. * @priority 0
  23631. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  23632. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  23633. *
  23634. * @example
  23635. <example>
  23636. <file name="index.html">
  23637. <button ng-mousedown="count = count + 1" ng-init="count=0">
  23638. Increment (on mouse down)
  23639. </button>
  23640. count: {{count}}
  23641. </file>
  23642. </example>
  23643. */
  23644. /**
  23645. * @ngdoc directive
  23646. * @name ngMouseup
  23647. *
  23648. * @description
  23649. * Specify custom behavior on mouseup event.
  23650. *
  23651. * @element ANY
  23652. * @priority 0
  23653. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  23654. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  23655. *
  23656. * @example
  23657. <example>
  23658. <file name="index.html">
  23659. <button ng-mouseup="count = count + 1" ng-init="count=0">
  23660. Increment (on mouse up)
  23661. </button>
  23662. count: {{count}}
  23663. </file>
  23664. </example>
  23665. */
  23666. /**
  23667. * @ngdoc directive
  23668. * @name ngMouseover
  23669. *
  23670. * @description
  23671. * Specify custom behavior on mouseover event.
  23672. *
  23673. * @element ANY
  23674. * @priority 0
  23675. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  23676. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  23677. *
  23678. * @example
  23679. <example>
  23680. <file name="index.html">
  23681. <button ng-mouseover="count = count + 1" ng-init="count=0">
  23682. Increment (when mouse is over)
  23683. </button>
  23684. count: {{count}}
  23685. </file>
  23686. </example>
  23687. */
  23688. /**
  23689. * @ngdoc directive
  23690. * @name ngMouseenter
  23691. *
  23692. * @description
  23693. * Specify custom behavior on mouseenter event.
  23694. *
  23695. * @element ANY
  23696. * @priority 0
  23697. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  23698. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  23699. *
  23700. * @example
  23701. <example>
  23702. <file name="index.html">
  23703. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  23704. Increment (when mouse enters)
  23705. </button>
  23706. count: {{count}}
  23707. </file>
  23708. </example>
  23709. */
  23710. /**
  23711. * @ngdoc directive
  23712. * @name ngMouseleave
  23713. *
  23714. * @description
  23715. * Specify custom behavior on mouseleave event.
  23716. *
  23717. * @element ANY
  23718. * @priority 0
  23719. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  23720. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  23721. *
  23722. * @example
  23723. <example>
  23724. <file name="index.html">
  23725. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  23726. Increment (when mouse leaves)
  23727. </button>
  23728. count: {{count}}
  23729. </file>
  23730. </example>
  23731. */
  23732. /**
  23733. * @ngdoc directive
  23734. * @name ngMousemove
  23735. *
  23736. * @description
  23737. * Specify custom behavior on mousemove event.
  23738. *
  23739. * @element ANY
  23740. * @priority 0
  23741. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  23742. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  23743. *
  23744. * @example
  23745. <example>
  23746. <file name="index.html">
  23747. <button ng-mousemove="count = count + 1" ng-init="count=0">
  23748. Increment (when mouse moves)
  23749. </button>
  23750. count: {{count}}
  23751. </file>
  23752. </example>
  23753. */
  23754. /**
  23755. * @ngdoc directive
  23756. * @name ngKeydown
  23757. *
  23758. * @description
  23759. * Specify custom behavior on keydown event.
  23760. *
  23761. * @element ANY
  23762. * @priority 0
  23763. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  23764. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  23765. *
  23766. * @example
  23767. <example>
  23768. <file name="index.html">
  23769. <input ng-keydown="count = count + 1" ng-init="count=0">
  23770. key down count: {{count}}
  23771. </file>
  23772. </example>
  23773. */
  23774. /**
  23775. * @ngdoc directive
  23776. * @name ngKeyup
  23777. *
  23778. * @description
  23779. * Specify custom behavior on keyup event.
  23780. *
  23781. * @element ANY
  23782. * @priority 0
  23783. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  23784. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  23785. *
  23786. * @example
  23787. <example>
  23788. <file name="index.html">
  23789. <p>Typing in the input box below updates the key count</p>
  23790. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  23791. <p>Typing in the input box below updates the keycode</p>
  23792. <input ng-keyup="event=$event">
  23793. <p>event keyCode: {{ event.keyCode }}</p>
  23794. <p>event altKey: {{ event.altKey }}</p>
  23795. </file>
  23796. </example>
  23797. */
  23798. /**
  23799. * @ngdoc directive
  23800. * @name ngKeypress
  23801. *
  23802. * @description
  23803. * Specify custom behavior on keypress event.
  23804. *
  23805. * @element ANY
  23806. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  23807. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  23808. * and can be interrogated for keyCode, altKey, etc.)
  23809. *
  23810. * @example
  23811. <example>
  23812. <file name="index.html">
  23813. <input ng-keypress="count = count + 1" ng-init="count=0">
  23814. key press count: {{count}}
  23815. </file>
  23816. </example>
  23817. */
  23818. /**
  23819. * @ngdoc directive
  23820. * @name ngSubmit
  23821. *
  23822. * @description
  23823. * Enables binding angular expressions to onsubmit events.
  23824. *
  23825. * Additionally it prevents the default action (which for form means sending the request to the
  23826. * server and reloading the current page), but only if the form does not contain `action`,
  23827. * `data-action`, or `x-action` attributes.
  23828. *
  23829. * <div class="alert alert-warning">
  23830. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  23831. * `ngSubmit` handlers together. See the
  23832. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  23833. * for a detailed discussion of when `ngSubmit` may be triggered.
  23834. * </div>
  23835. *
  23836. * @element form
  23837. * @priority 0
  23838. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  23839. * ({@link guide/expression#-event- Event object is available as `$event`})
  23840. *
  23841. * @example
  23842. <example module="submitExample">
  23843. <file name="index.html">
  23844. <script>
  23845. angular.module('submitExample', [])
  23846. .controller('ExampleController', ['$scope', function($scope) {
  23847. $scope.list = [];
  23848. $scope.text = 'hello';
  23849. $scope.submit = function() {
  23850. if ($scope.text) {
  23851. $scope.list.push(this.text);
  23852. $scope.text = '';
  23853. }
  23854. };
  23855. }]);
  23856. </script>
  23857. <form ng-submit="submit()" ng-controller="ExampleController">
  23858. Enter text and hit enter:
  23859. <input type="text" ng-model="text" name="text" />
  23860. <input type="submit" id="submit" value="Submit" />
  23861. <pre>list={{list}}</pre>
  23862. </form>
  23863. </file>
  23864. <file name="protractor.js" type="protractor">
  23865. it('should check ng-submit', function() {
  23866. expect(element(by.binding('list')).getText()).toBe('list=[]');
  23867. element(by.css('#submit')).click();
  23868. expect(element(by.binding('list')).getText()).toContain('hello');
  23869. expect(element(by.model('text')).getAttribute('value')).toBe('');
  23870. });
  23871. it('should ignore empty strings', function() {
  23872. expect(element(by.binding('list')).getText()).toBe('list=[]');
  23873. element(by.css('#submit')).click();
  23874. element(by.css('#submit')).click();
  23875. expect(element(by.binding('list')).getText()).toContain('hello');
  23876. });
  23877. </file>
  23878. </example>
  23879. */
  23880. /**
  23881. * @ngdoc directive
  23882. * @name ngFocus
  23883. *
  23884. * @description
  23885. * Specify custom behavior on focus event.
  23886. *
  23887. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  23888. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  23889. * during an `$apply` to ensure a consistent state.
  23890. *
  23891. * @element window, input, select, textarea, a
  23892. * @priority 0
  23893. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  23894. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  23895. *
  23896. * @example
  23897. * See {@link ng.directive:ngClick ngClick}
  23898. */
  23899. /**
  23900. * @ngdoc directive
  23901. * @name ngBlur
  23902. *
  23903. * @description
  23904. * Specify custom behavior on blur event.
  23905. *
  23906. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  23907. * an element has lost focus.
  23908. *
  23909. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  23910. * (e.g. removing a focussed input),
  23911. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  23912. * during an `$apply` to ensure a consistent state.
  23913. *
  23914. * @element window, input, select, textarea, a
  23915. * @priority 0
  23916. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  23917. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  23918. *
  23919. * @example
  23920. * See {@link ng.directive:ngClick ngClick}
  23921. */
  23922. /**
  23923. * @ngdoc directive
  23924. * @name ngCopy
  23925. *
  23926. * @description
  23927. * Specify custom behavior on copy event.
  23928. *
  23929. * @element window, input, select, textarea, a
  23930. * @priority 0
  23931. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  23932. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  23933. *
  23934. * @example
  23935. <example>
  23936. <file name="index.html">
  23937. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  23938. copied: {{copied}}
  23939. </file>
  23940. </example>
  23941. */
  23942. /**
  23943. * @ngdoc directive
  23944. * @name ngCut
  23945. *
  23946. * @description
  23947. * Specify custom behavior on cut event.
  23948. *
  23949. * @element window, input, select, textarea, a
  23950. * @priority 0
  23951. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  23952. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  23953. *
  23954. * @example
  23955. <example>
  23956. <file name="index.html">
  23957. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  23958. cut: {{cut}}
  23959. </file>
  23960. </example>
  23961. */
  23962. /**
  23963. * @ngdoc directive
  23964. * @name ngPaste
  23965. *
  23966. * @description
  23967. * Specify custom behavior on paste event.
  23968. *
  23969. * @element window, input, select, textarea, a
  23970. * @priority 0
  23971. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  23972. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  23973. *
  23974. * @example
  23975. <example>
  23976. <file name="index.html">
  23977. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  23978. pasted: {{paste}}
  23979. </file>
  23980. </example>
  23981. */
  23982. /**
  23983. * @ngdoc directive
  23984. * @name ngIf
  23985. * @restrict A
  23986. * @multiElement
  23987. *
  23988. * @description
  23989. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  23990. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  23991. * value then the element is removed from the DOM, otherwise a clone of the
  23992. * element is reinserted into the DOM.
  23993. *
  23994. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  23995. * element in the DOM rather than changing its visibility via the `display` css property. A common
  23996. * case when this difference is significant is when using css selectors that rely on an element's
  23997. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  23998. *
  23999. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  24000. * is created when the element is restored. The scope created within `ngIf` inherits from
  24001. * its parent scope using
  24002. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  24003. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  24004. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  24005. * variable within the child scope will override (hide) the value in the parent scope.
  24006. *
  24007. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  24008. * is if an element's class attribute is directly modified after it's compiled, using something like
  24009. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  24010. * the added class will be lost because the original compiled state is used to regenerate the element.
  24011. *
  24012. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  24013. * and `leave` effects.
  24014. *
  24015. * @animations
  24016. * | Animation | Occurs |
  24017. * |----------------------------------|-------------------------------------|
  24018. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  24019. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  24020. *
  24021. * @element ANY
  24022. * @scope
  24023. * @priority 600
  24024. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  24025. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  24026. * element is added to the DOM tree.
  24027. *
  24028. * @example
  24029. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24030. <file name="index.html">
  24031. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  24032. Show when checked:
  24033. <span ng-if="checked" class="animate-if">
  24034. This is removed when the checkbox is unchecked.
  24035. </span>
  24036. </file>
  24037. <file name="animations.css">
  24038. .animate-if {
  24039. background:white;
  24040. border:1px solid black;
  24041. padding:10px;
  24042. }
  24043. .animate-if.ng-enter, .animate-if.ng-leave {
  24044. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24045. }
  24046. .animate-if.ng-enter,
  24047. .animate-if.ng-leave.ng-leave-active {
  24048. opacity:0;
  24049. }
  24050. .animate-if.ng-leave,
  24051. .animate-if.ng-enter.ng-enter-active {
  24052. opacity:1;
  24053. }
  24054. </file>
  24055. </example>
  24056. */
  24057. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  24058. return {
  24059. multiElement: true,
  24060. transclude: 'element',
  24061. priority: 600,
  24062. terminal: true,
  24063. restrict: 'A',
  24064. $$tlb: true,
  24065. link: function($scope, $element, $attr, ctrl, $transclude) {
  24066. var block, childScope, previousElements;
  24067. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  24068. if (value) {
  24069. if (!childScope) {
  24070. $transclude(function(clone, newScope) {
  24071. childScope = newScope;
  24072. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  24073. // Note: We only need the first/last node of the cloned nodes.
  24074. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  24075. // by a directive with templateUrl when its template arrives.
  24076. block = {
  24077. clone: clone
  24078. };
  24079. $animate.enter(clone, $element.parent(), $element);
  24080. });
  24081. }
  24082. } else {
  24083. if (previousElements) {
  24084. previousElements.remove();
  24085. previousElements = null;
  24086. }
  24087. if (childScope) {
  24088. childScope.$destroy();
  24089. childScope = null;
  24090. }
  24091. if (block) {
  24092. previousElements = getBlockNodes(block.clone);
  24093. $animate.leave(previousElements).then(function() {
  24094. previousElements = null;
  24095. });
  24096. block = null;
  24097. }
  24098. }
  24099. });
  24100. }
  24101. };
  24102. }];
  24103. /**
  24104. * @ngdoc directive
  24105. * @name ngInclude
  24106. * @restrict ECA
  24107. *
  24108. * @description
  24109. * Fetches, compiles and includes an external HTML fragment.
  24110. *
  24111. * By default, the template URL is restricted to the same domain and protocol as the
  24112. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  24113. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  24114. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  24115. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  24116. * ng.$sce Strict Contextual Escaping}.
  24117. *
  24118. * In addition, the browser's
  24119. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  24120. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  24121. * policy may further restrict whether the template is successfully loaded.
  24122. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  24123. * access on some browsers.
  24124. *
  24125. * @animations
  24126. * | Animation | Occurs |
  24127. * |----------------------------------|-------------------------------------|
  24128. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  24129. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  24130. *
  24131. * The enter and leave animation occur concurrently.
  24132. *
  24133. * @scope
  24134. * @priority 400
  24135. *
  24136. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  24137. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  24138. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  24139. * <div class="alert alert-warning">
  24140. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  24141. * a function with the name on the window element, which will usually throw a
  24142. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  24143. * different form that {@link guide/directive#normalization matches} `onload`.
  24144. * </div>
  24145. *
  24146. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  24147. * $anchorScroll} to scroll the viewport after the content is loaded.
  24148. *
  24149. * - If the attribute is not set, disable scrolling.
  24150. * - If the attribute is set without value, enable scrolling.
  24151. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  24152. *
  24153. * @example
  24154. <example module="includeExample" deps="angular-animate.js" animations="true">
  24155. <file name="index.html">
  24156. <div ng-controller="ExampleController">
  24157. <select ng-model="template" ng-options="t.name for t in templates">
  24158. <option value="">(blank)</option>
  24159. </select>
  24160. url of the template: <code>{{template.url}}</code>
  24161. <hr/>
  24162. <div class="slide-animate-container">
  24163. <div class="slide-animate" ng-include="template.url"></div>
  24164. </div>
  24165. </div>
  24166. </file>
  24167. <file name="script.js">
  24168. angular.module('includeExample', ['ngAnimate'])
  24169. .controller('ExampleController', ['$scope', function($scope) {
  24170. $scope.templates =
  24171. [ { name: 'template1.html', url: 'template1.html'},
  24172. { name: 'template2.html', url: 'template2.html'} ];
  24173. $scope.template = $scope.templates[0];
  24174. }]);
  24175. </file>
  24176. <file name="template1.html">
  24177. Content of template1.html
  24178. </file>
  24179. <file name="template2.html">
  24180. Content of template2.html
  24181. </file>
  24182. <file name="animations.css">
  24183. .slide-animate-container {
  24184. position:relative;
  24185. background:white;
  24186. border:1px solid black;
  24187. height:40px;
  24188. overflow:hidden;
  24189. }
  24190. .slide-animate {
  24191. padding:10px;
  24192. }
  24193. .slide-animate.ng-enter, .slide-animate.ng-leave {
  24194. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24195. position:absolute;
  24196. top:0;
  24197. left:0;
  24198. right:0;
  24199. bottom:0;
  24200. display:block;
  24201. padding:10px;
  24202. }
  24203. .slide-animate.ng-enter {
  24204. top:-50px;
  24205. }
  24206. .slide-animate.ng-enter.ng-enter-active {
  24207. top:0;
  24208. }
  24209. .slide-animate.ng-leave {
  24210. top:0;
  24211. }
  24212. .slide-animate.ng-leave.ng-leave-active {
  24213. top:50px;
  24214. }
  24215. </file>
  24216. <file name="protractor.js" type="protractor">
  24217. var templateSelect = element(by.model('template'));
  24218. var includeElem = element(by.css('[ng-include]'));
  24219. it('should load template1.html', function() {
  24220. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  24221. });
  24222. it('should load template2.html', function() {
  24223. if (browser.params.browser == 'firefox') {
  24224. // Firefox can't handle using selects
  24225. // See https://github.com/angular/protractor/issues/480
  24226. return;
  24227. }
  24228. templateSelect.click();
  24229. templateSelect.all(by.css('option')).get(2).click();
  24230. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  24231. });
  24232. it('should change to blank', function() {
  24233. if (browser.params.browser == 'firefox') {
  24234. // Firefox can't handle using selects
  24235. return;
  24236. }
  24237. templateSelect.click();
  24238. templateSelect.all(by.css('option')).get(0).click();
  24239. expect(includeElem.isPresent()).toBe(false);
  24240. });
  24241. </file>
  24242. </example>
  24243. */
  24244. /**
  24245. * @ngdoc event
  24246. * @name ngInclude#$includeContentRequested
  24247. * @eventType emit on the scope ngInclude was declared in
  24248. * @description
  24249. * Emitted every time the ngInclude content is requested.
  24250. *
  24251. * @param {Object} angularEvent Synthetic event object.
  24252. * @param {String} src URL of content to load.
  24253. */
  24254. /**
  24255. * @ngdoc event
  24256. * @name ngInclude#$includeContentLoaded
  24257. * @eventType emit on the current ngInclude scope
  24258. * @description
  24259. * Emitted every time the ngInclude content is reloaded.
  24260. *
  24261. * @param {Object} angularEvent Synthetic event object.
  24262. * @param {String} src URL of content to load.
  24263. */
  24264. /**
  24265. * @ngdoc event
  24266. * @name ngInclude#$includeContentError
  24267. * @eventType emit on the scope ngInclude was declared in
  24268. * @description
  24269. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  24270. *
  24271. * @param {Object} angularEvent Synthetic event object.
  24272. * @param {String} src URL of content to load.
  24273. */
  24274. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  24275. function($templateRequest, $anchorScroll, $animate) {
  24276. return {
  24277. restrict: 'ECA',
  24278. priority: 400,
  24279. terminal: true,
  24280. transclude: 'element',
  24281. controller: angular.noop,
  24282. compile: function(element, attr) {
  24283. var srcExp = attr.ngInclude || attr.src,
  24284. onloadExp = attr.onload || '',
  24285. autoScrollExp = attr.autoscroll;
  24286. return function(scope, $element, $attr, ctrl, $transclude) {
  24287. var changeCounter = 0,
  24288. currentScope,
  24289. previousElement,
  24290. currentElement;
  24291. var cleanupLastIncludeContent = function() {
  24292. if (previousElement) {
  24293. previousElement.remove();
  24294. previousElement = null;
  24295. }
  24296. if (currentScope) {
  24297. currentScope.$destroy();
  24298. currentScope = null;
  24299. }
  24300. if (currentElement) {
  24301. $animate.leave(currentElement).then(function() {
  24302. previousElement = null;
  24303. });
  24304. previousElement = currentElement;
  24305. currentElement = null;
  24306. }
  24307. };
  24308. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  24309. var afterAnimation = function() {
  24310. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  24311. $anchorScroll();
  24312. }
  24313. };
  24314. var thisChangeId = ++changeCounter;
  24315. if (src) {
  24316. //set the 2nd param to true to ignore the template request error so that the inner
  24317. //contents and scope can be cleaned up.
  24318. $templateRequest(src, true).then(function(response) {
  24319. if (scope.$$destroyed) return;
  24320. if (thisChangeId !== changeCounter) return;
  24321. var newScope = scope.$new();
  24322. ctrl.template = response;
  24323. // Note: This will also link all children of ng-include that were contained in the original
  24324. // html. If that content contains controllers, ... they could pollute/change the scope.
  24325. // However, using ng-include on an element with additional content does not make sense...
  24326. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  24327. // function is called before linking the content, which would apply child
  24328. // directives to non existing elements.
  24329. var clone = $transclude(newScope, function(clone) {
  24330. cleanupLastIncludeContent();
  24331. $animate.enter(clone, null, $element).then(afterAnimation);
  24332. });
  24333. currentScope = newScope;
  24334. currentElement = clone;
  24335. currentScope.$emit('$includeContentLoaded', src);
  24336. scope.$eval(onloadExp);
  24337. }, function() {
  24338. if (scope.$$destroyed) return;
  24339. if (thisChangeId === changeCounter) {
  24340. cleanupLastIncludeContent();
  24341. scope.$emit('$includeContentError', src);
  24342. }
  24343. });
  24344. scope.$emit('$includeContentRequested', src);
  24345. } else {
  24346. cleanupLastIncludeContent();
  24347. ctrl.template = null;
  24348. }
  24349. });
  24350. };
  24351. }
  24352. };
  24353. }];
  24354. // This directive is called during the $transclude call of the first `ngInclude` directive.
  24355. // It will replace and compile the content of the element with the loaded template.
  24356. // We need this directive so that the element content is already filled when
  24357. // the link function of another directive on the same element as ngInclude
  24358. // is called.
  24359. var ngIncludeFillContentDirective = ['$compile',
  24360. function($compile) {
  24361. return {
  24362. restrict: 'ECA',
  24363. priority: -400,
  24364. require: 'ngInclude',
  24365. link: function(scope, $element, $attr, ctrl) {
  24366. if (toString.call($element[0]).match(/SVG/)) {
  24367. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  24368. // support innerHTML, so detect this here and try to generate the contents
  24369. // specially.
  24370. $element.empty();
  24371. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  24372. function namespaceAdaptedClone(clone) {
  24373. $element.append(clone);
  24374. }, {futureParentElement: $element});
  24375. return;
  24376. }
  24377. $element.html(ctrl.template);
  24378. $compile($element.contents())(scope);
  24379. }
  24380. };
  24381. }];
  24382. /**
  24383. * @ngdoc directive
  24384. * @name ngInit
  24385. * @restrict AC
  24386. *
  24387. * @description
  24388. * The `ngInit` directive allows you to evaluate an expression in the
  24389. * current scope.
  24390. *
  24391. * <div class="alert alert-danger">
  24392. * This directive can be abused to add unnecessary amounts of logic into your templates.
  24393. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  24394. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  24395. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  24396. * rather than `ngInit` to initialize values on a scope.
  24397. * </div>
  24398. *
  24399. * <div class="alert alert-warning">
  24400. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  24401. * sure you have parentheses to ensure correct operator precedence:
  24402. * <pre class="prettyprint">
  24403. * `<div ng-init="test1 = ($index | toString)"></div>`
  24404. * </pre>
  24405. * </div>
  24406. *
  24407. * @priority 450
  24408. *
  24409. * @element ANY
  24410. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  24411. *
  24412. * @example
  24413. <example module="initExample">
  24414. <file name="index.html">
  24415. <script>
  24416. angular.module('initExample', [])
  24417. .controller('ExampleController', ['$scope', function($scope) {
  24418. $scope.list = [['a', 'b'], ['c', 'd']];
  24419. }]);
  24420. </script>
  24421. <div ng-controller="ExampleController">
  24422. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  24423. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  24424. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  24425. </div>
  24426. </div>
  24427. </div>
  24428. </file>
  24429. <file name="protractor.js" type="protractor">
  24430. it('should alias index positions', function() {
  24431. var elements = element.all(by.css('.example-init'));
  24432. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  24433. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  24434. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  24435. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  24436. });
  24437. </file>
  24438. </example>
  24439. */
  24440. var ngInitDirective = ngDirective({
  24441. priority: 450,
  24442. compile: function() {
  24443. return {
  24444. pre: function(scope, element, attrs) {
  24445. scope.$eval(attrs.ngInit);
  24446. }
  24447. };
  24448. }
  24449. });
  24450. /**
  24451. * @ngdoc directive
  24452. * @name ngList
  24453. *
  24454. * @description
  24455. * Text input that converts between a delimited string and an array of strings. The default
  24456. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  24457. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  24458. *
  24459. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  24460. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  24461. * list item is respected. This implies that the user of the directive is responsible for
  24462. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  24463. * tab or newline character.
  24464. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  24465. * when joining the list items back together) and whitespace around each list item is stripped
  24466. * before it is added to the model.
  24467. *
  24468. * ### Example with Validation
  24469. *
  24470. * <example name="ngList-directive" module="listExample">
  24471. * <file name="app.js">
  24472. * angular.module('listExample', [])
  24473. * .controller('ExampleController', ['$scope', function($scope) {
  24474. * $scope.names = ['morpheus', 'neo', 'trinity'];
  24475. * }]);
  24476. * </file>
  24477. * <file name="index.html">
  24478. * <form name="myForm" ng-controller="ExampleController">
  24479. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  24480. * <span role="alert">
  24481. * <span class="error" ng-show="myForm.namesInput.$error.required">
  24482. * Required!</span>
  24483. * </span>
  24484. * <br>
  24485. * <tt>names = {{names}}</tt><br/>
  24486. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  24487. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  24488. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  24489. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  24490. * </form>
  24491. * </file>
  24492. * <file name="protractor.js" type="protractor">
  24493. * var listInput = element(by.model('names'));
  24494. * var names = element(by.exactBinding('names'));
  24495. * var valid = element(by.binding('myForm.namesInput.$valid'));
  24496. * var error = element(by.css('span.error'));
  24497. *
  24498. * it('should initialize to model', function() {
  24499. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  24500. * expect(valid.getText()).toContain('true');
  24501. * expect(error.getCssValue('display')).toBe('none');
  24502. * });
  24503. *
  24504. * it('should be invalid if empty', function() {
  24505. * listInput.clear();
  24506. * listInput.sendKeys('');
  24507. *
  24508. * expect(names.getText()).toContain('');
  24509. * expect(valid.getText()).toContain('false');
  24510. * expect(error.getCssValue('display')).not.toBe('none');
  24511. * });
  24512. * </file>
  24513. * </example>
  24514. *
  24515. * ### Example - splitting on newline
  24516. * <example name="ngList-directive-newlines">
  24517. * <file name="index.html">
  24518. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  24519. * <pre>{{ list | json }}</pre>
  24520. * </file>
  24521. * <file name="protractor.js" type="protractor">
  24522. * it("should split the text by newlines", function() {
  24523. * var listInput = element(by.model('list'));
  24524. * var output = element(by.binding('list | json'));
  24525. * listInput.sendKeys('abc\ndef\nghi');
  24526. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  24527. * });
  24528. * </file>
  24529. * </example>
  24530. *
  24531. * @element input
  24532. * @param {string=} ngList optional delimiter that should be used to split the value.
  24533. */
  24534. var ngListDirective = function() {
  24535. return {
  24536. restrict: 'A',
  24537. priority: 100,
  24538. require: 'ngModel',
  24539. link: function(scope, element, attr, ctrl) {
  24540. // We want to control whitespace trimming so we use this convoluted approach
  24541. // to access the ngList attribute, which doesn't pre-trim the attribute
  24542. var ngList = element.attr(attr.$attr.ngList) || ', ';
  24543. var trimValues = attr.ngTrim !== 'false';
  24544. var separator = trimValues ? trim(ngList) : ngList;
  24545. var parse = function(viewValue) {
  24546. // If the viewValue is invalid (say required but empty) it will be `undefined`
  24547. if (isUndefined(viewValue)) return;
  24548. var list = [];
  24549. if (viewValue) {
  24550. forEach(viewValue.split(separator), function(value) {
  24551. if (value) list.push(trimValues ? trim(value) : value);
  24552. });
  24553. }
  24554. return list;
  24555. };
  24556. ctrl.$parsers.push(parse);
  24557. ctrl.$formatters.push(function(value) {
  24558. if (isArray(value)) {
  24559. return value.join(ngList);
  24560. }
  24561. return undefined;
  24562. });
  24563. // Override the standard $isEmpty because an empty array means the input is empty.
  24564. ctrl.$isEmpty = function(value) {
  24565. return !value || !value.length;
  24566. };
  24567. }
  24568. };
  24569. };
  24570. /* global VALID_CLASS: true,
  24571. INVALID_CLASS: true,
  24572. PRISTINE_CLASS: true,
  24573. DIRTY_CLASS: true,
  24574. UNTOUCHED_CLASS: true,
  24575. TOUCHED_CLASS: true,
  24576. */
  24577. var VALID_CLASS = 'ng-valid',
  24578. INVALID_CLASS = 'ng-invalid',
  24579. PRISTINE_CLASS = 'ng-pristine',
  24580. DIRTY_CLASS = 'ng-dirty',
  24581. UNTOUCHED_CLASS = 'ng-untouched',
  24582. TOUCHED_CLASS = 'ng-touched',
  24583. PENDING_CLASS = 'ng-pending',
  24584. EMPTY_CLASS = 'ng-empty',
  24585. NOT_EMPTY_CLASS = 'ng-not-empty';
  24586. var ngModelMinErr = minErr('ngModel');
  24587. /**
  24588. * @ngdoc type
  24589. * @name ngModel.NgModelController
  24590. *
  24591. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  24592. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  24593. * is set.
  24594. * @property {*} $modelValue The value in the model that the control is bound to.
  24595. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  24596. the control reads value from the DOM. The functions are called in array order, each passing
  24597. its return value through to the next. The last return value is forwarded to the
  24598. {@link ngModel.NgModelController#$validators `$validators`} collection.
  24599. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  24600. `$viewValue`}.
  24601. Returning `undefined` from a parser means a parse error occurred. In that case,
  24602. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  24603. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  24604. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  24605. *
  24606. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  24607. the model value changes. The functions are called in reverse array order, each passing the value through to the
  24608. next. The last return value is used as the actual DOM value.
  24609. Used to format / convert values for display in the control.
  24610. * ```js
  24611. * function formatter(value) {
  24612. * if (value) {
  24613. * return value.toUpperCase();
  24614. * }
  24615. * }
  24616. * ngModel.$formatters.push(formatter);
  24617. * ```
  24618. *
  24619. * @property {Object.<string, function>} $validators A collection of validators that are applied
  24620. * whenever the model value changes. The key value within the object refers to the name of the
  24621. * validator while the function refers to the validation operation. The validation operation is
  24622. * provided with the model value as an argument and must return a true or false value depending
  24623. * on the response of that validation.
  24624. *
  24625. * ```js
  24626. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  24627. * var value = modelValue || viewValue;
  24628. * return /[0-9]+/.test(value) &&
  24629. * /[a-z]+/.test(value) &&
  24630. * /[A-Z]+/.test(value) &&
  24631. * /\W+/.test(value);
  24632. * };
  24633. * ```
  24634. *
  24635. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  24636. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  24637. * is expected to return a promise when it is run during the model validation process. Once the promise
  24638. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  24639. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  24640. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  24641. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  24642. * will only run once all synchronous validators have passed.
  24643. *
  24644. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  24645. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  24646. *
  24647. * ```js
  24648. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  24649. * var value = modelValue || viewValue;
  24650. *
  24651. * // Lookup user by username
  24652. * return $http.get('/api/users/' + value).
  24653. * then(function resolved() {
  24654. * //username exists, this means validation fails
  24655. * return $q.reject('exists');
  24656. * }, function rejected() {
  24657. * //username does not exist, therefore this validation passes
  24658. * return true;
  24659. * });
  24660. * };
  24661. * ```
  24662. *
  24663. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  24664. * view value has changed. It is called with no arguments, and its return value is ignored.
  24665. * This can be used in place of additional $watches against the model value.
  24666. *
  24667. * @property {Object} $error An object hash with all failing validator ids as keys.
  24668. * @property {Object} $pending An object hash with all pending validator ids as keys.
  24669. *
  24670. * @property {boolean} $untouched True if control has not lost focus yet.
  24671. * @property {boolean} $touched True if control has lost focus.
  24672. * @property {boolean} $pristine True if user has not interacted with the control yet.
  24673. * @property {boolean} $dirty True if user has already interacted with the control.
  24674. * @property {boolean} $valid True if there is no error.
  24675. * @property {boolean} $invalid True if at least one error on the control.
  24676. * @property {string} $name The name attribute of the control.
  24677. *
  24678. * @description
  24679. *
  24680. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  24681. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  24682. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  24683. * listening to DOM events.
  24684. * Such DOM related logic should be provided by other directives which make use of
  24685. * `NgModelController` for data-binding to control elements.
  24686. * Angular provides this DOM logic for most {@link input `input`} elements.
  24687. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  24688. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  24689. *
  24690. * @example
  24691. * ### Custom Control Example
  24692. * This example shows how to use `NgModelController` with a custom control to achieve
  24693. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  24694. * collaborate together to achieve the desired result.
  24695. *
  24696. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  24697. * contents be edited in place by the user.
  24698. *
  24699. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  24700. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  24701. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  24702. * that content using the `$sce` service.
  24703. *
  24704. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  24705. <file name="style.css">
  24706. [contenteditable] {
  24707. border: 1px solid black;
  24708. background-color: white;
  24709. min-height: 20px;
  24710. }
  24711. .ng-invalid {
  24712. border: 1px solid red;
  24713. }
  24714. </file>
  24715. <file name="script.js">
  24716. angular.module('customControl', ['ngSanitize']).
  24717. directive('contenteditable', ['$sce', function($sce) {
  24718. return {
  24719. restrict: 'A', // only activate on element attribute
  24720. require: '?ngModel', // get a hold of NgModelController
  24721. link: function(scope, element, attrs, ngModel) {
  24722. if (!ngModel) return; // do nothing if no ng-model
  24723. // Specify how UI should be updated
  24724. ngModel.$render = function() {
  24725. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  24726. };
  24727. // Listen for change events to enable binding
  24728. element.on('blur keyup change', function() {
  24729. scope.$evalAsync(read);
  24730. });
  24731. read(); // initialize
  24732. // Write data to the model
  24733. function read() {
  24734. var html = element.html();
  24735. // When we clear the content editable the browser leaves a <br> behind
  24736. // If strip-br attribute is provided then we strip this out
  24737. if ( attrs.stripBr && html == '<br>' ) {
  24738. html = '';
  24739. }
  24740. ngModel.$setViewValue(html);
  24741. }
  24742. }
  24743. };
  24744. }]);
  24745. </file>
  24746. <file name="index.html">
  24747. <form name="myForm">
  24748. <div contenteditable
  24749. name="myWidget" ng-model="userContent"
  24750. strip-br="true"
  24751. required>Change me!</div>
  24752. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  24753. <hr>
  24754. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  24755. </form>
  24756. </file>
  24757. <file name="protractor.js" type="protractor">
  24758. it('should data-bind and become invalid', function() {
  24759. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  24760. // SafariDriver can't handle contenteditable
  24761. // and Firefox driver can't clear contenteditables very well
  24762. return;
  24763. }
  24764. var contentEditable = element(by.css('[contenteditable]'));
  24765. var content = 'Change me!';
  24766. expect(contentEditable.getText()).toEqual(content);
  24767. contentEditable.clear();
  24768. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  24769. expect(contentEditable.getText()).toEqual('');
  24770. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  24771. });
  24772. </file>
  24773. * </example>
  24774. *
  24775. *
  24776. */
  24777. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  24778. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  24779. this.$viewValue = Number.NaN;
  24780. this.$modelValue = Number.NaN;
  24781. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  24782. this.$validators = {};
  24783. this.$asyncValidators = {};
  24784. this.$parsers = [];
  24785. this.$formatters = [];
  24786. this.$viewChangeListeners = [];
  24787. this.$untouched = true;
  24788. this.$touched = false;
  24789. this.$pristine = true;
  24790. this.$dirty = false;
  24791. this.$valid = true;
  24792. this.$invalid = false;
  24793. this.$error = {}; // keep invalid keys here
  24794. this.$$success = {}; // keep valid keys here
  24795. this.$pending = undefined; // keep pending keys here
  24796. this.$name = $interpolate($attr.name || '', false)($scope);
  24797. this.$$parentForm = nullFormCtrl;
  24798. var parsedNgModel = $parse($attr.ngModel),
  24799. parsedNgModelAssign = parsedNgModel.assign,
  24800. ngModelGet = parsedNgModel,
  24801. ngModelSet = parsedNgModelAssign,
  24802. pendingDebounce = null,
  24803. parserValid,
  24804. ctrl = this;
  24805. this.$$setOptions = function(options) {
  24806. ctrl.$options = options;
  24807. if (options && options.getterSetter) {
  24808. var invokeModelGetter = $parse($attr.ngModel + '()'),
  24809. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  24810. ngModelGet = function($scope) {
  24811. var modelValue = parsedNgModel($scope);
  24812. if (isFunction(modelValue)) {
  24813. modelValue = invokeModelGetter($scope);
  24814. }
  24815. return modelValue;
  24816. };
  24817. ngModelSet = function($scope, newValue) {
  24818. if (isFunction(parsedNgModel($scope))) {
  24819. invokeModelSetter($scope, {$$$p: newValue});
  24820. } else {
  24821. parsedNgModelAssign($scope, newValue);
  24822. }
  24823. };
  24824. } else if (!parsedNgModel.assign) {
  24825. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  24826. $attr.ngModel, startingTag($element));
  24827. }
  24828. };
  24829. /**
  24830. * @ngdoc method
  24831. * @name ngModel.NgModelController#$render
  24832. *
  24833. * @description
  24834. * Called when the view needs to be updated. It is expected that the user of the ng-model
  24835. * directive will implement this method.
  24836. *
  24837. * The `$render()` method is invoked in the following situations:
  24838. *
  24839. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  24840. * committed value then `$render()` is called to update the input control.
  24841. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  24842. * the `$viewValue` are different from last time.
  24843. *
  24844. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  24845. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  24846. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  24847. * invoked if you only change a property on the objects.
  24848. */
  24849. this.$render = noop;
  24850. /**
  24851. * @ngdoc method
  24852. * @name ngModel.NgModelController#$isEmpty
  24853. *
  24854. * @description
  24855. * This is called when we need to determine if the value of an input is empty.
  24856. *
  24857. * For instance, the required directive does this to work out if the input has data or not.
  24858. *
  24859. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  24860. *
  24861. * You can override this for input directives whose concept of being empty is different from the
  24862. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  24863. * implies empty.
  24864. *
  24865. * @param {*} value The value of the input to check for emptiness.
  24866. * @returns {boolean} True if `value` is "empty".
  24867. */
  24868. this.$isEmpty = function(value) {
  24869. return isUndefined(value) || value === '' || value === null || value !== value;
  24870. };
  24871. this.$$updateEmptyClasses = function(value) {
  24872. if (ctrl.$isEmpty(value)) {
  24873. $animate.removeClass($element, NOT_EMPTY_CLASS);
  24874. $animate.addClass($element, EMPTY_CLASS);
  24875. } else {
  24876. $animate.removeClass($element, EMPTY_CLASS);
  24877. $animate.addClass($element, NOT_EMPTY_CLASS);
  24878. }
  24879. };
  24880. var currentValidationRunId = 0;
  24881. /**
  24882. * @ngdoc method
  24883. * @name ngModel.NgModelController#$setValidity
  24884. *
  24885. * @description
  24886. * Change the validity state, and notify the form.
  24887. *
  24888. * This method can be called within $parsers/$formatters or a custom validation implementation.
  24889. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  24890. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  24891. *
  24892. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  24893. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  24894. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  24895. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  24896. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  24897. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  24898. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  24899. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  24900. * Skipped is used by Angular when validators do not run because of parse errors and
  24901. * when `$asyncValidators` do not run because any of the `$validators` failed.
  24902. */
  24903. addSetValidityMethod({
  24904. ctrl: this,
  24905. $element: $element,
  24906. set: function(object, property) {
  24907. object[property] = true;
  24908. },
  24909. unset: function(object, property) {
  24910. delete object[property];
  24911. },
  24912. $animate: $animate
  24913. });
  24914. /**
  24915. * @ngdoc method
  24916. * @name ngModel.NgModelController#$setPristine
  24917. *
  24918. * @description
  24919. * Sets the control to its pristine state.
  24920. *
  24921. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  24922. * state (`ng-pristine` class). A model is considered to be pristine when the control
  24923. * has not been changed from when first compiled.
  24924. */
  24925. this.$setPristine = function() {
  24926. ctrl.$dirty = false;
  24927. ctrl.$pristine = true;
  24928. $animate.removeClass($element, DIRTY_CLASS);
  24929. $animate.addClass($element, PRISTINE_CLASS);
  24930. };
  24931. /**
  24932. * @ngdoc method
  24933. * @name ngModel.NgModelController#$setDirty
  24934. *
  24935. * @description
  24936. * Sets the control to its dirty state.
  24937. *
  24938. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  24939. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  24940. * from when first compiled.
  24941. */
  24942. this.$setDirty = function() {
  24943. ctrl.$dirty = true;
  24944. ctrl.$pristine = false;
  24945. $animate.removeClass($element, PRISTINE_CLASS);
  24946. $animate.addClass($element, DIRTY_CLASS);
  24947. ctrl.$$parentForm.$setDirty();
  24948. };
  24949. /**
  24950. * @ngdoc method
  24951. * @name ngModel.NgModelController#$setUntouched
  24952. *
  24953. * @description
  24954. * Sets the control to its untouched state.
  24955. *
  24956. * This method can be called to remove the `ng-touched` class and set the control to its
  24957. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  24958. * by default, however this function can be used to restore that state if the model has
  24959. * already been touched by the user.
  24960. */
  24961. this.$setUntouched = function() {
  24962. ctrl.$touched = false;
  24963. ctrl.$untouched = true;
  24964. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  24965. };
  24966. /**
  24967. * @ngdoc method
  24968. * @name ngModel.NgModelController#$setTouched
  24969. *
  24970. * @description
  24971. * Sets the control to its touched state.
  24972. *
  24973. * This method can be called to remove the `ng-untouched` class and set the control to its
  24974. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  24975. * first focused the control element and then shifted focus away from the control (blur event).
  24976. */
  24977. this.$setTouched = function() {
  24978. ctrl.$touched = true;
  24979. ctrl.$untouched = false;
  24980. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  24981. };
  24982. /**
  24983. * @ngdoc method
  24984. * @name ngModel.NgModelController#$rollbackViewValue
  24985. *
  24986. * @description
  24987. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  24988. * which may be caused by a pending debounced event or because the input is waiting for a some
  24989. * future event.
  24990. *
  24991. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  24992. * depend on special events such as blur, you can have a situation where there is a period when
  24993. * the `$viewValue` is out of sync with the ngModel's `$modelValue`.
  24994. *
  24995. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  24996. * and reset the input to the last committed view value.
  24997. *
  24998. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  24999. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  25000. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  25001. *
  25002. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  25003. * input which may have such events pending. This is important in order to make sure that the
  25004. * input field will be updated with the new model value and any pending operations are cancelled.
  25005. *
  25006. * <example name="ng-model-cancel-update" module="cancel-update-example">
  25007. * <file name="app.js">
  25008. * angular.module('cancel-update-example', [])
  25009. *
  25010. * .controller('CancelUpdateController', ['$scope', function($scope) {
  25011. * $scope.model = {};
  25012. *
  25013. * $scope.setEmpty = function(e, value, rollback) {
  25014. * if (e.keyCode == 27) {
  25015. * e.preventDefault();
  25016. * if (rollback) {
  25017. * $scope.myForm[value].$rollbackViewValue();
  25018. * }
  25019. * $scope.model[value] = '';
  25020. * }
  25021. * };
  25022. * }]);
  25023. * </file>
  25024. * <file name="index.html">
  25025. * <div ng-controller="CancelUpdateController">
  25026. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  25027. * empty them. Follow these steps and observe the difference:</p>
  25028. * <ol>
  25029. * <li>Type something in the input. You will see that the model is not yet updated</li>
  25030. * <li>Press the Escape key.
  25031. * <ol>
  25032. * <li> In the first example, nothing happens, because the model is already '', and no
  25033. * update is detected. If you blur the input, the model will be set to the current view.
  25034. * </li>
  25035. * <li> In the second example, the pending update is cancelled, and the input is set back
  25036. * to the last committed view value (''). Blurring the input does nothing.
  25037. * </li>
  25038. * </ol>
  25039. * </li>
  25040. * </ol>
  25041. *
  25042. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  25043. * <div>
  25044. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  25045. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  25046. * ng-keydown="setEmpty($event, 'value1')">
  25047. * value1: "{{ model.value1 }}"
  25048. * </div>
  25049. *
  25050. * <div>
  25051. * <p id="inputDescription2">With $rollbackViewValue():</p>
  25052. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  25053. * ng-keydown="setEmpty($event, 'value2', true)">
  25054. * value2: "{{ model.value2 }}"
  25055. * </div>
  25056. * </form>
  25057. * </div>
  25058. * </file>
  25059. <file name="style.css">
  25060. div {
  25061. display: table-cell;
  25062. }
  25063. div:nth-child(1) {
  25064. padding-right: 30px;
  25065. }
  25066. </file>
  25067. * </example>
  25068. */
  25069. this.$rollbackViewValue = function() {
  25070. $timeout.cancel(pendingDebounce);
  25071. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  25072. ctrl.$render();
  25073. };
  25074. /**
  25075. * @ngdoc method
  25076. * @name ngModel.NgModelController#$validate
  25077. *
  25078. * @description
  25079. * Runs each of the registered validators (first synchronous validators and then
  25080. * asynchronous validators).
  25081. * If the validity changes to invalid, the model will be set to `undefined`,
  25082. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  25083. * If the validity changes to valid, it will set the model to the last available valid
  25084. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  25085. */
  25086. this.$validate = function() {
  25087. // ignore $validate before model is initialized
  25088. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  25089. return;
  25090. }
  25091. var viewValue = ctrl.$$lastCommittedViewValue;
  25092. // Note: we use the $$rawModelValue as $modelValue might have been
  25093. // set to undefined during a view -> model update that found validation
  25094. // errors. We can't parse the view here, since that could change
  25095. // the model although neither viewValue nor the model on the scope changed
  25096. var modelValue = ctrl.$$rawModelValue;
  25097. var prevValid = ctrl.$valid;
  25098. var prevModelValue = ctrl.$modelValue;
  25099. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  25100. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  25101. // If there was no change in validity, don't update the model
  25102. // This prevents changing an invalid modelValue to undefined
  25103. if (!allowInvalid && prevValid !== allValid) {
  25104. // Note: Don't check ctrl.$valid here, as we could have
  25105. // external validators (e.g. calculated on the server),
  25106. // that just call $setValidity and need the model value
  25107. // to calculate their validity.
  25108. ctrl.$modelValue = allValid ? modelValue : undefined;
  25109. if (ctrl.$modelValue !== prevModelValue) {
  25110. ctrl.$$writeModelToScope();
  25111. }
  25112. }
  25113. });
  25114. };
  25115. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  25116. currentValidationRunId++;
  25117. var localValidationRunId = currentValidationRunId;
  25118. // check parser error
  25119. if (!processParseErrors()) {
  25120. validationDone(false);
  25121. return;
  25122. }
  25123. if (!processSyncValidators()) {
  25124. validationDone(false);
  25125. return;
  25126. }
  25127. processAsyncValidators();
  25128. function processParseErrors() {
  25129. var errorKey = ctrl.$$parserName || 'parse';
  25130. if (isUndefined(parserValid)) {
  25131. setValidity(errorKey, null);
  25132. } else {
  25133. if (!parserValid) {
  25134. forEach(ctrl.$validators, function(v, name) {
  25135. setValidity(name, null);
  25136. });
  25137. forEach(ctrl.$asyncValidators, function(v, name) {
  25138. setValidity(name, null);
  25139. });
  25140. }
  25141. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  25142. setValidity(errorKey, parserValid);
  25143. return parserValid;
  25144. }
  25145. return true;
  25146. }
  25147. function processSyncValidators() {
  25148. var syncValidatorsValid = true;
  25149. forEach(ctrl.$validators, function(validator, name) {
  25150. var result = validator(modelValue, viewValue);
  25151. syncValidatorsValid = syncValidatorsValid && result;
  25152. setValidity(name, result);
  25153. });
  25154. if (!syncValidatorsValid) {
  25155. forEach(ctrl.$asyncValidators, function(v, name) {
  25156. setValidity(name, null);
  25157. });
  25158. return false;
  25159. }
  25160. return true;
  25161. }
  25162. function processAsyncValidators() {
  25163. var validatorPromises = [];
  25164. var allValid = true;
  25165. forEach(ctrl.$asyncValidators, function(validator, name) {
  25166. var promise = validator(modelValue, viewValue);
  25167. if (!isPromiseLike(promise)) {
  25168. throw ngModelMinErr('nopromise',
  25169. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  25170. }
  25171. setValidity(name, undefined);
  25172. validatorPromises.push(promise.then(function() {
  25173. setValidity(name, true);
  25174. }, function() {
  25175. allValid = false;
  25176. setValidity(name, false);
  25177. }));
  25178. });
  25179. if (!validatorPromises.length) {
  25180. validationDone(true);
  25181. } else {
  25182. $q.all(validatorPromises).then(function() {
  25183. validationDone(allValid);
  25184. }, noop);
  25185. }
  25186. }
  25187. function setValidity(name, isValid) {
  25188. if (localValidationRunId === currentValidationRunId) {
  25189. ctrl.$setValidity(name, isValid);
  25190. }
  25191. }
  25192. function validationDone(allValid) {
  25193. if (localValidationRunId === currentValidationRunId) {
  25194. doneCallback(allValid);
  25195. }
  25196. }
  25197. };
  25198. /**
  25199. * @ngdoc method
  25200. * @name ngModel.NgModelController#$commitViewValue
  25201. *
  25202. * @description
  25203. * Commit a pending update to the `$modelValue`.
  25204. *
  25205. * Updates may be pending by a debounced event or because the input is waiting for a some future
  25206. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  25207. * usually handles calling this in response to input events.
  25208. */
  25209. this.$commitViewValue = function() {
  25210. var viewValue = ctrl.$viewValue;
  25211. $timeout.cancel(pendingDebounce);
  25212. // If the view value has not changed then we should just exit, except in the case where there is
  25213. // a native validator on the element. In this case the validation state may have changed even though
  25214. // the viewValue has stayed empty.
  25215. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  25216. return;
  25217. }
  25218. ctrl.$$updateEmptyClasses(viewValue);
  25219. ctrl.$$lastCommittedViewValue = viewValue;
  25220. // change to dirty
  25221. if (ctrl.$pristine) {
  25222. this.$setDirty();
  25223. }
  25224. this.$$parseAndValidate();
  25225. };
  25226. this.$$parseAndValidate = function() {
  25227. var viewValue = ctrl.$$lastCommittedViewValue;
  25228. var modelValue = viewValue;
  25229. parserValid = isUndefined(modelValue) ? undefined : true;
  25230. if (parserValid) {
  25231. for (var i = 0; i < ctrl.$parsers.length; i++) {
  25232. modelValue = ctrl.$parsers[i](modelValue);
  25233. if (isUndefined(modelValue)) {
  25234. parserValid = false;
  25235. break;
  25236. }
  25237. }
  25238. }
  25239. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  25240. // ctrl.$modelValue has not been touched yet...
  25241. ctrl.$modelValue = ngModelGet($scope);
  25242. }
  25243. var prevModelValue = ctrl.$modelValue;
  25244. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  25245. ctrl.$$rawModelValue = modelValue;
  25246. if (allowInvalid) {
  25247. ctrl.$modelValue = modelValue;
  25248. writeToModelIfNeeded();
  25249. }
  25250. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  25251. // This can happen if e.g. $setViewValue is called from inside a parser
  25252. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  25253. if (!allowInvalid) {
  25254. // Note: Don't check ctrl.$valid here, as we could have
  25255. // external validators (e.g. calculated on the server),
  25256. // that just call $setValidity and need the model value
  25257. // to calculate their validity.
  25258. ctrl.$modelValue = allValid ? modelValue : undefined;
  25259. writeToModelIfNeeded();
  25260. }
  25261. });
  25262. function writeToModelIfNeeded() {
  25263. if (ctrl.$modelValue !== prevModelValue) {
  25264. ctrl.$$writeModelToScope();
  25265. }
  25266. }
  25267. };
  25268. this.$$writeModelToScope = function() {
  25269. ngModelSet($scope, ctrl.$modelValue);
  25270. forEach(ctrl.$viewChangeListeners, function(listener) {
  25271. try {
  25272. listener();
  25273. } catch (e) {
  25274. $exceptionHandler(e);
  25275. }
  25276. });
  25277. };
  25278. /**
  25279. * @ngdoc method
  25280. * @name ngModel.NgModelController#$setViewValue
  25281. *
  25282. * @description
  25283. * Update the view value.
  25284. *
  25285. * This method should be called when a control wants to change the view value; typically,
  25286. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  25287. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  25288. * calls it when an option is selected.
  25289. *
  25290. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  25291. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  25292. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  25293. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  25294. * in the `$viewChangeListeners` list, are called.
  25295. *
  25296. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  25297. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  25298. * `updateOn` events is triggered on the DOM element.
  25299. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  25300. * directive is used with a custom debounce for this particular event.
  25301. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  25302. * is specified, once the timer runs out.
  25303. *
  25304. * When used with standard inputs, the view value will always be a string (which is in some cases
  25305. * parsed into another type, such as a `Date` object for `input[date]`.)
  25306. * However, custom controls might also pass objects to this method. In this case, we should make
  25307. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  25308. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  25309. * the property of the object then ngModel will not realize that the object has changed and
  25310. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  25311. * not change properties of the copy once it has been passed to `$setViewValue`.
  25312. * Otherwise you may cause the model value on the scope to change incorrectly.
  25313. *
  25314. * <div class="alert alert-info">
  25315. * In any case, the value passed to the method should always reflect the current value
  25316. * of the control. For example, if you are calling `$setViewValue` for an input element,
  25317. * you should pass the input DOM value. Otherwise, the control and the scope model become
  25318. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  25319. * the control's DOM value in any way. If we want to change the control's DOM value
  25320. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  25321. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  25322. * to update the DOM, and finally call `$validate` on it.
  25323. * </div>
  25324. *
  25325. * @param {*} value value from the view.
  25326. * @param {string} trigger Event that triggered the update.
  25327. */
  25328. this.$setViewValue = function(value, trigger) {
  25329. ctrl.$viewValue = value;
  25330. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  25331. ctrl.$$debounceViewValueCommit(trigger);
  25332. }
  25333. };
  25334. this.$$debounceViewValueCommit = function(trigger) {
  25335. var debounceDelay = 0,
  25336. options = ctrl.$options,
  25337. debounce;
  25338. if (options && isDefined(options.debounce)) {
  25339. debounce = options.debounce;
  25340. if (isNumber(debounce)) {
  25341. debounceDelay = debounce;
  25342. } else if (isNumber(debounce[trigger])) {
  25343. debounceDelay = debounce[trigger];
  25344. } else if (isNumber(debounce['default'])) {
  25345. debounceDelay = debounce['default'];
  25346. }
  25347. }
  25348. $timeout.cancel(pendingDebounce);
  25349. if (debounceDelay) {
  25350. pendingDebounce = $timeout(function() {
  25351. ctrl.$commitViewValue();
  25352. }, debounceDelay);
  25353. } else if ($rootScope.$$phase) {
  25354. ctrl.$commitViewValue();
  25355. } else {
  25356. $scope.$apply(function() {
  25357. ctrl.$commitViewValue();
  25358. });
  25359. }
  25360. };
  25361. // model -> value
  25362. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  25363. // 1. scope value is 'a'
  25364. // 2. user enters 'b'
  25365. // 3. ng-change kicks in and reverts scope value to 'a'
  25366. // -> scope value did not change since the last digest as
  25367. // ng-change executes in apply phase
  25368. // 4. view should be changed back to 'a'
  25369. $scope.$watch(function ngModelWatch() {
  25370. var modelValue = ngModelGet($scope);
  25371. // if scope model value and ngModel value are out of sync
  25372. // TODO(perf): why not move this to the action fn?
  25373. if (modelValue !== ctrl.$modelValue &&
  25374. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  25375. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  25376. ) {
  25377. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  25378. parserValid = undefined;
  25379. var formatters = ctrl.$formatters,
  25380. idx = formatters.length;
  25381. var viewValue = modelValue;
  25382. while (idx--) {
  25383. viewValue = formatters[idx](viewValue);
  25384. }
  25385. if (ctrl.$viewValue !== viewValue) {
  25386. ctrl.$$updateEmptyClasses(viewValue);
  25387. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  25388. ctrl.$render();
  25389. ctrl.$$runValidators(modelValue, viewValue, noop);
  25390. }
  25391. }
  25392. return modelValue;
  25393. });
  25394. }];
  25395. /**
  25396. * @ngdoc directive
  25397. * @name ngModel
  25398. *
  25399. * @element input
  25400. * @priority 1
  25401. *
  25402. * @description
  25403. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  25404. * property on the scope using {@link ngModel.NgModelController NgModelController},
  25405. * which is created and exposed by this directive.
  25406. *
  25407. * `ngModel` is responsible for:
  25408. *
  25409. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  25410. * require.
  25411. * - Providing validation behavior (i.e. required, number, email, url).
  25412. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  25413. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  25414. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  25415. * - Registering the control with its parent {@link ng.directive:form form}.
  25416. *
  25417. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  25418. * current scope. If the property doesn't already exist on this scope, it will be created
  25419. * implicitly and added to the scope.
  25420. *
  25421. * For best practices on using `ngModel`, see:
  25422. *
  25423. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  25424. *
  25425. * For basic examples, how to use `ngModel`, see:
  25426. *
  25427. * - {@link ng.directive:input input}
  25428. * - {@link input[text] text}
  25429. * - {@link input[checkbox] checkbox}
  25430. * - {@link input[radio] radio}
  25431. * - {@link input[number] number}
  25432. * - {@link input[email] email}
  25433. * - {@link input[url] url}
  25434. * - {@link input[date] date}
  25435. * - {@link input[datetime-local] datetime-local}
  25436. * - {@link input[time] time}
  25437. * - {@link input[month] month}
  25438. * - {@link input[week] week}
  25439. * - {@link ng.directive:select select}
  25440. * - {@link ng.directive:textarea textarea}
  25441. *
  25442. * # Complex Models (objects or collections)
  25443. *
  25444. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  25445. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  25446. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  25447. *
  25448. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  25449. *
  25450. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  25451. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  25452. * if the select is given the `multiple` attribute.
  25453. *
  25454. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  25455. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  25456. * not trigger a re-rendering of the model.
  25457. *
  25458. * # CSS classes
  25459. * The following CSS classes are added and removed on the associated input/select/textarea element
  25460. * depending on the validity of the model.
  25461. *
  25462. * - `ng-valid`: the model is valid
  25463. * - `ng-invalid`: the model is invalid
  25464. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  25465. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  25466. * - `ng-pristine`: the control hasn't been interacted with yet
  25467. * - `ng-dirty`: the control has been interacted with
  25468. * - `ng-touched`: the control has been blurred
  25469. * - `ng-untouched`: the control hasn't been blurred
  25470. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  25471. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  25472. * by the {@link ngModel.NgModelController#$isEmpty} method
  25473. * - `ng-not-empty`: the view contains a non-empty value
  25474. *
  25475. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  25476. *
  25477. * ## Animation Hooks
  25478. *
  25479. * Animations within models are triggered when any of the associated CSS classes are added and removed
  25480. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  25481. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  25482. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  25483. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  25484. *
  25485. * The following example shows a simple way to utilize CSS transitions to style an input element
  25486. * that has been rendered as invalid after it has been validated:
  25487. *
  25488. * <pre>
  25489. * //be sure to include ngAnimate as a module to hook into more
  25490. * //advanced animations
  25491. * .my-input {
  25492. * transition:0.5s linear all;
  25493. * background: white;
  25494. * }
  25495. * .my-input.ng-invalid {
  25496. * background: red;
  25497. * color:white;
  25498. * }
  25499. * </pre>
  25500. *
  25501. * @example
  25502. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  25503. <file name="index.html">
  25504. <script>
  25505. angular.module('inputExample', [])
  25506. .controller('ExampleController', ['$scope', function($scope) {
  25507. $scope.val = '1';
  25508. }]);
  25509. </script>
  25510. <style>
  25511. .my-input {
  25512. transition:all linear 0.5s;
  25513. background: transparent;
  25514. }
  25515. .my-input.ng-invalid {
  25516. color:white;
  25517. background: red;
  25518. }
  25519. </style>
  25520. <p id="inputDescription">
  25521. Update input to see transitions when valid/invalid.
  25522. Integer is a valid value.
  25523. </p>
  25524. <form name="testForm" ng-controller="ExampleController">
  25525. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  25526. aria-describedby="inputDescription" />
  25527. </form>
  25528. </file>
  25529. * </example>
  25530. *
  25531. * ## Binding to a getter/setter
  25532. *
  25533. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  25534. * function that returns a representation of the model when called with zero arguments, and sets
  25535. * the internal state of a model when called with an argument. It's sometimes useful to use this
  25536. * for models that have an internal representation that's different from what the model exposes
  25537. * to the view.
  25538. *
  25539. * <div class="alert alert-success">
  25540. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  25541. * frequently than other parts of your code.
  25542. * </div>
  25543. *
  25544. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  25545. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  25546. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  25547. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  25548. *
  25549. * The following example shows how to use `ngModel` with a getter/setter:
  25550. *
  25551. * @example
  25552. * <example name="ngModel-getter-setter" module="getterSetterExample">
  25553. <file name="index.html">
  25554. <div ng-controller="ExampleController">
  25555. <form name="userForm">
  25556. <label>Name:
  25557. <input type="text" name="userName"
  25558. ng-model="user.name"
  25559. ng-model-options="{ getterSetter: true }" />
  25560. </label>
  25561. </form>
  25562. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  25563. </div>
  25564. </file>
  25565. <file name="app.js">
  25566. angular.module('getterSetterExample', [])
  25567. .controller('ExampleController', ['$scope', function($scope) {
  25568. var _name = 'Brian';
  25569. $scope.user = {
  25570. name: function(newName) {
  25571. // Note that newName can be undefined for two reasons:
  25572. // 1. Because it is called as a getter and thus called with no arguments
  25573. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  25574. // input is invalid
  25575. return arguments.length ? (_name = newName) : _name;
  25576. }
  25577. };
  25578. }]);
  25579. </file>
  25580. * </example>
  25581. */
  25582. var ngModelDirective = ['$rootScope', function($rootScope) {
  25583. return {
  25584. restrict: 'A',
  25585. require: ['ngModel', '^?form', '^?ngModelOptions'],
  25586. controller: NgModelController,
  25587. // Prelink needs to run before any input directive
  25588. // so that we can set the NgModelOptions in NgModelController
  25589. // before anyone else uses it.
  25590. priority: 1,
  25591. compile: function ngModelCompile(element) {
  25592. // Setup initial state of the control
  25593. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  25594. return {
  25595. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  25596. var modelCtrl = ctrls[0],
  25597. formCtrl = ctrls[1] || modelCtrl.$$parentForm;
  25598. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  25599. // notify others, especially parent forms
  25600. formCtrl.$addControl(modelCtrl);
  25601. attr.$observe('name', function(newValue) {
  25602. if (modelCtrl.$name !== newValue) {
  25603. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  25604. }
  25605. });
  25606. scope.$on('$destroy', function() {
  25607. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  25608. });
  25609. },
  25610. post: function ngModelPostLink(scope, element, attr, ctrls) {
  25611. var modelCtrl = ctrls[0];
  25612. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  25613. element.on(modelCtrl.$options.updateOn, function(ev) {
  25614. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  25615. });
  25616. }
  25617. element.on('blur', function() {
  25618. if (modelCtrl.$touched) return;
  25619. if ($rootScope.$$phase) {
  25620. scope.$evalAsync(modelCtrl.$setTouched);
  25621. } else {
  25622. scope.$apply(modelCtrl.$setTouched);
  25623. }
  25624. });
  25625. }
  25626. };
  25627. }
  25628. };
  25629. }];
  25630. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  25631. /**
  25632. * @ngdoc directive
  25633. * @name ngModelOptions
  25634. *
  25635. * @description
  25636. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  25637. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  25638. * takes place when a timer expires; this timer will be reset after another change takes place.
  25639. *
  25640. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  25641. * be different from the value in the actual model. This means that if you update the model you
  25642. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  25643. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  25644. *
  25645. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  25646. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  25647. * important because `form` controllers are published to the related scope under the name in their
  25648. * `name` attribute.
  25649. *
  25650. * Any pending changes will take place immediately when an enclosing form is submitted via the
  25651. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  25652. * to have access to the updated model.
  25653. *
  25654. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  25655. *
  25656. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  25657. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  25658. * events using an space delimited list. There is a special event called `default` that
  25659. * matches the default events belonging of the control.
  25660. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  25661. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  25662. * custom value for each event. For example:
  25663. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  25664. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  25665. * not validate correctly instead of the default behavior of setting the model to undefined.
  25666. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  25667. `ngModel` as getters/setters.
  25668. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  25669. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  25670. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  25671. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  25672. * If not specified, the timezone of the browser will be used.
  25673. *
  25674. * @example
  25675. The following example shows how to override immediate updates. Changes on the inputs within the
  25676. form will update the model only when the control loses focus (blur event). If `escape` key is
  25677. pressed while the input field is focused, the value is reset to the value in the current model.
  25678. <example name="ngModelOptions-directive-blur" module="optionsExample">
  25679. <file name="index.html">
  25680. <div ng-controller="ExampleController">
  25681. <form name="userForm">
  25682. <label>Name:
  25683. <input type="text" name="userName"
  25684. ng-model="user.name"
  25685. ng-model-options="{ updateOn: 'blur' }"
  25686. ng-keyup="cancel($event)" />
  25687. </label><br />
  25688. <label>Other data:
  25689. <input type="text" ng-model="user.data" />
  25690. </label><br />
  25691. </form>
  25692. <pre>user.name = <span ng-bind="user.name"></span></pre>
  25693. <pre>user.data = <span ng-bind="user.data"></span></pre>
  25694. </div>
  25695. </file>
  25696. <file name="app.js">
  25697. angular.module('optionsExample', [])
  25698. .controller('ExampleController', ['$scope', function($scope) {
  25699. $scope.user = { name: 'John', data: '' };
  25700. $scope.cancel = function(e) {
  25701. if (e.keyCode == 27) {
  25702. $scope.userForm.userName.$rollbackViewValue();
  25703. }
  25704. };
  25705. }]);
  25706. </file>
  25707. <file name="protractor.js" type="protractor">
  25708. var model = element(by.binding('user.name'));
  25709. var input = element(by.model('user.name'));
  25710. var other = element(by.model('user.data'));
  25711. it('should allow custom events', function() {
  25712. input.sendKeys(' Doe');
  25713. input.click();
  25714. expect(model.getText()).toEqual('John');
  25715. other.click();
  25716. expect(model.getText()).toEqual('John Doe');
  25717. });
  25718. it('should $rollbackViewValue when model changes', function() {
  25719. input.sendKeys(' Doe');
  25720. expect(input.getAttribute('value')).toEqual('John Doe');
  25721. input.sendKeys(protractor.Key.ESCAPE);
  25722. expect(input.getAttribute('value')).toEqual('John');
  25723. other.click();
  25724. expect(model.getText()).toEqual('John');
  25725. });
  25726. </file>
  25727. </example>
  25728. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  25729. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  25730. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  25731. <file name="index.html">
  25732. <div ng-controller="ExampleController">
  25733. <form name="userForm">
  25734. <label>Name:
  25735. <input type="text" name="userName"
  25736. ng-model="user.name"
  25737. ng-model-options="{ debounce: 1000 }" />
  25738. </label>
  25739. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  25740. <br />
  25741. </form>
  25742. <pre>user.name = <span ng-bind="user.name"></span></pre>
  25743. </div>
  25744. </file>
  25745. <file name="app.js">
  25746. angular.module('optionsExample', [])
  25747. .controller('ExampleController', ['$scope', function($scope) {
  25748. $scope.user = { name: 'Igor' };
  25749. }]);
  25750. </file>
  25751. </example>
  25752. This one shows how to bind to getter/setters:
  25753. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  25754. <file name="index.html">
  25755. <div ng-controller="ExampleController">
  25756. <form name="userForm">
  25757. <label>Name:
  25758. <input type="text" name="userName"
  25759. ng-model="user.name"
  25760. ng-model-options="{ getterSetter: true }" />
  25761. </label>
  25762. </form>
  25763. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  25764. </div>
  25765. </file>
  25766. <file name="app.js">
  25767. angular.module('getterSetterExample', [])
  25768. .controller('ExampleController', ['$scope', function($scope) {
  25769. var _name = 'Brian';
  25770. $scope.user = {
  25771. name: function(newName) {
  25772. // Note that newName can be undefined for two reasons:
  25773. // 1. Because it is called as a getter and thus called with no arguments
  25774. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  25775. // input is invalid
  25776. return arguments.length ? (_name = newName) : _name;
  25777. }
  25778. };
  25779. }]);
  25780. </file>
  25781. </example>
  25782. */
  25783. var ngModelOptionsDirective = function() {
  25784. return {
  25785. restrict: 'A',
  25786. controller: ['$scope', '$attrs', function($scope, $attrs) {
  25787. var that = this;
  25788. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  25789. // Allow adding/overriding bound events
  25790. if (isDefined(this.$options.updateOn)) {
  25791. this.$options.updateOnDefault = false;
  25792. // extract "default" pseudo-event from list of events that can trigger a model update
  25793. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  25794. that.$options.updateOnDefault = true;
  25795. return ' ';
  25796. }));
  25797. } else {
  25798. this.$options.updateOnDefault = true;
  25799. }
  25800. }]
  25801. };
  25802. };
  25803. // helper methods
  25804. function addSetValidityMethod(context) {
  25805. var ctrl = context.ctrl,
  25806. $element = context.$element,
  25807. classCache = {},
  25808. set = context.set,
  25809. unset = context.unset,
  25810. $animate = context.$animate;
  25811. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  25812. ctrl.$setValidity = setValidity;
  25813. function setValidity(validationErrorKey, state, controller) {
  25814. if (isUndefined(state)) {
  25815. createAndSet('$pending', validationErrorKey, controller);
  25816. } else {
  25817. unsetAndCleanup('$pending', validationErrorKey, controller);
  25818. }
  25819. if (!isBoolean(state)) {
  25820. unset(ctrl.$error, validationErrorKey, controller);
  25821. unset(ctrl.$$success, validationErrorKey, controller);
  25822. } else {
  25823. if (state) {
  25824. unset(ctrl.$error, validationErrorKey, controller);
  25825. set(ctrl.$$success, validationErrorKey, controller);
  25826. } else {
  25827. set(ctrl.$error, validationErrorKey, controller);
  25828. unset(ctrl.$$success, validationErrorKey, controller);
  25829. }
  25830. }
  25831. if (ctrl.$pending) {
  25832. cachedToggleClass(PENDING_CLASS, true);
  25833. ctrl.$valid = ctrl.$invalid = undefined;
  25834. toggleValidationCss('', null);
  25835. } else {
  25836. cachedToggleClass(PENDING_CLASS, false);
  25837. ctrl.$valid = isObjectEmpty(ctrl.$error);
  25838. ctrl.$invalid = !ctrl.$valid;
  25839. toggleValidationCss('', ctrl.$valid);
  25840. }
  25841. // re-read the state as the set/unset methods could have
  25842. // combined state in ctrl.$error[validationError] (used for forms),
  25843. // where setting/unsetting only increments/decrements the value,
  25844. // and does not replace it.
  25845. var combinedState;
  25846. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  25847. combinedState = undefined;
  25848. } else if (ctrl.$error[validationErrorKey]) {
  25849. combinedState = false;
  25850. } else if (ctrl.$$success[validationErrorKey]) {
  25851. combinedState = true;
  25852. } else {
  25853. combinedState = null;
  25854. }
  25855. toggleValidationCss(validationErrorKey, combinedState);
  25856. ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  25857. }
  25858. function createAndSet(name, value, controller) {
  25859. if (!ctrl[name]) {
  25860. ctrl[name] = {};
  25861. }
  25862. set(ctrl[name], value, controller);
  25863. }
  25864. function unsetAndCleanup(name, value, controller) {
  25865. if (ctrl[name]) {
  25866. unset(ctrl[name], value, controller);
  25867. }
  25868. if (isObjectEmpty(ctrl[name])) {
  25869. ctrl[name] = undefined;
  25870. }
  25871. }
  25872. function cachedToggleClass(className, switchValue) {
  25873. if (switchValue && !classCache[className]) {
  25874. $animate.addClass($element, className);
  25875. classCache[className] = true;
  25876. } else if (!switchValue && classCache[className]) {
  25877. $animate.removeClass($element, className);
  25878. classCache[className] = false;
  25879. }
  25880. }
  25881. function toggleValidationCss(validationErrorKey, isValid) {
  25882. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  25883. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  25884. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  25885. }
  25886. }
  25887. function isObjectEmpty(obj) {
  25888. if (obj) {
  25889. for (var prop in obj) {
  25890. if (obj.hasOwnProperty(prop)) {
  25891. return false;
  25892. }
  25893. }
  25894. }
  25895. return true;
  25896. }
  25897. /**
  25898. * @ngdoc directive
  25899. * @name ngNonBindable
  25900. * @restrict AC
  25901. * @priority 1000
  25902. *
  25903. * @description
  25904. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  25905. * DOM element. This is useful if the element contains what appears to be Angular directives and
  25906. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  25907. * displays snippets of code, for instance.
  25908. *
  25909. * @element ANY
  25910. *
  25911. * @example
  25912. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  25913. * but the one wrapped in `ngNonBindable` is left alone.
  25914. *
  25915. * @example
  25916. <example>
  25917. <file name="index.html">
  25918. <div>Normal: {{1 + 2}}</div>
  25919. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  25920. </file>
  25921. <file name="protractor.js" type="protractor">
  25922. it('should check ng-non-bindable', function() {
  25923. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  25924. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  25925. });
  25926. </file>
  25927. </example>
  25928. */
  25929. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  25930. /* global jqLiteRemove */
  25931. var ngOptionsMinErr = minErr('ngOptions');
  25932. /**
  25933. * @ngdoc directive
  25934. * @name ngOptions
  25935. * @restrict A
  25936. *
  25937. * @description
  25938. *
  25939. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  25940. * elements for the `<select>` element using the array or object obtained by evaluating the
  25941. * `ngOptions` comprehension expression.
  25942. *
  25943. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  25944. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  25945. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  25946. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  25947. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  25948. * to a non-string value. This is because an option element can only be bound to string values at
  25949. * present.
  25950. *
  25951. * When an item in the `<select>` menu is selected, the array element or object property
  25952. * represented by the selected option will be bound to the model identified by the `ngModel`
  25953. * directive.
  25954. *
  25955. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  25956. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  25957. * option. See example below for demonstration.
  25958. *
  25959. * ## Complex Models (objects or collections)
  25960. *
  25961. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  25962. * binding the select to a model that is an object or a collection.
  25963. *
  25964. * One issue occurs if you want to preselect an option. For example, if you set
  25965. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  25966. * because the objects are not identical. So by default, you should always reference the item in your collection
  25967. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  25968. *
  25969. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  25970. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  25971. * collection items have an id property, you would `track by item.id`.
  25972. *
  25973. * A different issue with objects or collections is that ngModel won't detect if an object property or
  25974. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  25975. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  25976. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  25977. * has not changed identity, but only a property on the object or an item in the collection changes.
  25978. *
  25979. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  25980. * if the model is an array). This means that changing a property deeper than the first level inside the
  25981. * object/collection will not trigger a re-rendering.
  25982. *
  25983. * ## `select` **`as`**
  25984. *
  25985. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  25986. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  25987. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  25988. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  25989. *
  25990. *
  25991. * ### `select` **`as`** and **`track by`**
  25992. *
  25993. * <div class="alert alert-warning">
  25994. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  25995. * </div>
  25996. *
  25997. * Given this array of items on the $scope:
  25998. *
  25999. * ```js
  26000. * $scope.items = [{
  26001. * id: 1,
  26002. * label: 'aLabel',
  26003. * subItem: { name: 'aSubItem' }
  26004. * }, {
  26005. * id: 2,
  26006. * label: 'bLabel',
  26007. * subItem: { name: 'bSubItem' }
  26008. * }];
  26009. * ```
  26010. *
  26011. * This will work:
  26012. *
  26013. * ```html
  26014. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  26015. * ```
  26016. * ```js
  26017. * $scope.selected = $scope.items[0];
  26018. * ```
  26019. *
  26020. * but this will not work:
  26021. *
  26022. * ```html
  26023. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  26024. * ```
  26025. * ```js
  26026. * $scope.selected = $scope.items[0].subItem;
  26027. * ```
  26028. *
  26029. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  26030. * `items` array. Because the selected option has been set programmatically in the controller, the
  26031. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  26032. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  26033. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  26034. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  26035. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  26036. *
  26037. *
  26038. * @param {string} ngModel Assignable angular expression to data-bind to.
  26039. * @param {string=} name Property name of the form under which the control is published.
  26040. * @param {string=} required The control is considered valid only if value is entered.
  26041. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  26042. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  26043. * `required` when you want to data-bind to the `required` attribute.
  26044. * @param {comprehension_expression=} ngOptions in one of the following forms:
  26045. *
  26046. * * for array data sources:
  26047. * * `label` **`for`** `value` **`in`** `array`
  26048. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  26049. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  26050. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  26051. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  26052. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  26053. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  26054. * (for including a filter with `track by`)
  26055. * * for object data sources:
  26056. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  26057. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  26058. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  26059. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  26060. * * `select` **`as`** `label` **`group by`** `group`
  26061. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  26062. * * `select` **`as`** `label` **`disable when`** `disable`
  26063. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  26064. *
  26065. * Where:
  26066. *
  26067. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  26068. * * `value`: local variable which will refer to each item in the `array` or each property value
  26069. * of `object` during iteration.
  26070. * * `key`: local variable which will refer to a property name in `object` during iteration.
  26071. * * `label`: The result of this expression will be the label for `<option>` element. The
  26072. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  26073. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  26074. * element. If not specified, `select` expression will default to `value`.
  26075. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  26076. * DOM element.
  26077. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  26078. * element. Return `true` to disable.
  26079. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  26080. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  26081. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  26082. * even when the options are recreated (e.g. reloaded from the server).
  26083. *
  26084. * @example
  26085. <example module="selectExample">
  26086. <file name="index.html">
  26087. <script>
  26088. angular.module('selectExample', [])
  26089. .controller('ExampleController', ['$scope', function($scope) {
  26090. $scope.colors = [
  26091. {name:'black', shade:'dark'},
  26092. {name:'white', shade:'light', notAnOption: true},
  26093. {name:'red', shade:'dark'},
  26094. {name:'blue', shade:'dark', notAnOption: true},
  26095. {name:'yellow', shade:'light', notAnOption: false}
  26096. ];
  26097. $scope.myColor = $scope.colors[2]; // red
  26098. }]);
  26099. </script>
  26100. <div ng-controller="ExampleController">
  26101. <ul>
  26102. <li ng-repeat="color in colors">
  26103. <label>Name: <input ng-model="color.name"></label>
  26104. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  26105. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  26106. </li>
  26107. <li>
  26108. <button ng-click="colors.push({})">add</button>
  26109. </li>
  26110. </ul>
  26111. <hr/>
  26112. <label>Color (null not allowed):
  26113. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  26114. </label><br/>
  26115. <label>Color (null allowed):
  26116. <span class="nullable">
  26117. <select ng-model="myColor" ng-options="color.name for color in colors">
  26118. <option value="">-- choose color --</option>
  26119. </select>
  26120. </span></label><br/>
  26121. <label>Color grouped by shade:
  26122. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  26123. </select>
  26124. </label><br/>
  26125. <label>Color grouped by shade, with some disabled:
  26126. <select ng-model="myColor"
  26127. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  26128. </select>
  26129. </label><br/>
  26130. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  26131. <br/>
  26132. <hr/>
  26133. Currently selected: {{ {selected_color:myColor} }}
  26134. <div style="border:solid 1px black; height:20px"
  26135. ng-style="{'background-color':myColor.name}">
  26136. </div>
  26137. </div>
  26138. </file>
  26139. <file name="protractor.js" type="protractor">
  26140. it('should check ng-options', function() {
  26141. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  26142. element.all(by.model('myColor')).first().click();
  26143. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  26144. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  26145. element(by.css('.nullable select[ng-model="myColor"]')).click();
  26146. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  26147. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  26148. });
  26149. </file>
  26150. </example>
  26151. */
  26152. // jshint maxlen: false
  26153. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  26154. 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]+?))?$/;
  26155. // 1: value expression (valueFn)
  26156. // 2: label expression (displayFn)
  26157. // 3: group by expression (groupByFn)
  26158. // 4: disable when expression (disableWhenFn)
  26159. // 5: array item variable name
  26160. // 6: object item key variable name
  26161. // 7: object item value variable name
  26162. // 8: collection expression
  26163. // 9: track by expression
  26164. // jshint maxlen: 100
  26165. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  26166. function parseOptionsExpression(optionsExp, selectElement, scope) {
  26167. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  26168. if (!(match)) {
  26169. throw ngOptionsMinErr('iexp',
  26170. "Expected expression in form of " +
  26171. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  26172. " but got '{0}'. Element: {1}",
  26173. optionsExp, startingTag(selectElement));
  26174. }
  26175. // Extract the parts from the ngOptions expression
  26176. // The variable name for the value of the item in the collection
  26177. var valueName = match[5] || match[7];
  26178. // The variable name for the key of the item in the collection
  26179. var keyName = match[6];
  26180. // An expression that generates the viewValue for an option if there is a label expression
  26181. var selectAs = / as /.test(match[0]) && match[1];
  26182. // An expression that is used to track the id of each object in the options collection
  26183. var trackBy = match[9];
  26184. // An expression that generates the viewValue for an option if there is no label expression
  26185. var valueFn = $parse(match[2] ? match[1] : valueName);
  26186. var selectAsFn = selectAs && $parse(selectAs);
  26187. var viewValueFn = selectAsFn || valueFn;
  26188. var trackByFn = trackBy && $parse(trackBy);
  26189. // Get the value by which we are going to track the option
  26190. // if we have a trackFn then use that (passing scope and locals)
  26191. // otherwise just hash the given viewValue
  26192. var getTrackByValueFn = trackBy ?
  26193. function(value, locals) { return trackByFn(scope, locals); } :
  26194. function getHashOfValue(value) { return hashKey(value); };
  26195. var getTrackByValue = function(value, key) {
  26196. return getTrackByValueFn(value, getLocals(value, key));
  26197. };
  26198. var displayFn = $parse(match[2] || match[1]);
  26199. var groupByFn = $parse(match[3] || '');
  26200. var disableWhenFn = $parse(match[4] || '');
  26201. var valuesFn = $parse(match[8]);
  26202. var locals = {};
  26203. var getLocals = keyName ? function(value, key) {
  26204. locals[keyName] = key;
  26205. locals[valueName] = value;
  26206. return locals;
  26207. } : function(value) {
  26208. locals[valueName] = value;
  26209. return locals;
  26210. };
  26211. function Option(selectValue, viewValue, label, group, disabled) {
  26212. this.selectValue = selectValue;
  26213. this.viewValue = viewValue;
  26214. this.label = label;
  26215. this.group = group;
  26216. this.disabled = disabled;
  26217. }
  26218. function getOptionValuesKeys(optionValues) {
  26219. var optionValuesKeys;
  26220. if (!keyName && isArrayLike(optionValues)) {
  26221. optionValuesKeys = optionValues;
  26222. } else {
  26223. // if object, extract keys, in enumeration order, unsorted
  26224. optionValuesKeys = [];
  26225. for (var itemKey in optionValues) {
  26226. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  26227. optionValuesKeys.push(itemKey);
  26228. }
  26229. }
  26230. }
  26231. return optionValuesKeys;
  26232. }
  26233. return {
  26234. trackBy: trackBy,
  26235. getTrackByValue: getTrackByValue,
  26236. getWatchables: $parse(valuesFn, function(optionValues) {
  26237. // Create a collection of things that we would like to watch (watchedArray)
  26238. // so that they can all be watched using a single $watchCollection
  26239. // that only runs the handler once if anything changes
  26240. var watchedArray = [];
  26241. optionValues = optionValues || [];
  26242. var optionValuesKeys = getOptionValuesKeys(optionValues);
  26243. var optionValuesLength = optionValuesKeys.length;
  26244. for (var index = 0; index < optionValuesLength; index++) {
  26245. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  26246. var value = optionValues[key];
  26247. var locals = getLocals(value, key);
  26248. var selectValue = getTrackByValueFn(value, locals);
  26249. watchedArray.push(selectValue);
  26250. // Only need to watch the displayFn if there is a specific label expression
  26251. if (match[2] || match[1]) {
  26252. var label = displayFn(scope, locals);
  26253. watchedArray.push(label);
  26254. }
  26255. // Only need to watch the disableWhenFn if there is a specific disable expression
  26256. if (match[4]) {
  26257. var disableWhen = disableWhenFn(scope, locals);
  26258. watchedArray.push(disableWhen);
  26259. }
  26260. }
  26261. return watchedArray;
  26262. }),
  26263. getOptions: function() {
  26264. var optionItems = [];
  26265. var selectValueMap = {};
  26266. // The option values were already computed in the `getWatchables` fn,
  26267. // which must have been called to trigger `getOptions`
  26268. var optionValues = valuesFn(scope) || [];
  26269. var optionValuesKeys = getOptionValuesKeys(optionValues);
  26270. var optionValuesLength = optionValuesKeys.length;
  26271. for (var index = 0; index < optionValuesLength; index++) {
  26272. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  26273. var value = optionValues[key];
  26274. var locals = getLocals(value, key);
  26275. var viewValue = viewValueFn(scope, locals);
  26276. var selectValue = getTrackByValueFn(viewValue, locals);
  26277. var label = displayFn(scope, locals);
  26278. var group = groupByFn(scope, locals);
  26279. var disabled = disableWhenFn(scope, locals);
  26280. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  26281. optionItems.push(optionItem);
  26282. selectValueMap[selectValue] = optionItem;
  26283. }
  26284. return {
  26285. items: optionItems,
  26286. selectValueMap: selectValueMap,
  26287. getOptionFromViewValue: function(value) {
  26288. return selectValueMap[getTrackByValue(value)];
  26289. },
  26290. getViewValueFromOption: function(option) {
  26291. // If the viewValue could be an object that may be mutated by the application,
  26292. // we need to make a copy and not return the reference to the value on the option.
  26293. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  26294. }
  26295. };
  26296. }
  26297. };
  26298. }
  26299. // we can't just jqLite('<option>') since jqLite is not smart enough
  26300. // to create it in <select> and IE barfs otherwise.
  26301. var optionTemplate = window.document.createElement('option'),
  26302. optGroupTemplate = window.document.createElement('optgroup');
  26303. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  26304. var selectCtrl = ctrls[0];
  26305. var ngModelCtrl = ctrls[1];
  26306. var multiple = attr.multiple;
  26307. // The emptyOption allows the application developer to provide their own custom "empty"
  26308. // option when the viewValue does not match any of the option values.
  26309. var emptyOption;
  26310. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  26311. if (children[i].value === '') {
  26312. emptyOption = children.eq(i);
  26313. break;
  26314. }
  26315. }
  26316. var providedEmptyOption = !!emptyOption;
  26317. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  26318. unknownOption.val('?');
  26319. var options;
  26320. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  26321. // This stores the newly created options before they are appended to the select.
  26322. // Since the contents are removed from the fragment when it is appended,
  26323. // we only need to create it once.
  26324. var listFragment = $document[0].createDocumentFragment();
  26325. var renderEmptyOption = function() {
  26326. if (!providedEmptyOption) {
  26327. selectElement.prepend(emptyOption);
  26328. }
  26329. selectElement.val('');
  26330. emptyOption.prop('selected', true); // needed for IE
  26331. emptyOption.attr('selected', true);
  26332. };
  26333. var removeEmptyOption = function() {
  26334. if (!providedEmptyOption) {
  26335. emptyOption.remove();
  26336. }
  26337. };
  26338. var renderUnknownOption = function() {
  26339. selectElement.prepend(unknownOption);
  26340. selectElement.val('?');
  26341. unknownOption.prop('selected', true); // needed for IE
  26342. unknownOption.attr('selected', true);
  26343. };
  26344. var removeUnknownOption = function() {
  26345. unknownOption.remove();
  26346. };
  26347. // Update the controller methods for multiple selectable options
  26348. if (!multiple) {
  26349. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  26350. var option = options.getOptionFromViewValue(value);
  26351. if (option) {
  26352. // Don't update the option when it is already selected.
  26353. // For example, the browser will select the first option by default. In that case,
  26354. // most properties are set automatically - except the `selected` attribute, which we
  26355. // set always
  26356. if (selectElement[0].value !== option.selectValue) {
  26357. removeUnknownOption();
  26358. removeEmptyOption();
  26359. selectElement[0].value = option.selectValue;
  26360. option.element.selected = true;
  26361. }
  26362. option.element.setAttribute('selected', 'selected');
  26363. } else {
  26364. if (value === null || providedEmptyOption) {
  26365. removeUnknownOption();
  26366. renderEmptyOption();
  26367. } else {
  26368. removeEmptyOption();
  26369. renderUnknownOption();
  26370. }
  26371. }
  26372. };
  26373. selectCtrl.readValue = function readNgOptionsValue() {
  26374. var selectedOption = options.selectValueMap[selectElement.val()];
  26375. if (selectedOption && !selectedOption.disabled) {
  26376. removeEmptyOption();
  26377. removeUnknownOption();
  26378. return options.getViewValueFromOption(selectedOption);
  26379. }
  26380. return null;
  26381. };
  26382. // If we are using `track by` then we must watch the tracked value on the model
  26383. // since ngModel only watches for object identity change
  26384. if (ngOptions.trackBy) {
  26385. scope.$watch(
  26386. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  26387. function() { ngModelCtrl.$render(); }
  26388. );
  26389. }
  26390. } else {
  26391. ngModelCtrl.$isEmpty = function(value) {
  26392. return !value || value.length === 0;
  26393. };
  26394. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  26395. options.items.forEach(function(option) {
  26396. option.element.selected = false;
  26397. });
  26398. if (value) {
  26399. value.forEach(function(item) {
  26400. var option = options.getOptionFromViewValue(item);
  26401. if (option) option.element.selected = true;
  26402. });
  26403. }
  26404. };
  26405. selectCtrl.readValue = function readNgOptionsMultiple() {
  26406. var selectedValues = selectElement.val() || [],
  26407. selections = [];
  26408. forEach(selectedValues, function(value) {
  26409. var option = options.selectValueMap[value];
  26410. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  26411. });
  26412. return selections;
  26413. };
  26414. // If we are using `track by` then we must watch these tracked values on the model
  26415. // since ngModel only watches for object identity change
  26416. if (ngOptions.trackBy) {
  26417. scope.$watchCollection(function() {
  26418. if (isArray(ngModelCtrl.$viewValue)) {
  26419. return ngModelCtrl.$viewValue.map(function(value) {
  26420. return ngOptions.getTrackByValue(value);
  26421. });
  26422. }
  26423. }, function() {
  26424. ngModelCtrl.$render();
  26425. });
  26426. }
  26427. }
  26428. if (providedEmptyOption) {
  26429. // we need to remove it before calling selectElement.empty() because otherwise IE will
  26430. // remove the label from the element. wtf?
  26431. emptyOption.remove();
  26432. // compile the element since there might be bindings in it
  26433. $compile(emptyOption)(scope);
  26434. // remove the class, which is added automatically because we recompile the element and it
  26435. // becomes the compilation root
  26436. emptyOption.removeClass('ng-scope');
  26437. } else {
  26438. emptyOption = jqLite(optionTemplate.cloneNode(false));
  26439. }
  26440. selectElement.empty();
  26441. // We need to do this here to ensure that the options object is defined
  26442. // when we first hit it in writeNgOptionsValue
  26443. updateOptions();
  26444. // We will re-render the option elements if the option values or labels change
  26445. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  26446. // ------------------------------------------------------------------ //
  26447. function addOptionElement(option, parent) {
  26448. var optionElement = optionTemplate.cloneNode(false);
  26449. parent.appendChild(optionElement);
  26450. updateOptionElement(option, optionElement);
  26451. }
  26452. function updateOptionElement(option, element) {
  26453. option.element = element;
  26454. element.disabled = option.disabled;
  26455. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  26456. // selects in certain circumstances when multiple selects are next to each other and display
  26457. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  26458. // See https://github.com/angular/angular.js/issues/11314 for more info.
  26459. // This is unfortunately untestable with unit / e2e tests
  26460. if (option.label !== element.label) {
  26461. element.label = option.label;
  26462. element.textContent = option.label;
  26463. }
  26464. if (option.value !== element.value) element.value = option.selectValue;
  26465. }
  26466. function updateOptions() {
  26467. var previousValue = options && selectCtrl.readValue();
  26468. // We must remove all current options, but cannot simply set innerHTML = null
  26469. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  26470. // must preserve.
  26471. // Instead, iterate over the current option elements and remove them or their optgroup
  26472. // parents
  26473. if (options) {
  26474. for (var i = options.items.length - 1; i >= 0; i--) {
  26475. var option = options.items[i];
  26476. if (isDefined(option.group)) {
  26477. jqLiteRemove(option.element.parentNode);
  26478. } else {
  26479. jqLiteRemove(option.element);
  26480. }
  26481. }
  26482. }
  26483. options = ngOptions.getOptions();
  26484. var groupElementMap = {};
  26485. // Ensure that the empty option is always there if it was explicitly provided
  26486. if (providedEmptyOption) {
  26487. selectElement.prepend(emptyOption);
  26488. }
  26489. options.items.forEach(function addOption(option) {
  26490. var groupElement;
  26491. if (isDefined(option.group)) {
  26492. // This option is to live in a group
  26493. // See if we have already created this group
  26494. groupElement = groupElementMap[option.group];
  26495. if (!groupElement) {
  26496. groupElement = optGroupTemplate.cloneNode(false);
  26497. listFragment.appendChild(groupElement);
  26498. // Update the label on the group element
  26499. // "null" is special cased because of Safari
  26500. groupElement.label = option.group === null ? 'null' : option.group;
  26501. // Store it for use later
  26502. groupElementMap[option.group] = groupElement;
  26503. }
  26504. addOptionElement(option, groupElement);
  26505. } else {
  26506. // This option is not in a group
  26507. addOptionElement(option, listFragment);
  26508. }
  26509. });
  26510. selectElement[0].appendChild(listFragment);
  26511. ngModelCtrl.$render();
  26512. // Check to see if the value has changed due to the update to the options
  26513. if (!ngModelCtrl.$isEmpty(previousValue)) {
  26514. var nextValue = selectCtrl.readValue();
  26515. var isNotPrimitive = ngOptions.trackBy || multiple;
  26516. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  26517. ngModelCtrl.$setViewValue(nextValue);
  26518. ngModelCtrl.$render();
  26519. }
  26520. }
  26521. }
  26522. }
  26523. return {
  26524. restrict: 'A',
  26525. terminal: true,
  26526. require: ['select', 'ngModel'],
  26527. link: {
  26528. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  26529. // Deactivate the SelectController.register method to prevent
  26530. // option directives from accidentally registering themselves
  26531. // (and unwanted $destroy handlers etc.)
  26532. ctrls[0].registerOption = noop;
  26533. },
  26534. post: ngOptionsPostLink
  26535. }
  26536. };
  26537. }];
  26538. /**
  26539. * @ngdoc directive
  26540. * @name ngPluralize
  26541. * @restrict EA
  26542. *
  26543. * @description
  26544. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  26545. * These rules are bundled with angular.js, but can be overridden
  26546. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  26547. * by specifying the mappings between
  26548. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  26549. * and the strings to be displayed.
  26550. *
  26551. * # Plural categories and explicit number rules
  26552. * There are two
  26553. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  26554. * in Angular's default en-US locale: "one" and "other".
  26555. *
  26556. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  26557. * any number that is not 1), an explicit number rule can only match one number. For example, the
  26558. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  26559. * and explicit number rules throughout the rest of this documentation.
  26560. *
  26561. * # Configuring ngPluralize
  26562. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  26563. * You can also provide an optional attribute, `offset`.
  26564. *
  26565. * The value of the `count` attribute can be either a string or an {@link guide/expression
  26566. * Angular expression}; these are evaluated on the current scope for its bound value.
  26567. *
  26568. * The `when` attribute specifies the mappings between plural categories and the actual
  26569. * string to be displayed. The value of the attribute should be a JSON object.
  26570. *
  26571. * The following example shows how to configure ngPluralize:
  26572. *
  26573. * ```html
  26574. * <ng-pluralize count="personCount"
  26575. when="{'0': 'Nobody is viewing.',
  26576. * 'one': '1 person is viewing.',
  26577. * 'other': '{} people are viewing.'}">
  26578. * </ng-pluralize>
  26579. *```
  26580. *
  26581. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  26582. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  26583. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  26584. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  26585. * show "a dozen people are viewing".
  26586. *
  26587. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  26588. * into pluralized strings. In the previous example, Angular will replace `{}` with
  26589. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  26590. * for <span ng-non-bindable>{{numberExpression}}</span>.
  26591. *
  26592. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  26593. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  26594. *
  26595. * # Configuring ngPluralize with offset
  26596. * The `offset` attribute allows further customization of pluralized text, which can result in
  26597. * a better user experience. For example, instead of the message "4 people are viewing this document",
  26598. * you might display "John, Kate and 2 others are viewing this document".
  26599. * The offset attribute allows you to offset a number by any desired value.
  26600. * Let's take a look at an example:
  26601. *
  26602. * ```html
  26603. * <ng-pluralize count="personCount" offset=2
  26604. * when="{'0': 'Nobody is viewing.',
  26605. * '1': '{{person1}} is viewing.',
  26606. * '2': '{{person1}} and {{person2}} are viewing.',
  26607. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  26608. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  26609. * </ng-pluralize>
  26610. * ```
  26611. *
  26612. * Notice that we are still using two plural categories(one, other), but we added
  26613. * three explicit number rules 0, 1 and 2.
  26614. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  26615. * When three people view the document, no explicit number rule is found, so
  26616. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  26617. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  26618. * is shown.
  26619. *
  26620. * Note that when you specify offsets, you must provide explicit number rules for
  26621. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  26622. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  26623. * plural categories "one" and "other".
  26624. *
  26625. * @param {string|expression} count The variable to be bound to.
  26626. * @param {string} when The mapping between plural category to its corresponding strings.
  26627. * @param {number=} offset Offset to deduct from the total number.
  26628. *
  26629. * @example
  26630. <example module="pluralizeExample">
  26631. <file name="index.html">
  26632. <script>
  26633. angular.module('pluralizeExample', [])
  26634. .controller('ExampleController', ['$scope', function($scope) {
  26635. $scope.person1 = 'Igor';
  26636. $scope.person2 = 'Misko';
  26637. $scope.personCount = 1;
  26638. }]);
  26639. </script>
  26640. <div ng-controller="ExampleController">
  26641. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  26642. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  26643. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  26644. <!--- Example with simple pluralization rules for en locale --->
  26645. Without Offset:
  26646. <ng-pluralize count="personCount"
  26647. when="{'0': 'Nobody is viewing.',
  26648. 'one': '1 person is viewing.',
  26649. 'other': '{} people are viewing.'}">
  26650. </ng-pluralize><br>
  26651. <!--- Example with offset --->
  26652. With Offset(2):
  26653. <ng-pluralize count="personCount" offset=2
  26654. when="{'0': 'Nobody is viewing.',
  26655. '1': '{{person1}} is viewing.',
  26656. '2': '{{person1}} and {{person2}} are viewing.',
  26657. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  26658. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  26659. </ng-pluralize>
  26660. </div>
  26661. </file>
  26662. <file name="protractor.js" type="protractor">
  26663. it('should show correct pluralized string', function() {
  26664. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  26665. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  26666. var countInput = element(by.model('personCount'));
  26667. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  26668. expect(withOffset.getText()).toEqual('Igor is viewing.');
  26669. countInput.clear();
  26670. countInput.sendKeys('0');
  26671. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  26672. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  26673. countInput.clear();
  26674. countInput.sendKeys('2');
  26675. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  26676. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  26677. countInput.clear();
  26678. countInput.sendKeys('3');
  26679. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  26680. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  26681. countInput.clear();
  26682. countInput.sendKeys('4');
  26683. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  26684. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  26685. });
  26686. it('should show data-bound names', function() {
  26687. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  26688. var personCount = element(by.model('personCount'));
  26689. var person1 = element(by.model('person1'));
  26690. var person2 = element(by.model('person2'));
  26691. personCount.clear();
  26692. personCount.sendKeys('4');
  26693. person1.clear();
  26694. person1.sendKeys('Di');
  26695. person2.clear();
  26696. person2.sendKeys('Vojta');
  26697. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  26698. });
  26699. </file>
  26700. </example>
  26701. */
  26702. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  26703. var BRACE = /{}/g,
  26704. IS_WHEN = /^when(Minus)?(.+)$/;
  26705. return {
  26706. link: function(scope, element, attr) {
  26707. var numberExp = attr.count,
  26708. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  26709. offset = attr.offset || 0,
  26710. whens = scope.$eval(whenExp) || {},
  26711. whensExpFns = {},
  26712. startSymbol = $interpolate.startSymbol(),
  26713. endSymbol = $interpolate.endSymbol(),
  26714. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  26715. watchRemover = angular.noop,
  26716. lastCount;
  26717. forEach(attr, function(expression, attributeName) {
  26718. var tmpMatch = IS_WHEN.exec(attributeName);
  26719. if (tmpMatch) {
  26720. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  26721. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  26722. }
  26723. });
  26724. forEach(whens, function(expression, key) {
  26725. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  26726. });
  26727. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  26728. var count = parseFloat(newVal);
  26729. var countIsNaN = isNaN(count);
  26730. if (!countIsNaN && !(count in whens)) {
  26731. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  26732. // Otherwise, check it against pluralization rules in $locale service.
  26733. count = $locale.pluralCat(count - offset);
  26734. }
  26735. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  26736. // In JS `NaN !== NaN`, so we have to explicitly check.
  26737. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  26738. watchRemover();
  26739. var whenExpFn = whensExpFns[count];
  26740. if (isUndefined(whenExpFn)) {
  26741. if (newVal != null) {
  26742. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  26743. }
  26744. watchRemover = noop;
  26745. updateElementText();
  26746. } else {
  26747. watchRemover = scope.$watch(whenExpFn, updateElementText);
  26748. }
  26749. lastCount = count;
  26750. }
  26751. });
  26752. function updateElementText(newText) {
  26753. element.text(newText || '');
  26754. }
  26755. }
  26756. };
  26757. }];
  26758. /**
  26759. * @ngdoc directive
  26760. * @name ngRepeat
  26761. * @multiElement
  26762. *
  26763. * @description
  26764. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  26765. * instance gets its own scope, where the given loop variable is set to the current collection item,
  26766. * and `$index` is set to the item index or key.
  26767. *
  26768. * Special properties are exposed on the local scope of each template instance, including:
  26769. *
  26770. * | Variable | Type | Details |
  26771. * |-----------|-----------------|-----------------------------------------------------------------------------|
  26772. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  26773. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  26774. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  26775. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  26776. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  26777. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  26778. *
  26779. * <div class="alert alert-info">
  26780. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  26781. * This may be useful when, for instance, nesting ngRepeats.
  26782. * </div>
  26783. *
  26784. *
  26785. * # Iterating over object properties
  26786. *
  26787. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  26788. * syntax:
  26789. *
  26790. * ```js
  26791. * <div ng-repeat="(key, value) in myObj"> ... </div>
  26792. * ```
  26793. *
  26794. * However, there are a limitations compared to array iteration:
  26795. *
  26796. * - The JavaScript specification does not define the order of keys
  26797. * returned for an object, so Angular relies on the order returned by the browser
  26798. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  26799. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  26800. * and reinstated. See the
  26801. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  26802. *
  26803. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  26804. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  26805. *
  26806. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  26807. * objects, and will throw an error if used with one.
  26808. *
  26809. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  26810. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  26811. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  26812. * or implement a `$watch` on the object yourself.
  26813. *
  26814. *
  26815. * # Tracking and Duplicates
  26816. *
  26817. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  26818. * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
  26819. *
  26820. * * When an item is added, a new instance of the template is added to the DOM.
  26821. * * When an item is removed, its template instance is removed from the DOM.
  26822. * * When items are reordered, their respective templates are reordered in the DOM.
  26823. *
  26824. * To minimize creation of DOM elements, `ngRepeat` uses a function
  26825. * to "keep track" of all items in the collection and their corresponding DOM elements.
  26826. * For example, if an item is added to the collection, ngRepeat will know that all other items
  26827. * already have DOM elements, and will not re-render them.
  26828. *
  26829. * The default tracking function (which tracks items by their identity) does not allow
  26830. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  26831. * to maintain a one-to-one mapping between collection items and DOM elements.
  26832. *
  26833. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  26834. * with your own using the `track by` expression.
  26835. *
  26836. * For example, you may track items by the index of each item in the collection, using the
  26837. * special scope property `$index`:
  26838. * ```html
  26839. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  26840. * {{n}}
  26841. * </div>
  26842. * ```
  26843. *
  26844. * You may also use arbitrary expressions in `track by`, including references to custom functions
  26845. * on the scope:
  26846. * ```html
  26847. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  26848. * {{n}}
  26849. * </div>
  26850. * ```
  26851. *
  26852. * <div class="alert alert-success">
  26853. * If you are working with objects that have an identifier property, you should track
  26854. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  26855. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  26856. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  26857. * this significantly improves rendering performance. If you don't have a unique identifier,
  26858. * `track by $index` can also provide a performance boost.
  26859. * </div>
  26860. * ```html
  26861. * <div ng-repeat="model in collection track by model.id">
  26862. * {{model.name}}
  26863. * </div>
  26864. * ```
  26865. *
  26866. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  26867. * `$id` function, which tracks items by their identity:
  26868. * ```html
  26869. * <div ng-repeat="obj in collection track by $id(obj)">
  26870. * {{obj.prop}}
  26871. * </div>
  26872. * ```
  26873. *
  26874. * <div class="alert alert-warning">
  26875. * **Note:** `track by` must always be the last expression:
  26876. * </div>
  26877. * ```
  26878. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  26879. * {{model.name}}
  26880. * </div>
  26881. * ```
  26882. *
  26883. * # Special repeat start and end points
  26884. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  26885. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  26886. * 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)
  26887. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  26888. *
  26889. * The example below makes use of this feature:
  26890. * ```html
  26891. * <header ng-repeat-start="item in items">
  26892. * Header {{ item }}
  26893. * </header>
  26894. * <div class="body">
  26895. * Body {{ item }}
  26896. * </div>
  26897. * <footer ng-repeat-end>
  26898. * Footer {{ item }}
  26899. * </footer>
  26900. * ```
  26901. *
  26902. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  26903. * ```html
  26904. * <header>
  26905. * Header A
  26906. * </header>
  26907. * <div class="body">
  26908. * Body A
  26909. * </div>
  26910. * <footer>
  26911. * Footer A
  26912. * </footer>
  26913. * <header>
  26914. * Header B
  26915. * </header>
  26916. * <div class="body">
  26917. * Body B
  26918. * </div>
  26919. * <footer>
  26920. * Footer B
  26921. * </footer>
  26922. * ```
  26923. *
  26924. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  26925. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  26926. *
  26927. * @animations
  26928. * | Animation | Occurs |
  26929. * |----------------------------------|-------------------------------------|
  26930. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  26931. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  26932. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  26933. *
  26934. * See the example below for defining CSS animations with ngRepeat.
  26935. *
  26936. * @element ANY
  26937. * @scope
  26938. * @priority 1000
  26939. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  26940. * formats are currently supported:
  26941. *
  26942. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  26943. * is a scope expression giving the collection to enumerate.
  26944. *
  26945. * For example: `album in artist.albums`.
  26946. *
  26947. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  26948. * and `expression` is the scope expression giving the collection to enumerate.
  26949. *
  26950. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  26951. *
  26952. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  26953. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  26954. * is specified, ng-repeat associates elements by identity. It is an error to have
  26955. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  26956. * mapped to the same DOM element, which is not possible.)
  26957. *
  26958. * Note that the tracking expression must come last, after any filters, and the alias expression.
  26959. *
  26960. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  26961. * will be associated by item identity in the array.
  26962. *
  26963. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  26964. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  26965. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  26966. * element in the same way in the DOM.
  26967. *
  26968. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  26969. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  26970. * property is same.
  26971. *
  26972. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  26973. * to items in conjunction with a tracking expression.
  26974. *
  26975. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  26976. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  26977. * when a filter is active on the repeater, but the filtered result set is empty.
  26978. *
  26979. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  26980. * the items have been processed through the filter.
  26981. *
  26982. * 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
  26983. * (and not as operator, inside an expression).
  26984. *
  26985. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  26986. *
  26987. * @example
  26988. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  26989. * results by name. New (entering) and removed (leaving) items are animated.
  26990. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
  26991. <file name="index.html">
  26992. <div ng-controller="repeatController">
  26993. I have {{friends.length}} friends. They are:
  26994. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  26995. <ul class="example-animate-container">
  26996. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  26997. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  26998. </li>
  26999. <li class="animate-repeat" ng-if="results.length == 0">
  27000. <strong>No results found...</strong>
  27001. </li>
  27002. </ul>
  27003. </div>
  27004. </file>
  27005. <file name="script.js">
  27006. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  27007. $scope.friends = [
  27008. {name:'John', age:25, gender:'boy'},
  27009. {name:'Jessie', age:30, gender:'girl'},
  27010. {name:'Johanna', age:28, gender:'girl'},
  27011. {name:'Joy', age:15, gender:'girl'},
  27012. {name:'Mary', age:28, gender:'girl'},
  27013. {name:'Peter', age:95, gender:'boy'},
  27014. {name:'Sebastian', age:50, gender:'boy'},
  27015. {name:'Erika', age:27, gender:'girl'},
  27016. {name:'Patrick', age:40, gender:'boy'},
  27017. {name:'Samantha', age:60, gender:'girl'}
  27018. ];
  27019. });
  27020. </file>
  27021. <file name="animations.css">
  27022. .example-animate-container {
  27023. background:white;
  27024. border:1px solid black;
  27025. list-style:none;
  27026. margin:0;
  27027. padding:0 10px;
  27028. }
  27029. .animate-repeat {
  27030. line-height:30px;
  27031. list-style:none;
  27032. box-sizing:border-box;
  27033. }
  27034. .animate-repeat.ng-move,
  27035. .animate-repeat.ng-enter,
  27036. .animate-repeat.ng-leave {
  27037. transition:all linear 0.5s;
  27038. }
  27039. .animate-repeat.ng-leave.ng-leave-active,
  27040. .animate-repeat.ng-move,
  27041. .animate-repeat.ng-enter {
  27042. opacity:0;
  27043. max-height:0;
  27044. }
  27045. .animate-repeat.ng-leave,
  27046. .animate-repeat.ng-move.ng-move-active,
  27047. .animate-repeat.ng-enter.ng-enter-active {
  27048. opacity:1;
  27049. max-height:30px;
  27050. }
  27051. </file>
  27052. <file name="protractor.js" type="protractor">
  27053. var friends = element.all(by.repeater('friend in friends'));
  27054. it('should render initial data set', function() {
  27055. expect(friends.count()).toBe(10);
  27056. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  27057. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  27058. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  27059. expect(element(by.binding('friends.length')).getText())
  27060. .toMatch("I have 10 friends. They are:");
  27061. });
  27062. it('should update repeater when filter predicate changes', function() {
  27063. expect(friends.count()).toBe(10);
  27064. element(by.model('q')).sendKeys('ma');
  27065. expect(friends.count()).toBe(2);
  27066. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  27067. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  27068. });
  27069. </file>
  27070. </example>
  27071. */
  27072. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  27073. var NG_REMOVED = '$$NG_REMOVED';
  27074. var ngRepeatMinErr = minErr('ngRepeat');
  27075. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  27076. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  27077. scope[valueIdentifier] = value;
  27078. if (keyIdentifier) scope[keyIdentifier] = key;
  27079. scope.$index = index;
  27080. scope.$first = (index === 0);
  27081. scope.$last = (index === (arrayLength - 1));
  27082. scope.$middle = !(scope.$first || scope.$last);
  27083. // jshint bitwise: false
  27084. scope.$odd = !(scope.$even = (index&1) === 0);
  27085. // jshint bitwise: true
  27086. };
  27087. var getBlockStart = function(block) {
  27088. return block.clone[0];
  27089. };
  27090. var getBlockEnd = function(block) {
  27091. return block.clone[block.clone.length - 1];
  27092. };
  27093. return {
  27094. restrict: 'A',
  27095. multiElement: true,
  27096. transclude: 'element',
  27097. priority: 1000,
  27098. terminal: true,
  27099. $$tlb: true,
  27100. compile: function ngRepeatCompile($element, $attr) {
  27101. var expression = $attr.ngRepeat;
  27102. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  27103. 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*$/);
  27104. if (!match) {
  27105. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  27106. expression);
  27107. }
  27108. var lhs = match[1];
  27109. var rhs = match[2];
  27110. var aliasAs = match[3];
  27111. var trackByExp = match[4];
  27112. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  27113. if (!match) {
  27114. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  27115. lhs);
  27116. }
  27117. var valueIdentifier = match[3] || match[1];
  27118. var keyIdentifier = match[2];
  27119. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  27120. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  27121. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  27122. aliasAs);
  27123. }
  27124. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  27125. var hashFnLocals = {$id: hashKey};
  27126. if (trackByExp) {
  27127. trackByExpGetter = $parse(trackByExp);
  27128. } else {
  27129. trackByIdArrayFn = function(key, value) {
  27130. return hashKey(value);
  27131. };
  27132. trackByIdObjFn = function(key) {
  27133. return key;
  27134. };
  27135. }
  27136. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  27137. if (trackByExpGetter) {
  27138. trackByIdExpFn = function(key, value, index) {
  27139. // assign key, value, and $index to the locals so that they can be used in hash functions
  27140. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  27141. hashFnLocals[valueIdentifier] = value;
  27142. hashFnLocals.$index = index;
  27143. return trackByExpGetter($scope, hashFnLocals);
  27144. };
  27145. }
  27146. // Store a list of elements from previous run. This is a hash where key is the item from the
  27147. // iterator, and the value is objects with following properties.
  27148. // - scope: bound scope
  27149. // - element: previous element.
  27150. // - index: position
  27151. //
  27152. // We are using no-proto object so that we don't need to guard against inherited props via
  27153. // hasOwnProperty.
  27154. var lastBlockMap = createMap();
  27155. //watch props
  27156. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  27157. var index, length,
  27158. previousNode = $element[0], // node that cloned nodes should be inserted after
  27159. // initialized to the comment node anchor
  27160. nextNode,
  27161. // Same as lastBlockMap but it has the current state. It will become the
  27162. // lastBlockMap on the next iteration.
  27163. nextBlockMap = createMap(),
  27164. collectionLength,
  27165. key, value, // key/value of iteration
  27166. trackById,
  27167. trackByIdFn,
  27168. collectionKeys,
  27169. block, // last object information {scope, element, id}
  27170. nextBlockOrder,
  27171. elementsToRemove;
  27172. if (aliasAs) {
  27173. $scope[aliasAs] = collection;
  27174. }
  27175. if (isArrayLike(collection)) {
  27176. collectionKeys = collection;
  27177. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  27178. } else {
  27179. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  27180. // if object, extract keys, in enumeration order, unsorted
  27181. collectionKeys = [];
  27182. for (var itemKey in collection) {
  27183. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  27184. collectionKeys.push(itemKey);
  27185. }
  27186. }
  27187. }
  27188. collectionLength = collectionKeys.length;
  27189. nextBlockOrder = new Array(collectionLength);
  27190. // locate existing items
  27191. for (index = 0; index < collectionLength; index++) {
  27192. key = (collection === collectionKeys) ? index : collectionKeys[index];
  27193. value = collection[key];
  27194. trackById = trackByIdFn(key, value, index);
  27195. if (lastBlockMap[trackById]) {
  27196. // found previously seen block
  27197. block = lastBlockMap[trackById];
  27198. delete lastBlockMap[trackById];
  27199. nextBlockMap[trackById] = block;
  27200. nextBlockOrder[index] = block;
  27201. } else if (nextBlockMap[trackById]) {
  27202. // if collision detected. restore lastBlockMap and throw an error
  27203. forEach(nextBlockOrder, function(block) {
  27204. if (block && block.scope) lastBlockMap[block.id] = block;
  27205. });
  27206. throw ngRepeatMinErr('dupes',
  27207. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  27208. expression, trackById, value);
  27209. } else {
  27210. // new never before seen block
  27211. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  27212. nextBlockMap[trackById] = true;
  27213. }
  27214. }
  27215. // remove leftover items
  27216. for (var blockKey in lastBlockMap) {
  27217. block = lastBlockMap[blockKey];
  27218. elementsToRemove = getBlockNodes(block.clone);
  27219. $animate.leave(elementsToRemove);
  27220. if (elementsToRemove[0].parentNode) {
  27221. // if the element was not removed yet because of pending animation, mark it as deleted
  27222. // so that we can ignore it later
  27223. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  27224. elementsToRemove[index][NG_REMOVED] = true;
  27225. }
  27226. }
  27227. block.scope.$destroy();
  27228. }
  27229. // we are not using forEach for perf reasons (trying to avoid #call)
  27230. for (index = 0; index < collectionLength; index++) {
  27231. key = (collection === collectionKeys) ? index : collectionKeys[index];
  27232. value = collection[key];
  27233. block = nextBlockOrder[index];
  27234. if (block.scope) {
  27235. // if we have already seen this object, then we need to reuse the
  27236. // associated scope/element
  27237. nextNode = previousNode;
  27238. // skip nodes that are already pending removal via leave animation
  27239. do {
  27240. nextNode = nextNode.nextSibling;
  27241. } while (nextNode && nextNode[NG_REMOVED]);
  27242. if (getBlockStart(block) != nextNode) {
  27243. // existing item which got moved
  27244. $animate.move(getBlockNodes(block.clone), null, previousNode);
  27245. }
  27246. previousNode = getBlockEnd(block);
  27247. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  27248. } else {
  27249. // new item which we don't know about
  27250. $transclude(function ngRepeatTransclude(clone, scope) {
  27251. block.scope = scope;
  27252. // http://jsperf.com/clone-vs-createcomment
  27253. var endNode = ngRepeatEndComment.cloneNode(false);
  27254. clone[clone.length++] = endNode;
  27255. $animate.enter(clone, null, previousNode);
  27256. previousNode = endNode;
  27257. // Note: We only need the first/last node of the cloned nodes.
  27258. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  27259. // by a directive with templateUrl when its template arrives.
  27260. block.clone = clone;
  27261. nextBlockMap[block.id] = block;
  27262. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  27263. });
  27264. }
  27265. }
  27266. lastBlockMap = nextBlockMap;
  27267. });
  27268. };
  27269. }
  27270. };
  27271. }];
  27272. var NG_HIDE_CLASS = 'ng-hide';
  27273. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  27274. /**
  27275. * @ngdoc directive
  27276. * @name ngShow
  27277. * @multiElement
  27278. *
  27279. * @description
  27280. * The `ngShow` directive shows or hides the given HTML element based on the expression
  27281. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  27282. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  27283. * in AngularJS and sets the display style to none (using an !important flag).
  27284. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  27285. *
  27286. * ```html
  27287. * <!-- when $scope.myValue is truthy (element is visible) -->
  27288. * <div ng-show="myValue"></div>
  27289. *
  27290. * <!-- when $scope.myValue is falsy (element is hidden) -->
  27291. * <div ng-show="myValue" class="ng-hide"></div>
  27292. * ```
  27293. *
  27294. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  27295. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  27296. * from the element causing the element not to appear hidden.
  27297. *
  27298. * ## Why is !important used?
  27299. *
  27300. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  27301. * can be easily overridden by heavier selectors. For example, something as simple
  27302. * as changing the display style on a HTML list item would make hidden elements appear visible.
  27303. * This also becomes a bigger issue when dealing with CSS frameworks.
  27304. *
  27305. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  27306. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  27307. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  27308. *
  27309. * ### Overriding `.ng-hide`
  27310. *
  27311. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  27312. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  27313. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  27314. * with extra animation classes that can be added.
  27315. *
  27316. * ```css
  27317. * .ng-hide:not(.ng-hide-animate) {
  27318. * /&#42; this is just another form of hiding an element &#42;/
  27319. * display: block!important;
  27320. * position: absolute;
  27321. * top: -9999px;
  27322. * left: -9999px;
  27323. * }
  27324. * ```
  27325. *
  27326. * By default you don't need to override in CSS anything and the animations will work around the display style.
  27327. *
  27328. * ## A note about animations with `ngShow`
  27329. *
  27330. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  27331. * is true and false. This system works like the animation system present with ngClass except that
  27332. * you must also include the !important flag to override the display property
  27333. * so that you can perform an animation when the element is hidden during the time of the animation.
  27334. *
  27335. * ```css
  27336. * //
  27337. * //a working example can be found at the bottom of this page
  27338. * //
  27339. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  27340. * /&#42; this is required as of 1.3x to properly
  27341. * apply all styling in a show/hide animation &#42;/
  27342. * transition: 0s linear all;
  27343. * }
  27344. *
  27345. * .my-element.ng-hide-add-active,
  27346. * .my-element.ng-hide-remove-active {
  27347. * /&#42; the transition is defined in the active class &#42;/
  27348. * transition: 1s linear all;
  27349. * }
  27350. *
  27351. * .my-element.ng-hide-add { ... }
  27352. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  27353. * .my-element.ng-hide-remove { ... }
  27354. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  27355. * ```
  27356. *
  27357. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  27358. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  27359. *
  27360. * @animations
  27361. * | Animation | Occurs |
  27362. * |----------------------------------|-------------------------------------|
  27363. * | {@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 |
  27364. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngShow` expression evaluates to a truthy value and just before contents are set to visible |
  27365. *
  27366. * @element ANY
  27367. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  27368. * then the element is shown or hidden respectively.
  27369. *
  27370. * @example
  27371. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  27372. <file name="index.html">
  27373. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  27374. <div>
  27375. Show:
  27376. <div class="check-element animate-show" ng-show="checked">
  27377. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  27378. </div>
  27379. </div>
  27380. <div>
  27381. Hide:
  27382. <div class="check-element animate-show" ng-hide="checked">
  27383. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  27384. </div>
  27385. </div>
  27386. </file>
  27387. <file name="glyphicons.css">
  27388. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  27389. </file>
  27390. <file name="animations.css">
  27391. .animate-show {
  27392. line-height: 20px;
  27393. opacity: 1;
  27394. padding: 10px;
  27395. border: 1px solid black;
  27396. background: white;
  27397. }
  27398. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  27399. transition: all linear 0.5s;
  27400. }
  27401. .animate-show.ng-hide {
  27402. line-height: 0;
  27403. opacity: 0;
  27404. padding: 0 10px;
  27405. }
  27406. .check-element {
  27407. padding: 10px;
  27408. border: 1px solid black;
  27409. background: white;
  27410. }
  27411. </file>
  27412. <file name="protractor.js" type="protractor">
  27413. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  27414. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  27415. it('should check ng-show / ng-hide', function() {
  27416. expect(thumbsUp.isDisplayed()).toBeFalsy();
  27417. expect(thumbsDown.isDisplayed()).toBeTruthy();
  27418. element(by.model('checked')).click();
  27419. expect(thumbsUp.isDisplayed()).toBeTruthy();
  27420. expect(thumbsDown.isDisplayed()).toBeFalsy();
  27421. });
  27422. </file>
  27423. </example>
  27424. */
  27425. var ngShowDirective = ['$animate', function($animate) {
  27426. return {
  27427. restrict: 'A',
  27428. multiElement: true,
  27429. link: function(scope, element, attr) {
  27430. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  27431. // we're adding a temporary, animation-specific class for ng-hide since this way
  27432. // we can control when the element is actually displayed on screen without having
  27433. // to have a global/greedy CSS selector that breaks when other animations are run.
  27434. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  27435. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  27436. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  27437. });
  27438. });
  27439. }
  27440. };
  27441. }];
  27442. /**
  27443. * @ngdoc directive
  27444. * @name ngHide
  27445. * @multiElement
  27446. *
  27447. * @description
  27448. * The `ngHide` directive shows or hides the given HTML element based on the expression
  27449. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  27450. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  27451. * in AngularJS and sets the display style to none (using an !important flag).
  27452. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  27453. *
  27454. * ```html
  27455. * <!-- when $scope.myValue is truthy (element is hidden) -->
  27456. * <div ng-hide="myValue" class="ng-hide"></div>
  27457. *
  27458. * <!-- when $scope.myValue is falsy (element is visible) -->
  27459. * <div ng-hide="myValue"></div>
  27460. * ```
  27461. *
  27462. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  27463. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  27464. * from the element causing the element not to appear hidden.
  27465. *
  27466. * ## Why is !important used?
  27467. *
  27468. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  27469. * can be easily overridden by heavier selectors. For example, something as simple
  27470. * as changing the display style on a HTML list item would make hidden elements appear visible.
  27471. * This also becomes a bigger issue when dealing with CSS frameworks.
  27472. *
  27473. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  27474. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  27475. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  27476. *
  27477. * ### Overriding `.ng-hide`
  27478. *
  27479. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  27480. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  27481. * class in CSS:
  27482. *
  27483. * ```css
  27484. * .ng-hide {
  27485. * /&#42; this is just another form of hiding an element &#42;/
  27486. * display: block!important;
  27487. * position: absolute;
  27488. * top: -9999px;
  27489. * left: -9999px;
  27490. * }
  27491. * ```
  27492. *
  27493. * By default you don't need to override in CSS anything and the animations will work around the display style.
  27494. *
  27495. * ## A note about animations with `ngHide`
  27496. *
  27497. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  27498. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  27499. * CSS class is added and removed for you instead of your own CSS class.
  27500. *
  27501. * ```css
  27502. * //
  27503. * //a working example can be found at the bottom of this page
  27504. * //
  27505. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  27506. * transition: 0.5s linear all;
  27507. * }
  27508. *
  27509. * .my-element.ng-hide-add { ... }
  27510. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  27511. * .my-element.ng-hide-remove { ... }
  27512. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  27513. * ```
  27514. *
  27515. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  27516. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  27517. *
  27518. * @animations
  27519. * | Animation | Occurs |
  27520. * |----------------------------------|-------------------------------------|
  27521. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden |
  27522. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible |
  27523. *
  27524. *
  27525. * @element ANY
  27526. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  27527. * the element is shown or hidden respectively.
  27528. *
  27529. * @example
  27530. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  27531. <file name="index.html">
  27532. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  27533. <div>
  27534. Show:
  27535. <div class="check-element animate-hide" ng-show="checked">
  27536. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  27537. </div>
  27538. </div>
  27539. <div>
  27540. Hide:
  27541. <div class="check-element animate-hide" ng-hide="checked">
  27542. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  27543. </div>
  27544. </div>
  27545. </file>
  27546. <file name="glyphicons.css">
  27547. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  27548. </file>
  27549. <file name="animations.css">
  27550. .animate-hide {
  27551. transition: all linear 0.5s;
  27552. line-height: 20px;
  27553. opacity: 1;
  27554. padding: 10px;
  27555. border: 1px solid black;
  27556. background: white;
  27557. }
  27558. .animate-hide.ng-hide {
  27559. line-height: 0;
  27560. opacity: 0;
  27561. padding: 0 10px;
  27562. }
  27563. .check-element {
  27564. padding: 10px;
  27565. border: 1px solid black;
  27566. background: white;
  27567. }
  27568. </file>
  27569. <file name="protractor.js" type="protractor">
  27570. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  27571. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  27572. it('should check ng-show / ng-hide', function() {
  27573. expect(thumbsUp.isDisplayed()).toBeFalsy();
  27574. expect(thumbsDown.isDisplayed()).toBeTruthy();
  27575. element(by.model('checked')).click();
  27576. expect(thumbsUp.isDisplayed()).toBeTruthy();
  27577. expect(thumbsDown.isDisplayed()).toBeFalsy();
  27578. });
  27579. </file>
  27580. </example>
  27581. */
  27582. var ngHideDirective = ['$animate', function($animate) {
  27583. return {
  27584. restrict: 'A',
  27585. multiElement: true,
  27586. link: function(scope, element, attr) {
  27587. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  27588. // The comment inside of the ngShowDirective explains why we add and
  27589. // remove a temporary class for the show/hide animation
  27590. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  27591. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  27592. });
  27593. });
  27594. }
  27595. };
  27596. }];
  27597. /**
  27598. * @ngdoc directive
  27599. * @name ngStyle
  27600. * @restrict AC
  27601. *
  27602. * @description
  27603. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  27604. *
  27605. * @knownIssue
  27606. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  27607. * attribute, when using the `ngStyle` directive on the same element.
  27608. * See {@link guide/interpolation#known-issues here} for more info.
  27609. *
  27610. * @element ANY
  27611. * @param {expression} ngStyle
  27612. *
  27613. * {@link guide/expression Expression} which evals to an
  27614. * object whose keys are CSS style names and values are corresponding values for those CSS
  27615. * keys.
  27616. *
  27617. * Since some CSS style names are not valid keys for an object, they must be quoted.
  27618. * See the 'background-color' style in the example below.
  27619. *
  27620. * @example
  27621. <example>
  27622. <file name="index.html">
  27623. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  27624. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  27625. <input type="button" value="clear" ng-click="myStyle={}">
  27626. <br/>
  27627. <span ng-style="myStyle">Sample Text</span>
  27628. <pre>myStyle={{myStyle}}</pre>
  27629. </file>
  27630. <file name="style.css">
  27631. span {
  27632. color: black;
  27633. }
  27634. </file>
  27635. <file name="protractor.js" type="protractor">
  27636. var colorSpan = element(by.css('span'));
  27637. it('should check ng-style', function() {
  27638. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  27639. element(by.css('input[value=\'set color\']')).click();
  27640. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  27641. element(by.css('input[value=clear]')).click();
  27642. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  27643. });
  27644. </file>
  27645. </example>
  27646. */
  27647. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  27648. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  27649. if (oldStyles && (newStyles !== oldStyles)) {
  27650. forEach(oldStyles, function(val, style) { element.css(style, '');});
  27651. }
  27652. if (newStyles) element.css(newStyles);
  27653. }, true);
  27654. });
  27655. /**
  27656. * @ngdoc directive
  27657. * @name ngSwitch
  27658. * @restrict EA
  27659. *
  27660. * @description
  27661. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  27662. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  27663. * as specified in the template.
  27664. *
  27665. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  27666. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  27667. * matches the value obtained from the evaluated expression. In other words, you define a container element
  27668. * (where you place the directive), place an expression on the **`on="..."` attribute**
  27669. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  27670. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  27671. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  27672. * attribute is displayed.
  27673. *
  27674. * <div class="alert alert-info">
  27675. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  27676. * as literal string values to match against.
  27677. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  27678. * value of the expression `$scope.someVal`.
  27679. * </div>
  27680. * @animations
  27681. * | Animation | Occurs |
  27682. * |----------------------------------|-------------------------------------|
  27683. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  27684. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  27685. *
  27686. * @usage
  27687. *
  27688. * ```
  27689. * <ANY ng-switch="expression">
  27690. * <ANY ng-switch-when="matchValue1">...</ANY>
  27691. * <ANY ng-switch-when="matchValue2">...</ANY>
  27692. * <ANY ng-switch-default>...</ANY>
  27693. * </ANY>
  27694. * ```
  27695. *
  27696. *
  27697. * @scope
  27698. * @priority 1200
  27699. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  27700. * On child elements add:
  27701. *
  27702. * * `ngSwitchWhen`: the case statement to match against. If match then this
  27703. * case will be displayed. If the same match appears multiple times, all the
  27704. * elements will be displayed.
  27705. * * `ngSwitchDefault`: the default case when no other case match. If there
  27706. * are multiple default cases, all of them will be displayed when no other
  27707. * case match.
  27708. *
  27709. *
  27710. * @example
  27711. <example module="switchExample" deps="angular-animate.js" animations="true">
  27712. <file name="index.html">
  27713. <div ng-controller="ExampleController">
  27714. <select ng-model="selection" ng-options="item for item in items">
  27715. </select>
  27716. <code>selection={{selection}}</code>
  27717. <hr/>
  27718. <div class="animate-switch-container"
  27719. ng-switch on="selection">
  27720. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  27721. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  27722. <div class="animate-switch" ng-switch-default>default</div>
  27723. </div>
  27724. </div>
  27725. </file>
  27726. <file name="script.js">
  27727. angular.module('switchExample', ['ngAnimate'])
  27728. .controller('ExampleController', ['$scope', function($scope) {
  27729. $scope.items = ['settings', 'home', 'other'];
  27730. $scope.selection = $scope.items[0];
  27731. }]);
  27732. </file>
  27733. <file name="animations.css">
  27734. .animate-switch-container {
  27735. position:relative;
  27736. background:white;
  27737. border:1px solid black;
  27738. height:40px;
  27739. overflow:hidden;
  27740. }
  27741. .animate-switch {
  27742. padding:10px;
  27743. }
  27744. .animate-switch.ng-animate {
  27745. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  27746. position:absolute;
  27747. top:0;
  27748. left:0;
  27749. right:0;
  27750. bottom:0;
  27751. }
  27752. .animate-switch.ng-leave.ng-leave-active,
  27753. .animate-switch.ng-enter {
  27754. top:-50px;
  27755. }
  27756. .animate-switch.ng-leave,
  27757. .animate-switch.ng-enter.ng-enter-active {
  27758. top:0;
  27759. }
  27760. </file>
  27761. <file name="protractor.js" type="protractor">
  27762. var switchElem = element(by.css('[ng-switch]'));
  27763. var select = element(by.model('selection'));
  27764. it('should start in settings', function() {
  27765. expect(switchElem.getText()).toMatch(/Settings Div/);
  27766. });
  27767. it('should change to home', function() {
  27768. select.all(by.css('option')).get(1).click();
  27769. expect(switchElem.getText()).toMatch(/Home Span/);
  27770. });
  27771. it('should select default', function() {
  27772. select.all(by.css('option')).get(2).click();
  27773. expect(switchElem.getText()).toMatch(/default/);
  27774. });
  27775. </file>
  27776. </example>
  27777. */
  27778. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  27779. return {
  27780. require: 'ngSwitch',
  27781. // asks for $scope to fool the BC controller module
  27782. controller: ['$scope', function ngSwitchController() {
  27783. this.cases = {};
  27784. }],
  27785. link: function(scope, element, attr, ngSwitchController) {
  27786. var watchExpr = attr.ngSwitch || attr.on,
  27787. selectedTranscludes = [],
  27788. selectedElements = [],
  27789. previousLeaveAnimations = [],
  27790. selectedScopes = [];
  27791. var spliceFactory = function(array, index) {
  27792. return function() { array.splice(index, 1); };
  27793. };
  27794. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  27795. var i, ii;
  27796. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  27797. $animate.cancel(previousLeaveAnimations[i]);
  27798. }
  27799. previousLeaveAnimations.length = 0;
  27800. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  27801. var selected = getBlockNodes(selectedElements[i].clone);
  27802. selectedScopes[i].$destroy();
  27803. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  27804. promise.then(spliceFactory(previousLeaveAnimations, i));
  27805. }
  27806. selectedElements.length = 0;
  27807. selectedScopes.length = 0;
  27808. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  27809. forEach(selectedTranscludes, function(selectedTransclude) {
  27810. selectedTransclude.transclude(function(caseElement, selectedScope) {
  27811. selectedScopes.push(selectedScope);
  27812. var anchor = selectedTransclude.element;
  27813. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  27814. var block = { clone: caseElement };
  27815. selectedElements.push(block);
  27816. $animate.enter(caseElement, anchor.parent(), anchor);
  27817. });
  27818. });
  27819. }
  27820. });
  27821. }
  27822. };
  27823. }];
  27824. var ngSwitchWhenDirective = ngDirective({
  27825. transclude: 'element',
  27826. priority: 1200,
  27827. require: '^ngSwitch',
  27828. multiElement: true,
  27829. link: function(scope, element, attrs, ctrl, $transclude) {
  27830. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  27831. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  27832. }
  27833. });
  27834. var ngSwitchDefaultDirective = ngDirective({
  27835. transclude: 'element',
  27836. priority: 1200,
  27837. require: '^ngSwitch',
  27838. multiElement: true,
  27839. link: function(scope, element, attr, ctrl, $transclude) {
  27840. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  27841. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  27842. }
  27843. });
  27844. /**
  27845. * @ngdoc directive
  27846. * @name ngTransclude
  27847. * @restrict EAC
  27848. *
  27849. * @description
  27850. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  27851. *
  27852. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  27853. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  27854. *
  27855. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  27856. * content of this element will be removed before the transcluded content is inserted.
  27857. * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
  27858. * that no transcluded content is provided.
  27859. *
  27860. * @element ANY
  27861. *
  27862. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  27863. * or its value is the same as the name of the attribute then the default slot is used.
  27864. *
  27865. * @example
  27866. * ### Basic transclusion
  27867. * This example demonstrates basic transclusion of content into a component directive.
  27868. * <example name="simpleTranscludeExample" module="transcludeExample">
  27869. * <file name="index.html">
  27870. * <script>
  27871. * angular.module('transcludeExample', [])
  27872. * .directive('pane', function(){
  27873. * return {
  27874. * restrict: 'E',
  27875. * transclude: true,
  27876. * scope: { title:'@' },
  27877. * template: '<div style="border: 1px solid black;">' +
  27878. * '<div style="background-color: gray">{{title}}</div>' +
  27879. * '<ng-transclude></ng-transclude>' +
  27880. * '</div>'
  27881. * };
  27882. * })
  27883. * .controller('ExampleController', ['$scope', function($scope) {
  27884. * $scope.title = 'Lorem Ipsum';
  27885. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  27886. * }]);
  27887. * </script>
  27888. * <div ng-controller="ExampleController">
  27889. * <input ng-model="title" aria-label="title"> <br/>
  27890. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  27891. * <pane title="{{title}}">{{text}}</pane>
  27892. * </div>
  27893. * </file>
  27894. * <file name="protractor.js" type="protractor">
  27895. * it('should have transcluded', function() {
  27896. * var titleElement = element(by.model('title'));
  27897. * titleElement.clear();
  27898. * titleElement.sendKeys('TITLE');
  27899. * var textElement = element(by.model('text'));
  27900. * textElement.clear();
  27901. * textElement.sendKeys('TEXT');
  27902. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  27903. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  27904. * });
  27905. * </file>
  27906. * </example>
  27907. *
  27908. * @example
  27909. * ### Transclude fallback content
  27910. * This example shows how to use `NgTransclude` with fallback content, that
  27911. * is displayed if no transcluded content is provided.
  27912. *
  27913. * <example module="transcludeFallbackContentExample">
  27914. * <file name="index.html">
  27915. * <script>
  27916. * angular.module('transcludeFallbackContentExample', [])
  27917. * .directive('myButton', function(){
  27918. * return {
  27919. * restrict: 'E',
  27920. * transclude: true,
  27921. * scope: true,
  27922. * template: '<button style="cursor: pointer;">' +
  27923. * '<ng-transclude>' +
  27924. * '<b style="color: red;">Button1</b>' +
  27925. * '</ng-transclude>' +
  27926. * '</button>'
  27927. * };
  27928. * });
  27929. * </script>
  27930. * <!-- fallback button content -->
  27931. * <my-button id="fallback"></my-button>
  27932. * <!-- modified button content -->
  27933. * <my-button id="modified">
  27934. * <i style="color: green;">Button2</i>
  27935. * </my-button>
  27936. * </file>
  27937. * <file name="protractor.js" type="protractor">
  27938. * it('should have different transclude element content', function() {
  27939. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  27940. * expect(element(by.id('modified')).getText()).toBe('Button2');
  27941. * });
  27942. * </file>
  27943. * </example>
  27944. *
  27945. * @example
  27946. * ### Multi-slot transclusion
  27947. * This example demonstrates using multi-slot transclusion in a component directive.
  27948. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  27949. * <file name="index.html">
  27950. * <style>
  27951. * .title, .footer {
  27952. * background-color: gray
  27953. * }
  27954. * </style>
  27955. * <div ng-controller="ExampleController">
  27956. * <input ng-model="title" aria-label="title"> <br/>
  27957. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  27958. * <pane>
  27959. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  27960. * <pane-body><p>{{text}}</p></pane-body>
  27961. * </pane>
  27962. * </div>
  27963. * </file>
  27964. * <file name="app.js">
  27965. * angular.module('multiSlotTranscludeExample', [])
  27966. * .directive('pane', function(){
  27967. * return {
  27968. * restrict: 'E',
  27969. * transclude: {
  27970. * 'title': '?paneTitle',
  27971. * 'body': 'paneBody',
  27972. * 'footer': '?paneFooter'
  27973. * },
  27974. * template: '<div style="border: 1px solid black;">' +
  27975. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  27976. * '<div ng-transclude="body"></div>' +
  27977. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  27978. * '</div>'
  27979. * };
  27980. * })
  27981. * .controller('ExampleController', ['$scope', function($scope) {
  27982. * $scope.title = 'Lorem Ipsum';
  27983. * $scope.link = "https://google.com";
  27984. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  27985. * }]);
  27986. * </file>
  27987. * <file name="protractor.js" type="protractor">
  27988. * it('should have transcluded the title and the body', function() {
  27989. * var titleElement = element(by.model('title'));
  27990. * titleElement.clear();
  27991. * titleElement.sendKeys('TITLE');
  27992. * var textElement = element(by.model('text'));
  27993. * textElement.clear();
  27994. * textElement.sendKeys('TEXT');
  27995. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  27996. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  27997. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  27998. * });
  27999. * </file>
  28000. * </example>
  28001. */
  28002. var ngTranscludeMinErr = minErr('ngTransclude');
  28003. var ngTranscludeDirective = ['$compile', function($compile) {
  28004. return {
  28005. restrict: 'EAC',
  28006. terminal: true,
  28007. compile: function ngTranscludeCompile(tElement) {
  28008. // Remove and cache any original content to act as a fallback
  28009. var fallbackLinkFn = $compile(tElement.contents());
  28010. tElement.empty();
  28011. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  28012. if (!$transclude) {
  28013. throw ngTranscludeMinErr('orphan',
  28014. 'Illegal use of ngTransclude directive in the template! ' +
  28015. 'No parent directive that requires a transclusion found. ' +
  28016. 'Element: {0}',
  28017. startingTag($element));
  28018. }
  28019. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  28020. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  28021. $attrs.ngTransclude = '';
  28022. }
  28023. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  28024. // If the slot is required and no transclusion content is provided then this call will throw an error
  28025. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  28026. // If the slot is optional and no transclusion content is provided then use the fallback content
  28027. if (slotName && !$transclude.isSlotFilled(slotName)) {
  28028. useFallbackContent();
  28029. }
  28030. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  28031. if (clone.length) {
  28032. $element.append(clone);
  28033. } else {
  28034. useFallbackContent();
  28035. // There is nothing linked against the transcluded scope since no content was available,
  28036. // so it should be safe to clean up the generated scope.
  28037. transcludedScope.$destroy();
  28038. }
  28039. }
  28040. function useFallbackContent() {
  28041. // Since this is the fallback content rather than the transcluded content,
  28042. // we link against the scope of this directive rather than the transcluded scope
  28043. fallbackLinkFn($scope, function(clone) {
  28044. $element.append(clone);
  28045. });
  28046. }
  28047. };
  28048. }
  28049. };
  28050. }];
  28051. /**
  28052. * @ngdoc directive
  28053. * @name script
  28054. * @restrict E
  28055. *
  28056. * @description
  28057. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  28058. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  28059. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  28060. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  28061. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  28062. *
  28063. * @param {string} type Must be set to `'text/ng-template'`.
  28064. * @param {string} id Cache name of the template.
  28065. *
  28066. * @example
  28067. <example>
  28068. <file name="index.html">
  28069. <script type="text/ng-template" id="/tpl.html">
  28070. Content of the template.
  28071. </script>
  28072. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  28073. <div id="tpl-content" ng-include src="currentTpl"></div>
  28074. </file>
  28075. <file name="protractor.js" type="protractor">
  28076. it('should load template defined inside script tag', function() {
  28077. element(by.css('#tpl-link')).click();
  28078. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  28079. });
  28080. </file>
  28081. </example>
  28082. */
  28083. var scriptDirective = ['$templateCache', function($templateCache) {
  28084. return {
  28085. restrict: 'E',
  28086. terminal: true,
  28087. compile: function(element, attr) {
  28088. if (attr.type == 'text/ng-template') {
  28089. var templateUrl = attr.id,
  28090. text = element[0].text;
  28091. $templateCache.put(templateUrl, text);
  28092. }
  28093. }
  28094. };
  28095. }];
  28096. var noopNgModelController = { $setViewValue: noop, $render: noop };
  28097. function chromeHack(optionElement) {
  28098. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  28099. // Adding an <option selected="selected"> element to a <select required="required"> should
  28100. // automatically select the new element
  28101. if (optionElement[0].hasAttribute('selected')) {
  28102. optionElement[0].selected = true;
  28103. }
  28104. }
  28105. /**
  28106. * @ngdoc type
  28107. * @name select.SelectController
  28108. * @description
  28109. * The controller for the `<select>` directive. This provides support for reading
  28110. * and writing the selected value(s) of the control and also coordinates dynamically
  28111. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  28112. */
  28113. var SelectController =
  28114. ['$element', '$scope', function($element, $scope) {
  28115. var self = this,
  28116. optionsMap = new HashMap();
  28117. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  28118. self.ngModelCtrl = noopNgModelController;
  28119. // The "unknown" option is one that is prepended to the list if the viewValue
  28120. // does not match any of the options. When it is rendered the value of the unknown
  28121. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  28122. //
  28123. // We can't just jqLite('<option>') since jqLite is not smart enough
  28124. // to create it in <select> and IE barfs otherwise.
  28125. self.unknownOption = jqLite(window.document.createElement('option'));
  28126. self.renderUnknownOption = function(val) {
  28127. var unknownVal = '? ' + hashKey(val) + ' ?';
  28128. self.unknownOption.val(unknownVal);
  28129. $element.prepend(self.unknownOption);
  28130. $element.val(unknownVal);
  28131. };
  28132. $scope.$on('$destroy', function() {
  28133. // disable unknown option so that we don't do work when the whole select is being destroyed
  28134. self.renderUnknownOption = noop;
  28135. });
  28136. self.removeUnknownOption = function() {
  28137. if (self.unknownOption.parent()) self.unknownOption.remove();
  28138. };
  28139. // Read the value of the select control, the implementation of this changes depending
  28140. // upon whether the select can have multiple values and whether ngOptions is at work.
  28141. self.readValue = function readSingleValue() {
  28142. self.removeUnknownOption();
  28143. return $element.val();
  28144. };
  28145. // Write the value to the select control, the implementation of this changes depending
  28146. // upon whether the select can have multiple values and whether ngOptions is at work.
  28147. self.writeValue = function writeSingleValue(value) {
  28148. if (self.hasOption(value)) {
  28149. self.removeUnknownOption();
  28150. $element.val(value);
  28151. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  28152. } else {
  28153. if (value == null && self.emptyOption) {
  28154. self.removeUnknownOption();
  28155. $element.val('');
  28156. } else {
  28157. self.renderUnknownOption(value);
  28158. }
  28159. }
  28160. };
  28161. // Tell the select control that an option, with the given value, has been added
  28162. self.addOption = function(value, element) {
  28163. // Skip comment nodes, as they only pollute the `optionsMap`
  28164. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  28165. assertNotHasOwnProperty(value, '"option value"');
  28166. if (value === '') {
  28167. self.emptyOption = element;
  28168. }
  28169. var count = optionsMap.get(value) || 0;
  28170. optionsMap.put(value, count + 1);
  28171. self.ngModelCtrl.$render();
  28172. chromeHack(element);
  28173. };
  28174. // Tell the select control that an option, with the given value, has been removed
  28175. self.removeOption = function(value) {
  28176. var count = optionsMap.get(value);
  28177. if (count) {
  28178. if (count === 1) {
  28179. optionsMap.remove(value);
  28180. if (value === '') {
  28181. self.emptyOption = undefined;
  28182. }
  28183. } else {
  28184. optionsMap.put(value, count - 1);
  28185. }
  28186. }
  28187. };
  28188. // Check whether the select control has an option matching the given value
  28189. self.hasOption = function(value) {
  28190. return !!optionsMap.get(value);
  28191. };
  28192. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  28193. if (interpolateValueFn) {
  28194. // The value attribute is interpolated
  28195. var oldVal;
  28196. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  28197. if (isDefined(oldVal)) {
  28198. self.removeOption(oldVal);
  28199. }
  28200. oldVal = newVal;
  28201. self.addOption(newVal, optionElement);
  28202. });
  28203. } else if (interpolateTextFn) {
  28204. // The text content is interpolated
  28205. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  28206. optionAttrs.$set('value', newVal);
  28207. if (oldVal !== newVal) {
  28208. self.removeOption(oldVal);
  28209. }
  28210. self.addOption(newVal, optionElement);
  28211. });
  28212. } else {
  28213. // The value attribute is static
  28214. self.addOption(optionAttrs.value, optionElement);
  28215. }
  28216. optionElement.on('$destroy', function() {
  28217. self.removeOption(optionAttrs.value);
  28218. self.ngModelCtrl.$render();
  28219. });
  28220. };
  28221. }];
  28222. /**
  28223. * @ngdoc directive
  28224. * @name select
  28225. * @restrict E
  28226. *
  28227. * @description
  28228. * HTML `SELECT` element with angular data-binding.
  28229. *
  28230. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  28231. * between the scope and the `<select>` control (including setting default values).
  28232. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  28233. * {@link ngOptions `ngOptions`} directives.
  28234. *
  28235. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  28236. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  28237. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  28238. * If you want dynamic value attributes, you can use interpolation inside the value attribute.
  28239. *
  28240. * <div class="alert alert-warning">
  28241. * Note that the value of a `select` directive used without `ngOptions` is always a string.
  28242. * When the model needs to be bound to a non-string value, you must either explicitly convert it
  28243. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  28244. * This is because an option element can only be bound to string values at present.
  28245. * </div>
  28246. *
  28247. * If the viewValue of `ngModel` does not match any of the options, then the control
  28248. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  28249. *
  28250. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  28251. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  28252. * option. See example below for demonstration.
  28253. *
  28254. * <div class="alert alert-info">
  28255. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  28256. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
  28257. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  28258. * comprehension expression, and additionally in reducing memory and increasing speed by not creating
  28259. * a new scope for each repeated instance.
  28260. * </div>
  28261. *
  28262. *
  28263. * @param {string} ngModel Assignable angular expression to data-bind to.
  28264. * @param {string=} name Property name of the form under which the control is published.
  28265. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  28266. * bound to the model as an array.
  28267. * @param {string=} required Sets `required` validation error key if the value is not entered.
  28268. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  28269. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  28270. * when you want to data-bind to the required attribute.
  28271. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  28272. * interaction with the select element.
  28273. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  28274. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  28275. *
  28276. * @example
  28277. * ### Simple `select` elements with static options
  28278. *
  28279. * <example name="static-select" module="staticSelect">
  28280. * <file name="index.html">
  28281. * <div ng-controller="ExampleController">
  28282. * <form name="myForm">
  28283. * <label for="singleSelect"> Single select: </label><br>
  28284. * <select name="singleSelect" ng-model="data.singleSelect">
  28285. * <option value="option-1">Option 1</option>
  28286. * <option value="option-2">Option 2</option>
  28287. * </select><br>
  28288. *
  28289. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  28290. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  28291. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  28292. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  28293. * <option value="option-2">Option 2</option>
  28294. * </select><br>
  28295. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  28296. * <tt>singleSelect = {{data.singleSelect}}</tt>
  28297. *
  28298. * <hr>
  28299. * <label for="multipleSelect"> Multiple select: </label><br>
  28300. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  28301. * <option value="option-1">Option 1</option>
  28302. * <option value="option-2">Option 2</option>
  28303. * <option value="option-3">Option 3</option>
  28304. * </select><br>
  28305. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  28306. * </form>
  28307. * </div>
  28308. * </file>
  28309. * <file name="app.js">
  28310. * angular.module('staticSelect', [])
  28311. * .controller('ExampleController', ['$scope', function($scope) {
  28312. * $scope.data = {
  28313. * singleSelect: null,
  28314. * multipleSelect: [],
  28315. * option1: 'option-1',
  28316. * };
  28317. *
  28318. * $scope.forceUnknownOption = function() {
  28319. * $scope.data.singleSelect = 'nonsense';
  28320. * };
  28321. * }]);
  28322. * </file>
  28323. *</example>
  28324. *
  28325. * ### Using `ngRepeat` to generate `select` options
  28326. * <example name="ngrepeat-select" module="ngrepeatSelect">
  28327. * <file name="index.html">
  28328. * <div ng-controller="ExampleController">
  28329. * <form name="myForm">
  28330. * <label for="repeatSelect"> Repeat select: </label>
  28331. * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
  28332. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  28333. * </select>
  28334. * </form>
  28335. * <hr>
  28336. * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
  28337. * </div>
  28338. * </file>
  28339. * <file name="app.js">
  28340. * angular.module('ngrepeatSelect', [])
  28341. * .controller('ExampleController', ['$scope', function($scope) {
  28342. * $scope.data = {
  28343. * repeatSelect: null,
  28344. * availableOptions: [
  28345. * {id: '1', name: 'Option A'},
  28346. * {id: '2', name: 'Option B'},
  28347. * {id: '3', name: 'Option C'}
  28348. * ],
  28349. * };
  28350. * }]);
  28351. * </file>
  28352. *</example>
  28353. *
  28354. *
  28355. * ### Using `select` with `ngOptions` and setting a default value
  28356. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  28357. *
  28358. * <example name="select-with-default-values" module="defaultValueSelect">
  28359. * <file name="index.html">
  28360. * <div ng-controller="ExampleController">
  28361. * <form name="myForm">
  28362. * <label for="mySelect">Make a choice:</label>
  28363. * <select name="mySelect" id="mySelect"
  28364. * ng-options="option.name for option in data.availableOptions track by option.id"
  28365. * ng-model="data.selectedOption"></select>
  28366. * </form>
  28367. * <hr>
  28368. * <tt>option = {{data.selectedOption}}</tt><br/>
  28369. * </div>
  28370. * </file>
  28371. * <file name="app.js">
  28372. * angular.module('defaultValueSelect', [])
  28373. * .controller('ExampleController', ['$scope', function($scope) {
  28374. * $scope.data = {
  28375. * availableOptions: [
  28376. * {id: '1', name: 'Option A'},
  28377. * {id: '2', name: 'Option B'},
  28378. * {id: '3', name: 'Option C'}
  28379. * ],
  28380. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  28381. * };
  28382. * }]);
  28383. * </file>
  28384. *</example>
  28385. *
  28386. *
  28387. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  28388. *
  28389. * <example name="select-with-non-string-options" module="nonStringSelect">
  28390. * <file name="index.html">
  28391. * <select ng-model="model.id" convert-to-number>
  28392. * <option value="0">Zero</option>
  28393. * <option value="1">One</option>
  28394. * <option value="2">Two</option>
  28395. * </select>
  28396. * {{ model }}
  28397. * </file>
  28398. * <file name="app.js">
  28399. * angular.module('nonStringSelect', [])
  28400. * .run(function($rootScope) {
  28401. * $rootScope.model = { id: 2 };
  28402. * })
  28403. * .directive('convertToNumber', function() {
  28404. * return {
  28405. * require: 'ngModel',
  28406. * link: function(scope, element, attrs, ngModel) {
  28407. * ngModel.$parsers.push(function(val) {
  28408. * return parseInt(val, 10);
  28409. * });
  28410. * ngModel.$formatters.push(function(val) {
  28411. * return '' + val;
  28412. * });
  28413. * }
  28414. * };
  28415. * });
  28416. * </file>
  28417. * <file name="protractor.js" type="protractor">
  28418. * it('should initialize to model', function() {
  28419. * var select = element(by.css('select'));
  28420. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  28421. * });
  28422. * </file>
  28423. * </example>
  28424. *
  28425. */
  28426. var selectDirective = function() {
  28427. return {
  28428. restrict: 'E',
  28429. require: ['select', '?ngModel'],
  28430. controller: SelectController,
  28431. priority: 1,
  28432. link: {
  28433. pre: selectPreLink,
  28434. post: selectPostLink
  28435. }
  28436. };
  28437. function selectPreLink(scope, element, attr, ctrls) {
  28438. // if ngModel is not defined, we don't need to do anything
  28439. var ngModelCtrl = ctrls[1];
  28440. if (!ngModelCtrl) return;
  28441. var selectCtrl = ctrls[0];
  28442. selectCtrl.ngModelCtrl = ngModelCtrl;
  28443. // When the selected item(s) changes we delegate getting the value of the select control
  28444. // to the `readValue` method, which can be changed if the select can have multiple
  28445. // selected values or if the options are being generated by `ngOptions`
  28446. element.on('change', function() {
  28447. scope.$apply(function() {
  28448. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  28449. });
  28450. });
  28451. // If the select allows multiple values then we need to modify how we read and write
  28452. // values from and to the control; also what it means for the value to be empty and
  28453. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  28454. // doesn't trigger rendering if only an item in the array changes.
  28455. if (attr.multiple) {
  28456. // Read value now needs to check each option to see if it is selected
  28457. selectCtrl.readValue = function readMultipleValue() {
  28458. var array = [];
  28459. forEach(element.find('option'), function(option) {
  28460. if (option.selected) {
  28461. array.push(option.value);
  28462. }
  28463. });
  28464. return array;
  28465. };
  28466. // Write value now needs to set the selected property of each matching option
  28467. selectCtrl.writeValue = function writeMultipleValue(value) {
  28468. var items = new HashMap(value);
  28469. forEach(element.find('option'), function(option) {
  28470. option.selected = isDefined(items.get(option.value));
  28471. });
  28472. };
  28473. // we have to do it on each watch since ngModel watches reference, but
  28474. // we need to work of an array, so we need to see if anything was inserted/removed
  28475. var lastView, lastViewRef = NaN;
  28476. scope.$watch(function selectMultipleWatch() {
  28477. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  28478. lastView = shallowCopy(ngModelCtrl.$viewValue);
  28479. ngModelCtrl.$render();
  28480. }
  28481. lastViewRef = ngModelCtrl.$viewValue;
  28482. });
  28483. // If we are a multiple select then value is now a collection
  28484. // so the meaning of $isEmpty changes
  28485. ngModelCtrl.$isEmpty = function(value) {
  28486. return !value || value.length === 0;
  28487. };
  28488. }
  28489. }
  28490. function selectPostLink(scope, element, attrs, ctrls) {
  28491. // if ngModel is not defined, we don't need to do anything
  28492. var ngModelCtrl = ctrls[1];
  28493. if (!ngModelCtrl) return;
  28494. var selectCtrl = ctrls[0];
  28495. // We delegate rendering to the `writeValue` method, which can be changed
  28496. // if the select can have multiple selected values or if the options are being
  28497. // generated by `ngOptions`.
  28498. // This must be done in the postLink fn to prevent $render to be called before
  28499. // all nodes have been linked correctly.
  28500. ngModelCtrl.$render = function() {
  28501. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  28502. };
  28503. }
  28504. };
  28505. // The option directive is purely designed to communicate the existence (or lack of)
  28506. // of dynamically created (and destroyed) option elements to their containing select
  28507. // directive via its controller.
  28508. var optionDirective = ['$interpolate', function($interpolate) {
  28509. return {
  28510. restrict: 'E',
  28511. priority: 100,
  28512. compile: function(element, attr) {
  28513. if (isDefined(attr.value)) {
  28514. // If the value attribute is defined, check if it contains an interpolation
  28515. var interpolateValueFn = $interpolate(attr.value, true);
  28516. } else {
  28517. // If the value attribute is not defined then we fall back to the
  28518. // text content of the option element, which may be interpolated
  28519. var interpolateTextFn = $interpolate(element.text(), true);
  28520. if (!interpolateTextFn) {
  28521. attr.$set('value', element.text());
  28522. }
  28523. }
  28524. return function(scope, element, attr) {
  28525. // This is an optimization over using ^^ since we don't want to have to search
  28526. // all the way to the root of the DOM for every single option element
  28527. var selectCtrlName = '$selectController',
  28528. parent = element.parent(),
  28529. selectCtrl = parent.data(selectCtrlName) ||
  28530. parent.parent().data(selectCtrlName); // in case we are in optgroup
  28531. if (selectCtrl) {
  28532. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  28533. }
  28534. };
  28535. }
  28536. };
  28537. }];
  28538. var styleDirective = valueFn({
  28539. restrict: 'E',
  28540. terminal: false
  28541. });
  28542. /**
  28543. * @ngdoc directive
  28544. * @name ngRequired
  28545. * @restrict A
  28546. *
  28547. * @description
  28548. *
  28549. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  28550. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  28551. * applied to custom controls.
  28552. *
  28553. * The directive sets the `required` attribute on the element if the Angular expression inside
  28554. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  28555. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  28556. * for more info.
  28557. *
  28558. * The validator will set the `required` error key to true if the `required` attribute is set and
  28559. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  28560. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  28561. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  28562. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  28563. *
  28564. * @example
  28565. * <example name="ngRequiredDirective" module="ngRequiredExample">
  28566. * <file name="index.html">
  28567. * <script>
  28568. * angular.module('ngRequiredExample', [])
  28569. * .controller('ExampleController', ['$scope', function($scope) {
  28570. * $scope.required = true;
  28571. * }]);
  28572. * </script>
  28573. * <div ng-controller="ExampleController">
  28574. * <form name="form">
  28575. * <label for="required">Toggle required: </label>
  28576. * <input type="checkbox" ng-model="required" id="required" />
  28577. * <br>
  28578. * <label for="input">This input must be filled if `required` is true: </label>
  28579. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  28580. * <hr>
  28581. * required error set? = <code>{{form.input.$error.required}}</code><br>
  28582. * model = <code>{{model}}</code>
  28583. * </form>
  28584. * </div>
  28585. * </file>
  28586. * <file name="protractor.js" type="protractor">
  28587. var required = element(by.binding('form.input.$error.required'));
  28588. var model = element(by.binding('model'));
  28589. var input = element(by.id('input'));
  28590. it('should set the required error', function() {
  28591. expect(required.getText()).toContain('true');
  28592. input.sendKeys('123');
  28593. expect(required.getText()).not.toContain('true');
  28594. expect(model.getText()).toContain('123');
  28595. });
  28596. * </file>
  28597. * </example>
  28598. */
  28599. var requiredDirective = function() {
  28600. return {
  28601. restrict: 'A',
  28602. require: '?ngModel',
  28603. link: function(scope, elm, attr, ctrl) {
  28604. if (!ctrl) return;
  28605. attr.required = true; // force truthy in case we are on non input element
  28606. ctrl.$validators.required = function(modelValue, viewValue) {
  28607. return !attr.required || !ctrl.$isEmpty(viewValue);
  28608. };
  28609. attr.$observe('required', function() {
  28610. ctrl.$validate();
  28611. });
  28612. }
  28613. };
  28614. };
  28615. /**
  28616. * @ngdoc directive
  28617. * @name ngPattern
  28618. *
  28619. * @description
  28620. *
  28621. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  28622. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  28623. *
  28624. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  28625. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  28626. * `ngPattern` attribute value:
  28627. * * If the expression evaluates to a RegExp object, then this is used directly.
  28628. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  28629. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  28630. *
  28631. * <div class="alert alert-info">
  28632. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  28633. * start at the index of the last search's match, thus not taking the whole input value into
  28634. * account.
  28635. * </div>
  28636. *
  28637. * <div class="alert alert-info">
  28638. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  28639. * differences:
  28640. * <ol>
  28641. * <li>
  28642. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  28643. * not available.
  28644. * </li>
  28645. * <li>
  28646. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  28647. * interpolated.
  28648. * </li>
  28649. * </ol>
  28650. * </div>
  28651. *
  28652. * @example
  28653. * <example name="ngPatternDirective" module="ngPatternExample">
  28654. * <file name="index.html">
  28655. * <script>
  28656. * angular.module('ngPatternExample', [])
  28657. * .controller('ExampleController', ['$scope', function($scope) {
  28658. * $scope.regex = '\\d+';
  28659. * }]);
  28660. * </script>
  28661. * <div ng-controller="ExampleController">
  28662. * <form name="form">
  28663. * <label for="regex">Set a pattern (regex string): </label>
  28664. * <input type="text" ng-model="regex" id="regex" />
  28665. * <br>
  28666. * <label for="input">This input is restricted by the current pattern: </label>
  28667. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  28668. * <hr>
  28669. * input valid? = <code>{{form.input.$valid}}</code><br>
  28670. * model = <code>{{model}}</code>
  28671. * </form>
  28672. * </div>
  28673. * </file>
  28674. * <file name="protractor.js" type="protractor">
  28675. var model = element(by.binding('model'));
  28676. var input = element(by.id('input'));
  28677. it('should validate the input with the default pattern', function() {
  28678. input.sendKeys('aaa');
  28679. expect(model.getText()).not.toContain('aaa');
  28680. input.clear().then(function() {
  28681. input.sendKeys('123');
  28682. expect(model.getText()).toContain('123');
  28683. });
  28684. });
  28685. * </file>
  28686. * </example>
  28687. */
  28688. var patternDirective = function() {
  28689. return {
  28690. restrict: 'A',
  28691. require: '?ngModel',
  28692. link: function(scope, elm, attr, ctrl) {
  28693. if (!ctrl) return;
  28694. var regexp, patternExp = attr.ngPattern || attr.pattern;
  28695. attr.$observe('pattern', function(regex) {
  28696. if (isString(regex) && regex.length > 0) {
  28697. regex = new RegExp('^' + regex + '$');
  28698. }
  28699. if (regex && !regex.test) {
  28700. throw minErr('ngPattern')('noregexp',
  28701. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  28702. regex, startingTag(elm));
  28703. }
  28704. regexp = regex || undefined;
  28705. ctrl.$validate();
  28706. });
  28707. ctrl.$validators.pattern = function(modelValue, viewValue) {
  28708. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  28709. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  28710. };
  28711. }
  28712. };
  28713. };
  28714. /**
  28715. * @ngdoc directive
  28716. * @name ngMaxlength
  28717. *
  28718. * @description
  28719. *
  28720. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  28721. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  28722. *
  28723. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  28724. * is longer than the integer obtained by evaluating the Angular expression given in the
  28725. * `ngMaxlength` attribute value.
  28726. *
  28727. * <div class="alert alert-info">
  28728. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  28729. * differences:
  28730. * <ol>
  28731. * <li>
  28732. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  28733. * validation is not available.
  28734. * </li>
  28735. * <li>
  28736. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  28737. * interpolated.
  28738. * </li>
  28739. * </ol>
  28740. * </div>
  28741. *
  28742. * @example
  28743. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  28744. * <file name="index.html">
  28745. * <script>
  28746. * angular.module('ngMaxlengthExample', [])
  28747. * .controller('ExampleController', ['$scope', function($scope) {
  28748. * $scope.maxlength = 5;
  28749. * }]);
  28750. * </script>
  28751. * <div ng-controller="ExampleController">
  28752. * <form name="form">
  28753. * <label for="maxlength">Set a maxlength: </label>
  28754. * <input type="number" ng-model="maxlength" id="maxlength" />
  28755. * <br>
  28756. * <label for="input">This input is restricted by the current maxlength: </label>
  28757. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  28758. * <hr>
  28759. * input valid? = <code>{{form.input.$valid}}</code><br>
  28760. * model = <code>{{model}}</code>
  28761. * </form>
  28762. * </div>
  28763. * </file>
  28764. * <file name="protractor.js" type="protractor">
  28765. var model = element(by.binding('model'));
  28766. var input = element(by.id('input'));
  28767. it('should validate the input with the default maxlength', function() {
  28768. input.sendKeys('abcdef');
  28769. expect(model.getText()).not.toContain('abcdef');
  28770. input.clear().then(function() {
  28771. input.sendKeys('abcde');
  28772. expect(model.getText()).toContain('abcde');
  28773. });
  28774. });
  28775. * </file>
  28776. * </example>
  28777. */
  28778. var maxlengthDirective = function() {
  28779. return {
  28780. restrict: 'A',
  28781. require: '?ngModel',
  28782. link: function(scope, elm, attr, ctrl) {
  28783. if (!ctrl) return;
  28784. var maxlength = -1;
  28785. attr.$observe('maxlength', function(value) {
  28786. var intVal = toInt(value);
  28787. maxlength = isNaN(intVal) ? -1 : intVal;
  28788. ctrl.$validate();
  28789. });
  28790. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  28791. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  28792. };
  28793. }
  28794. };
  28795. };
  28796. /**
  28797. * @ngdoc directive
  28798. * @name ngMinlength
  28799. *
  28800. * @description
  28801. *
  28802. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  28803. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  28804. *
  28805. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  28806. * is shorter than the integer obtained by evaluating the Angular expression given in the
  28807. * `ngMinlength` attribute value.
  28808. *
  28809. * <div class="alert alert-info">
  28810. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  28811. * differences:
  28812. * <ol>
  28813. * <li>
  28814. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  28815. * validation is not available.
  28816. * </li>
  28817. * <li>
  28818. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  28819. * interpolated.
  28820. * </li>
  28821. * </ol>
  28822. * </div>
  28823. *
  28824. * @example
  28825. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  28826. * <file name="index.html">
  28827. * <script>
  28828. * angular.module('ngMinlengthExample', [])
  28829. * .controller('ExampleController', ['$scope', function($scope) {
  28830. * $scope.minlength = 3;
  28831. * }]);
  28832. * </script>
  28833. * <div ng-controller="ExampleController">
  28834. * <form name="form">
  28835. * <label for="minlength">Set a minlength: </label>
  28836. * <input type="number" ng-model="minlength" id="minlength" />
  28837. * <br>
  28838. * <label for="input">This input is restricted by the current minlength: </label>
  28839. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  28840. * <hr>
  28841. * input valid? = <code>{{form.input.$valid}}</code><br>
  28842. * model = <code>{{model}}</code>
  28843. * </form>
  28844. * </div>
  28845. * </file>
  28846. * <file name="protractor.js" type="protractor">
  28847. var model = element(by.binding('model'));
  28848. var input = element(by.id('input'));
  28849. it('should validate the input with the default minlength', function() {
  28850. input.sendKeys('ab');
  28851. expect(model.getText()).not.toContain('ab');
  28852. input.sendKeys('abc');
  28853. expect(model.getText()).toContain('abc');
  28854. });
  28855. * </file>
  28856. * </example>
  28857. */
  28858. var minlengthDirective = function() {
  28859. return {
  28860. restrict: 'A',
  28861. require: '?ngModel',
  28862. link: function(scope, elm, attr, ctrl) {
  28863. if (!ctrl) return;
  28864. var minlength = 0;
  28865. attr.$observe('minlength', function(value) {
  28866. minlength = toInt(value) || 0;
  28867. ctrl.$validate();
  28868. });
  28869. ctrl.$validators.minlength = function(modelValue, viewValue) {
  28870. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  28871. };
  28872. }
  28873. };
  28874. };
  28875. if (window.angular.bootstrap) {
  28876. //AngularJS is already loaded, so we can return here...
  28877. if (window.console) {
  28878. console.log('WARNING: Tried to load angular more than once.');
  28879. }
  28880. return;
  28881. }
  28882. //try to bind to jquery now so that one can write jqLite(document).ready()
  28883. //but we will rebind on bootstrap again.
  28884. bindJQuery();
  28885. publishExternalAPI(angular);
  28886. angular.module("ngLocale", [], ["$provide", function($provide) {
  28887. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  28888. function getDecimals(n) {
  28889. n = n + '';
  28890. var i = n.indexOf('.');
  28891. return (i == -1) ? 0 : n.length - i - 1;
  28892. }
  28893. function getVF(n, opt_precision) {
  28894. var v = opt_precision;
  28895. if (undefined === v) {
  28896. v = Math.min(getDecimals(n), 3);
  28897. }
  28898. var base = Math.pow(10, v);
  28899. var f = ((n * base) | 0) % base;
  28900. return {v: v, f: f};
  28901. }
  28902. $provide.value("$locale", {
  28903. "DATETIME_FORMATS": {
  28904. "AMPMS": [
  28905. "AM",
  28906. "PM"
  28907. ],
  28908. "DAY": [
  28909. "Sunday",
  28910. "Monday",
  28911. "Tuesday",
  28912. "Wednesday",
  28913. "Thursday",
  28914. "Friday",
  28915. "Saturday"
  28916. ],
  28917. "ERANAMES": [
  28918. "Before Christ",
  28919. "Anno Domini"
  28920. ],
  28921. "ERAS": [
  28922. "BC",
  28923. "AD"
  28924. ],
  28925. "FIRSTDAYOFWEEK": 6,
  28926. "MONTH": [
  28927. "January",
  28928. "February",
  28929. "March",
  28930. "April",
  28931. "May",
  28932. "June",
  28933. "July",
  28934. "August",
  28935. "September",
  28936. "October",
  28937. "November",
  28938. "December"
  28939. ],
  28940. "SHORTDAY": [
  28941. "Sun",
  28942. "Mon",
  28943. "Tue",
  28944. "Wed",
  28945. "Thu",
  28946. "Fri",
  28947. "Sat"
  28948. ],
  28949. "SHORTMONTH": [
  28950. "Jan",
  28951. "Feb",
  28952. "Mar",
  28953. "Apr",
  28954. "May",
  28955. "Jun",
  28956. "Jul",
  28957. "Aug",
  28958. "Sep",
  28959. "Oct",
  28960. "Nov",
  28961. "Dec"
  28962. ],
  28963. "STANDALONEMONTH": [
  28964. "January",
  28965. "February",
  28966. "March",
  28967. "April",
  28968. "May",
  28969. "June",
  28970. "July",
  28971. "August",
  28972. "September",
  28973. "October",
  28974. "November",
  28975. "December"
  28976. ],
  28977. "WEEKENDRANGE": [
  28978. 5,
  28979. 6
  28980. ],
  28981. "fullDate": "EEEE, MMMM d, y",
  28982. "longDate": "MMMM d, y",
  28983. "medium": "MMM d, y h:mm:ss a",
  28984. "mediumDate": "MMM d, y",
  28985. "mediumTime": "h:mm:ss a",
  28986. "short": "M/d/yy h:mm a",
  28987. "shortDate": "M/d/yy",
  28988. "shortTime": "h:mm a"
  28989. },
  28990. "NUMBER_FORMATS": {
  28991. "CURRENCY_SYM": "$",
  28992. "DECIMAL_SEP": ".",
  28993. "GROUP_SEP": ",",
  28994. "PATTERNS": [
  28995. {
  28996. "gSize": 3,
  28997. "lgSize": 3,
  28998. "maxFrac": 3,
  28999. "minFrac": 0,
  29000. "minInt": 1,
  29001. "negPre": "-",
  29002. "negSuf": "",
  29003. "posPre": "",
  29004. "posSuf": ""
  29005. },
  29006. {
  29007. "gSize": 3,
  29008. "lgSize": 3,
  29009. "maxFrac": 2,
  29010. "minFrac": 2,
  29011. "minInt": 1,
  29012. "negPre": "-\u00a4",
  29013. "negSuf": "",
  29014. "posPre": "\u00a4",
  29015. "posSuf": ""
  29016. }
  29017. ]
  29018. },
  29019. "id": "en-us",
  29020. "localeID": "en_US",
  29021. "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;}
  29022. });
  29023. }]);
  29024. jqLite(window.document).ready(function() {
  29025. angularInit(window.document, bootstrap);
  29026. });
  29027. })(window);
  29028. !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>');