angular.js 1017 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364
  1. /**
  2. * @license AngularJS v1.4.3
  3. * (c) 2010-2015 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, document, undefined) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.4.3/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  57. encodeURIComponent(toDebugString(templateArgs[i]));
  58. }
  59. return new ErrorConstructor(message);
  60. };
  61. }
  62. /* We need to tell jshint what variables are being exported */
  63. /* global angular: true,
  64. msie: true,
  65. jqLite: true,
  66. jQuery: true,
  67. slice: true,
  68. splice: true,
  69. push: true,
  70. toString: true,
  71. ngMinErr: true,
  72. angularModule: true,
  73. uid: true,
  74. REGEX_STRING_REGEXP: true,
  75. VALIDITY_STATE_PROPERTY: true,
  76. lowercase: true,
  77. uppercase: true,
  78. manualLowercase: true,
  79. manualUppercase: true,
  80. nodeName_: true,
  81. isArrayLike: true,
  82. forEach: true,
  83. forEachSorted: true,
  84. reverseParams: true,
  85. nextUid: true,
  86. setHashKey: true,
  87. extend: true,
  88. toInt: true,
  89. inherit: true,
  90. merge: true,
  91. noop: true,
  92. identity: true,
  93. valueFn: true,
  94. isUndefined: true,
  95. isDefined: true,
  96. isObject: true,
  97. isBlankObject: true,
  98. isString: true,
  99. isNumber: true,
  100. isDate: true,
  101. isArray: true,
  102. isFunction: true,
  103. isRegExp: true,
  104. isWindow: true,
  105. isScope: true,
  106. isFile: true,
  107. isFormData: true,
  108. isBlob: true,
  109. isBoolean: true,
  110. isPromiseLike: true,
  111. trim: true,
  112. escapeForRegexp: true,
  113. isElement: true,
  114. makeMap: true,
  115. includes: true,
  116. arrayRemove: true,
  117. copy: true,
  118. shallowCopy: true,
  119. equals: true,
  120. csp: true,
  121. jq: true,
  122. concat: true,
  123. sliceArgs: true,
  124. bind: true,
  125. toJsonReplacer: true,
  126. toJson: true,
  127. fromJson: true,
  128. convertTimezoneToLocal: true,
  129. timezoneToOffset: true,
  130. startingTag: true,
  131. tryDecodeURIComponent: true,
  132. parseKeyValue: true,
  133. toKeyValue: true,
  134. encodeUriSegment: true,
  135. encodeUriQuery: true,
  136. angularInit: true,
  137. bootstrap: true,
  138. getTestability: true,
  139. snake_case: true,
  140. bindJQuery: true,
  141. assertArg: true,
  142. assertArgFn: true,
  143. assertNotHasOwnProperty: true,
  144. getter: true,
  145. getBlockNodes: true,
  146. hasOwnProperty: true,
  147. createMap: true,
  148. NODE_TYPE_ELEMENT: true,
  149. NODE_TYPE_ATTRIBUTE: true,
  150. NODE_TYPE_TEXT: true,
  151. NODE_TYPE_COMMENT: true,
  152. NODE_TYPE_DOCUMENT: true,
  153. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  154. */
  155. ////////////////////////////////////
  156. /**
  157. * @ngdoc module
  158. * @name ng
  159. * @module ng
  160. * @description
  161. *
  162. * # ng (core module)
  163. * The ng module is loaded by default when an AngularJS application is started. The module itself
  164. * contains the essential components for an AngularJS application to function. The table below
  165. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  166. * components available within this core module.
  167. *
  168. * <div doc-module-components="ng"></div>
  169. */
  170. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  171. // The name of a form control's ValidityState property.
  172. // This is used so that it's possible for internal tests to create mock ValidityStates.
  173. var VALIDITY_STATE_PROPERTY = 'validity';
  174. /**
  175. * @ngdoc function
  176. * @name angular.lowercase
  177. * @module ng
  178. * @kind function
  179. *
  180. * @description Converts the specified string to lowercase.
  181. * @param {string} string String to be converted to lowercase.
  182. * @returns {string} Lowercased string.
  183. */
  184. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  185. var hasOwnProperty = Object.prototype.hasOwnProperty;
  186. /**
  187. * @ngdoc function
  188. * @name angular.uppercase
  189. * @module ng
  190. * @kind function
  191. *
  192. * @description Converts the specified string to uppercase.
  193. * @param {string} string String to be converted to uppercase.
  194. * @returns {string} Uppercased string.
  195. */
  196. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  197. var manualLowercase = function(s) {
  198. /* jshint bitwise: false */
  199. return isString(s)
  200. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  201. : s;
  202. };
  203. var manualUppercase = function(s) {
  204. /* jshint bitwise: false */
  205. return isString(s)
  206. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  207. : s;
  208. };
  209. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  210. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  211. // with correct but slower alternatives.
  212. if ('i' !== 'I'.toLowerCase()) {
  213. lowercase = manualLowercase;
  214. uppercase = manualUppercase;
  215. }
  216. var
  217. msie, // holds major version number for IE, or NaN if UA is not IE.
  218. jqLite, // delay binding since jQuery could be loaded after us.
  219. jQuery, // delay binding
  220. slice = [].slice,
  221. splice = [].splice,
  222. push = [].push,
  223. toString = Object.prototype.toString,
  224. getPrototypeOf = Object.getPrototypeOf,
  225. ngMinErr = minErr('ng'),
  226. /** @name angular */
  227. angular = window.angular || (window.angular = {}),
  228. angularModule,
  229. uid = 0;
  230. /**
  231. * documentMode is an IE-only property
  232. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  233. */
  234. msie = document.documentMode;
  235. /**
  236. * @private
  237. * @param {*} obj
  238. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  239. * String ...)
  240. */
  241. function isArrayLike(obj) {
  242. if (obj == null || isWindow(obj)) {
  243. return false;
  244. }
  245. // Support: iOS 8.2 (not reproducible in simulator)
  246. // "length" in obj used to prevent JIT error (gh-11508)
  247. var length = "length" in Object(obj) && obj.length;
  248. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  249. return true;
  250. }
  251. return isString(obj) || isArray(obj) || length === 0 ||
  252. typeof length === 'number' && length > 0 && (length - 1) in obj;
  253. }
  254. /**
  255. * @ngdoc function
  256. * @name angular.forEach
  257. * @module ng
  258. * @kind function
  259. *
  260. * @description
  261. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  262. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  263. * is the value of an object property or an array element, `key` is the object property key or
  264. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  265. *
  266. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  267. * using the `hasOwnProperty` method.
  268. *
  269. * Unlike ES262's
  270. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  271. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  272. * return the value provided.
  273. *
  274. ```js
  275. var values = {name: 'misko', gender: 'male'};
  276. var log = [];
  277. angular.forEach(values, function(value, key) {
  278. this.push(key + ': ' + value);
  279. }, log);
  280. expect(log).toEqual(['name: misko', 'gender: male']);
  281. ```
  282. *
  283. * @param {Object|Array} obj Object to iterate over.
  284. * @param {Function} iterator Iterator function.
  285. * @param {Object=} context Object to become context (`this`) for the iterator function.
  286. * @returns {Object|Array} Reference to `obj`.
  287. */
  288. function forEach(obj, iterator, context) {
  289. var key, length;
  290. if (obj) {
  291. if (isFunction(obj)) {
  292. for (key in obj) {
  293. // Need to check if hasOwnProperty exists,
  294. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  295. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  296. iterator.call(context, obj[key], key, obj);
  297. }
  298. }
  299. } else if (isArray(obj) || isArrayLike(obj)) {
  300. var isPrimitive = typeof obj !== 'object';
  301. for (key = 0, length = obj.length; key < length; key++) {
  302. if (isPrimitive || key in obj) {
  303. iterator.call(context, obj[key], key, obj);
  304. }
  305. }
  306. } else if (obj.forEach && obj.forEach !== forEach) {
  307. obj.forEach(iterator, context, obj);
  308. } else if (isBlankObject(obj)) {
  309. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  310. for (key in obj) {
  311. iterator.call(context, obj[key], key, obj);
  312. }
  313. } else if (typeof obj.hasOwnProperty === 'function') {
  314. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  315. for (key in obj) {
  316. if (obj.hasOwnProperty(key)) {
  317. iterator.call(context, obj[key], key, obj);
  318. }
  319. }
  320. } else {
  321. // Slow path for objects which do not have a method `hasOwnProperty`
  322. for (key in obj) {
  323. if (hasOwnProperty.call(obj, key)) {
  324. iterator.call(context, obj[key], key, obj);
  325. }
  326. }
  327. }
  328. }
  329. return obj;
  330. }
  331. function forEachSorted(obj, iterator, context) {
  332. var keys = Object.keys(obj).sort();
  333. for (var i = 0; i < keys.length; i++) {
  334. iterator.call(context, obj[keys[i]], keys[i]);
  335. }
  336. return keys;
  337. }
  338. /**
  339. * when using forEach the params are value, key, but it is often useful to have key, value.
  340. * @param {function(string, *)} iteratorFn
  341. * @returns {function(*, string)}
  342. */
  343. function reverseParams(iteratorFn) {
  344. return function(value, key) { iteratorFn(key, value); };
  345. }
  346. /**
  347. * A consistent way of creating unique IDs in angular.
  348. *
  349. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  350. * we hit number precision issues in JavaScript.
  351. *
  352. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  353. *
  354. * @returns {number} an unique alpha-numeric string
  355. */
  356. function nextUid() {
  357. return ++uid;
  358. }
  359. /**
  360. * Set or clear the hashkey for an object.
  361. * @param obj object
  362. * @param h the hashkey (!truthy to delete the hashkey)
  363. */
  364. function setHashKey(obj, h) {
  365. if (h) {
  366. obj.$$hashKey = h;
  367. } else {
  368. delete obj.$$hashKey;
  369. }
  370. }
  371. function baseExtend(dst, objs, deep) {
  372. var h = dst.$$hashKey;
  373. for (var i = 0, ii = objs.length; i < ii; ++i) {
  374. var obj = objs[i];
  375. if (!isObject(obj) && !isFunction(obj)) continue;
  376. var keys = Object.keys(obj);
  377. for (var j = 0, jj = keys.length; j < jj; j++) {
  378. var key = keys[j];
  379. var src = obj[key];
  380. if (deep && isObject(src)) {
  381. if (isDate(src)) {
  382. dst[key] = new Date(src.valueOf());
  383. } else {
  384. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  385. baseExtend(dst[key], [src], true);
  386. }
  387. } else {
  388. dst[key] = src;
  389. }
  390. }
  391. }
  392. setHashKey(dst, h);
  393. return dst;
  394. }
  395. /**
  396. * @ngdoc function
  397. * @name angular.extend
  398. * @module ng
  399. * @kind function
  400. *
  401. * @description
  402. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  403. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  404. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  405. *
  406. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  407. * {@link angular.merge} for this.
  408. *
  409. * @param {Object} dst Destination object.
  410. * @param {...Object} src Source object(s).
  411. * @returns {Object} Reference to `dst`.
  412. */
  413. function extend(dst) {
  414. return baseExtend(dst, slice.call(arguments, 1), false);
  415. }
  416. /**
  417. * @ngdoc function
  418. * @name angular.merge
  419. * @module ng
  420. * @kind function
  421. *
  422. * @description
  423. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  424. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  425. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  426. *
  427. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  428. * objects, performing a deep copy.
  429. *
  430. * @param {Object} dst Destination object.
  431. * @param {...Object} src Source object(s).
  432. * @returns {Object} Reference to `dst`.
  433. */
  434. function merge(dst) {
  435. return baseExtend(dst, slice.call(arguments, 1), true);
  436. }
  437. function toInt(str) {
  438. return parseInt(str, 10);
  439. }
  440. function inherit(parent, extra) {
  441. return extend(Object.create(parent), extra);
  442. }
  443. /**
  444. * @ngdoc function
  445. * @name angular.noop
  446. * @module ng
  447. * @kind function
  448. *
  449. * @description
  450. * A function that performs no operations. This function can be useful when writing code in the
  451. * functional style.
  452. ```js
  453. function foo(callback) {
  454. var result = calculateResult();
  455. (callback || angular.noop)(result);
  456. }
  457. ```
  458. */
  459. function noop() {}
  460. noop.$inject = [];
  461. /**
  462. * @ngdoc function
  463. * @name angular.identity
  464. * @module ng
  465. * @kind function
  466. *
  467. * @description
  468. * A function that returns its first argument. This function is useful when writing code in the
  469. * functional style.
  470. *
  471. ```js
  472. function transformer(transformationFn, value) {
  473. return (transformationFn || angular.identity)(value);
  474. };
  475. ```
  476. * @param {*} value to be returned.
  477. * @returns {*} the value passed in.
  478. */
  479. function identity($) {return $;}
  480. identity.$inject = [];
  481. function valueFn(value) {return function() {return value;};}
  482. function hasCustomToString(obj) {
  483. return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
  484. }
  485. /**
  486. * @ngdoc function
  487. * @name angular.isUndefined
  488. * @module ng
  489. * @kind function
  490. *
  491. * @description
  492. * Determines if a reference is undefined.
  493. *
  494. * @param {*} value Reference to check.
  495. * @returns {boolean} True if `value` is undefined.
  496. */
  497. function isUndefined(value) {return typeof value === 'undefined';}
  498. /**
  499. * @ngdoc function
  500. * @name angular.isDefined
  501. * @module ng
  502. * @kind function
  503. *
  504. * @description
  505. * Determines if a reference is defined.
  506. *
  507. * @param {*} value Reference to check.
  508. * @returns {boolean} True if `value` is defined.
  509. */
  510. function isDefined(value) {return typeof value !== 'undefined';}
  511. /**
  512. * @ngdoc function
  513. * @name angular.isObject
  514. * @module ng
  515. * @kind function
  516. *
  517. * @description
  518. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  519. * considered to be objects. Note that JavaScript arrays are objects.
  520. *
  521. * @param {*} value Reference to check.
  522. * @returns {boolean} True if `value` is an `Object` but not `null`.
  523. */
  524. function isObject(value) {
  525. // http://jsperf.com/isobject4
  526. return value !== null && typeof value === 'object';
  527. }
  528. /**
  529. * Determine if a value is an object with a null prototype
  530. *
  531. * @returns {boolean} True if `value` is an `Object` with a null prototype
  532. */
  533. function isBlankObject(value) {
  534. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  535. }
  536. /**
  537. * @ngdoc function
  538. * @name angular.isString
  539. * @module ng
  540. * @kind function
  541. *
  542. * @description
  543. * Determines if a reference is a `String`.
  544. *
  545. * @param {*} value Reference to check.
  546. * @returns {boolean} True if `value` is a `String`.
  547. */
  548. function isString(value) {return typeof value === 'string';}
  549. /**
  550. * @ngdoc function
  551. * @name angular.isNumber
  552. * @module ng
  553. * @kind function
  554. *
  555. * @description
  556. * Determines if a reference is a `Number`.
  557. *
  558. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  559. *
  560. * If you wish to exclude these then you can use the native
  561. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  562. * method.
  563. *
  564. * @param {*} value Reference to check.
  565. * @returns {boolean} True if `value` is a `Number`.
  566. */
  567. function isNumber(value) {return typeof value === 'number';}
  568. /**
  569. * @ngdoc function
  570. * @name angular.isDate
  571. * @module ng
  572. * @kind function
  573. *
  574. * @description
  575. * Determines if a value is a date.
  576. *
  577. * @param {*} value Reference to check.
  578. * @returns {boolean} True if `value` is a `Date`.
  579. */
  580. function isDate(value) {
  581. return toString.call(value) === '[object Date]';
  582. }
  583. /**
  584. * @ngdoc function
  585. * @name angular.isArray
  586. * @module ng
  587. * @kind function
  588. *
  589. * @description
  590. * Determines if a reference is an `Array`.
  591. *
  592. * @param {*} value Reference to check.
  593. * @returns {boolean} True if `value` is an `Array`.
  594. */
  595. var isArray = Array.isArray;
  596. /**
  597. * @ngdoc function
  598. * @name angular.isFunction
  599. * @module ng
  600. * @kind function
  601. *
  602. * @description
  603. * Determines if a reference is a `Function`.
  604. *
  605. * @param {*} value Reference to check.
  606. * @returns {boolean} True if `value` is a `Function`.
  607. */
  608. function isFunction(value) {return typeof value === 'function';}
  609. /**
  610. * Determines if a value is a regular expression object.
  611. *
  612. * @private
  613. * @param {*} value Reference to check.
  614. * @returns {boolean} True if `value` is a `RegExp`.
  615. */
  616. function isRegExp(value) {
  617. return toString.call(value) === '[object RegExp]';
  618. }
  619. /**
  620. * Checks if `obj` is a window object.
  621. *
  622. * @private
  623. * @param {*} obj Object to check
  624. * @returns {boolean} True if `obj` is a window obj.
  625. */
  626. function isWindow(obj) {
  627. return obj && obj.window === obj;
  628. }
  629. function isScope(obj) {
  630. return obj && obj.$evalAsync && obj.$watch;
  631. }
  632. function isFile(obj) {
  633. return toString.call(obj) === '[object File]';
  634. }
  635. function isFormData(obj) {
  636. return toString.call(obj) === '[object FormData]';
  637. }
  638. function isBlob(obj) {
  639. return toString.call(obj) === '[object Blob]';
  640. }
  641. function isBoolean(value) {
  642. return typeof value === 'boolean';
  643. }
  644. function isPromiseLike(obj) {
  645. return obj && isFunction(obj.then);
  646. }
  647. var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
  648. function isTypedArray(value) {
  649. return TYPED_ARRAY_REGEXP.test(toString.call(value));
  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. * @param {*} source The source that will be used to make a copy.
  718. * Can be any type, including primitives, `null`, and `undefined`.
  719. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  720. * provided, must be of the same type as `source`.
  721. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  722. *
  723. * @example
  724. <example module="copyExample">
  725. <file name="index.html">
  726. <div ng-controller="ExampleController">
  727. <form novalidate class="simple-form">
  728. Name: <input type="text" ng-model="user.name" /><br />
  729. E-mail: <input type="email" ng-model="user.email" /><br />
  730. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  731. <input type="radio" ng-model="user.gender" value="female" />female<br />
  732. <button ng-click="reset()">RESET</button>
  733. <button ng-click="update(user)">SAVE</button>
  734. </form>
  735. <pre>form = {{user | json}}</pre>
  736. <pre>master = {{master | json}}</pre>
  737. </div>
  738. <script>
  739. angular.module('copyExample', [])
  740. .controller('ExampleController', ['$scope', function($scope) {
  741. $scope.master= {};
  742. $scope.update = function(user) {
  743. // Example with 1 argument
  744. $scope.master= angular.copy(user);
  745. };
  746. $scope.reset = function() {
  747. // Example with 2 arguments
  748. angular.copy($scope.master, $scope.user);
  749. };
  750. $scope.reset();
  751. }]);
  752. </script>
  753. </file>
  754. </example>
  755. */
  756. function copy(source, destination, stackSource, stackDest) {
  757. if (isWindow(source) || isScope(source)) {
  758. throw ngMinErr('cpws',
  759. "Can't copy! Making copies of Window or Scope instances is not supported.");
  760. }
  761. if (isTypedArray(destination)) {
  762. throw ngMinErr('cpta',
  763. "Can't copy! TypedArray destination cannot be mutated.");
  764. }
  765. if (!destination) {
  766. destination = source;
  767. if (isObject(source)) {
  768. var index;
  769. if (stackSource && (index = stackSource.indexOf(source)) !== -1) {
  770. return stackDest[index];
  771. }
  772. // TypedArray, Date and RegExp have specific copy functionality and must be
  773. // pushed onto the stack before returning.
  774. // Array and other objects create the base object and recurse to copy child
  775. // objects. The array/object will be pushed onto the stack when recursed.
  776. if (isArray(source)) {
  777. return copy(source, [], stackSource, stackDest);
  778. } else if (isTypedArray(source)) {
  779. destination = new source.constructor(source);
  780. } else if (isDate(source)) {
  781. destination = new Date(source.getTime());
  782. } else if (isRegExp(source)) {
  783. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  784. destination.lastIndex = source.lastIndex;
  785. } else {
  786. var emptyObject = Object.create(getPrototypeOf(source));
  787. return copy(source, emptyObject, stackSource, stackDest);
  788. }
  789. if (stackDest) {
  790. stackSource.push(source);
  791. stackDest.push(destination);
  792. }
  793. }
  794. } else {
  795. if (source === destination) throw ngMinErr('cpi',
  796. "Can't copy! Source and destination are identical.");
  797. stackSource = stackSource || [];
  798. stackDest = stackDest || [];
  799. if (isObject(source)) {
  800. stackSource.push(source);
  801. stackDest.push(destination);
  802. }
  803. var result, key;
  804. if (isArray(source)) {
  805. destination.length = 0;
  806. for (var i = 0; i < source.length; i++) {
  807. destination.push(copy(source[i], null, stackSource, stackDest));
  808. }
  809. } else {
  810. var h = destination.$$hashKey;
  811. if (isArray(destination)) {
  812. destination.length = 0;
  813. } else {
  814. forEach(destination, function(value, key) {
  815. delete destination[key];
  816. });
  817. }
  818. if (isBlankObject(source)) {
  819. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  820. for (key in source) {
  821. destination[key] = copy(source[key], null, stackSource, stackDest);
  822. }
  823. } else if (source && typeof source.hasOwnProperty === 'function') {
  824. // Slow path, which must rely on hasOwnProperty
  825. for (key in source) {
  826. if (source.hasOwnProperty(key)) {
  827. destination[key] = copy(source[key], null, stackSource, stackDest);
  828. }
  829. }
  830. } else {
  831. // Slowest path --- hasOwnProperty can't be called as a method
  832. for (key in source) {
  833. if (hasOwnProperty.call(source, key)) {
  834. destination[key] = copy(source[key], null, stackSource, stackDest);
  835. }
  836. }
  837. }
  838. setHashKey(destination,h);
  839. }
  840. }
  841. return destination;
  842. }
  843. /**
  844. * Creates a shallow copy of an object, an array or a primitive.
  845. *
  846. * Assumes that there are no proto properties for objects.
  847. */
  848. function shallowCopy(src, dst) {
  849. if (isArray(src)) {
  850. dst = dst || [];
  851. for (var i = 0, ii = src.length; i < ii; i++) {
  852. dst[i] = src[i];
  853. }
  854. } else if (isObject(src)) {
  855. dst = dst || {};
  856. for (var key in src) {
  857. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  858. dst[key] = src[key];
  859. }
  860. }
  861. }
  862. return dst || src;
  863. }
  864. /**
  865. * @ngdoc function
  866. * @name angular.equals
  867. * @module ng
  868. * @kind function
  869. *
  870. * @description
  871. * Determines if two objects or two values are equivalent. Supports value types, regular
  872. * expressions, arrays and objects.
  873. *
  874. * Two objects or values are considered equivalent if at least one of the following is true:
  875. *
  876. * * Both objects or values pass `===` comparison.
  877. * * Both objects or values are of the same type and all of their properties are equal by
  878. * comparing them with `angular.equals`.
  879. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  880. * * Both values represent the same regular expression (In JavaScript,
  881. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  882. * representation matches).
  883. *
  884. * During a property comparison, properties of `function` type and properties with names
  885. * that begin with `$` are ignored.
  886. *
  887. * Scope and DOMWindow objects are being compared only by identify (`===`).
  888. *
  889. * @param {*} o1 Object or value to compare.
  890. * @param {*} o2 Object or value to compare.
  891. * @returns {boolean} True if arguments are equal.
  892. */
  893. function equals(o1, o2) {
  894. if (o1 === o2) return true;
  895. if (o1 === null || o2 === null) return false;
  896. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  897. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  898. if (t1 == t2) {
  899. if (t1 == 'object') {
  900. if (isArray(o1)) {
  901. if (!isArray(o2)) return false;
  902. if ((length = o1.length) == o2.length) {
  903. for (key = 0; key < length; key++) {
  904. if (!equals(o1[key], o2[key])) return false;
  905. }
  906. return true;
  907. }
  908. } else if (isDate(o1)) {
  909. if (!isDate(o2)) return false;
  910. return equals(o1.getTime(), o2.getTime());
  911. } else if (isRegExp(o1)) {
  912. return isRegExp(o2) ? o1.toString() == o2.toString() : false;
  913. } else {
  914. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  915. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  916. keySet = createMap();
  917. for (key in o1) {
  918. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  919. if (!equals(o1[key], o2[key])) return false;
  920. keySet[key] = true;
  921. }
  922. for (key in o2) {
  923. if (!(key in keySet) &&
  924. key.charAt(0) !== '$' &&
  925. o2[key] !== undefined &&
  926. !isFunction(o2[key])) return false;
  927. }
  928. return true;
  929. }
  930. }
  931. }
  932. return false;
  933. }
  934. var csp = function() {
  935. if (isDefined(csp.isActive_)) return csp.isActive_;
  936. var active = !!(document.querySelector('[ng-csp]') ||
  937. document.querySelector('[data-ng-csp]'));
  938. if (!active) {
  939. try {
  940. /* jshint -W031, -W054 */
  941. new Function('');
  942. /* jshint +W031, +W054 */
  943. } catch (e) {
  944. active = true;
  945. }
  946. }
  947. return (csp.isActive_ = active);
  948. };
  949. /**
  950. * @ngdoc directive
  951. * @module ng
  952. * @name ngJq
  953. *
  954. * @element ANY
  955. * @param {string=} ngJq the name of the library available under `window`
  956. * to be used for angular.element
  957. * @description
  958. * Use this directive to force the angular.element library. This should be
  959. * used to force either jqLite by leaving ng-jq blank or setting the name of
  960. * the jquery variable under window (eg. jQuery).
  961. *
  962. * Since angular looks for this directive when it is loaded (doesn't wait for the
  963. * DOMContentLoaded event), it must be placed on an element that comes before the script
  964. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  965. * others ignored.
  966. *
  967. * @example
  968. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  969. ```html
  970. <!doctype html>
  971. <html ng-app ng-jq>
  972. ...
  973. ...
  974. </html>
  975. ```
  976. * @example
  977. * This example shows how to use a jQuery based library of a different name.
  978. * The library name must be available at the top most 'window'.
  979. ```html
  980. <!doctype html>
  981. <html ng-app ng-jq="jQueryLib">
  982. ...
  983. ...
  984. </html>
  985. ```
  986. */
  987. var jq = function() {
  988. if (isDefined(jq.name_)) return jq.name_;
  989. var el;
  990. var i, ii = ngAttrPrefixes.length, prefix, name;
  991. for (i = 0; i < ii; ++i) {
  992. prefix = ngAttrPrefixes[i];
  993. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  994. name = el.getAttribute(prefix + 'jq');
  995. break;
  996. }
  997. }
  998. return (jq.name_ = name);
  999. };
  1000. function concat(array1, array2, index) {
  1001. return array1.concat(slice.call(array2, index));
  1002. }
  1003. function sliceArgs(args, startIndex) {
  1004. return slice.call(args, startIndex || 0);
  1005. }
  1006. /* jshint -W101 */
  1007. /**
  1008. * @ngdoc function
  1009. * @name angular.bind
  1010. * @module ng
  1011. * @kind function
  1012. *
  1013. * @description
  1014. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1015. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1016. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1017. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1018. *
  1019. * @param {Object} self Context which `fn` should be evaluated in.
  1020. * @param {function()} fn Function to be bound.
  1021. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1022. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1023. */
  1024. /* jshint +W101 */
  1025. function bind(self, fn) {
  1026. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1027. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1028. return curryArgs.length
  1029. ? function() {
  1030. return arguments.length
  1031. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1032. : fn.apply(self, curryArgs);
  1033. }
  1034. : function() {
  1035. return arguments.length
  1036. ? fn.apply(self, arguments)
  1037. : fn.call(self);
  1038. };
  1039. } else {
  1040. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  1041. return fn;
  1042. }
  1043. }
  1044. function toJsonReplacer(key, value) {
  1045. var val = value;
  1046. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1047. val = undefined;
  1048. } else if (isWindow(value)) {
  1049. val = '$WINDOW';
  1050. } else if (value && document === value) {
  1051. val = '$DOCUMENT';
  1052. } else if (isScope(value)) {
  1053. val = '$SCOPE';
  1054. }
  1055. return val;
  1056. }
  1057. /**
  1058. * @ngdoc function
  1059. * @name angular.toJson
  1060. * @module ng
  1061. * @kind function
  1062. *
  1063. * @description
  1064. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1065. * stripped since angular uses this notation internally.
  1066. *
  1067. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1068. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1069. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1070. * @returns {string|undefined} JSON-ified string representing `obj`.
  1071. */
  1072. function toJson(obj, pretty) {
  1073. if (typeof obj === 'undefined') return undefined;
  1074. if (!isNumber(pretty)) {
  1075. pretty = pretty ? 2 : null;
  1076. }
  1077. return JSON.stringify(obj, toJsonReplacer, pretty);
  1078. }
  1079. /**
  1080. * @ngdoc function
  1081. * @name angular.fromJson
  1082. * @module ng
  1083. * @kind function
  1084. *
  1085. * @description
  1086. * Deserializes a JSON string.
  1087. *
  1088. * @param {string} json JSON string to deserialize.
  1089. * @returns {Object|Array|string|number} Deserialized JSON string.
  1090. */
  1091. function fromJson(json) {
  1092. return isString(json)
  1093. ? JSON.parse(json)
  1094. : json;
  1095. }
  1096. function timezoneToOffset(timezone, fallback) {
  1097. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1098. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1099. }
  1100. function addDateMinutes(date, minutes) {
  1101. date = new Date(date.getTime());
  1102. date.setMinutes(date.getMinutes() + minutes);
  1103. return date;
  1104. }
  1105. function convertTimezoneToLocal(date, timezone, reverse) {
  1106. reverse = reverse ? -1 : 1;
  1107. var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  1108. return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
  1109. }
  1110. /**
  1111. * @returns {string} Returns the string representation of the element.
  1112. */
  1113. function startingTag(element) {
  1114. element = jqLite(element).clone();
  1115. try {
  1116. // turns out IE does not let you set .html() on elements which
  1117. // are not allowed to have children. So we just ignore it.
  1118. element.empty();
  1119. } catch (e) {}
  1120. var elemHtml = jqLite('<div>').append(element).html();
  1121. try {
  1122. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1123. elemHtml.
  1124. match(/^(<[^>]+>)/)[1].
  1125. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1126. } catch (e) {
  1127. return lowercase(elemHtml);
  1128. }
  1129. }
  1130. /////////////////////////////////////////////////
  1131. /**
  1132. * Tries to decode the URI component without throwing an exception.
  1133. *
  1134. * @private
  1135. * @param str value potential URI component to check.
  1136. * @returns {boolean} True if `value` can be decoded
  1137. * with the decodeURIComponent function.
  1138. */
  1139. function tryDecodeURIComponent(value) {
  1140. try {
  1141. return decodeURIComponent(value);
  1142. } catch (e) {
  1143. // Ignore any invalid uri component
  1144. }
  1145. }
  1146. /**
  1147. * Parses an escaped url query string into key-value pairs.
  1148. * @returns {Object.<string,boolean|Array>}
  1149. */
  1150. function parseKeyValue(/**string*/keyValue) {
  1151. var obj = {}, key_value, key;
  1152. forEach((keyValue || "").split('&'), function(keyValue) {
  1153. if (keyValue) {
  1154. key_value = keyValue.replace(/\+/g,'%20').split('=');
  1155. key = tryDecodeURIComponent(key_value[0]);
  1156. if (isDefined(key)) {
  1157. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1158. if (!hasOwnProperty.call(obj, key)) {
  1159. obj[key] = val;
  1160. } else if (isArray(obj[key])) {
  1161. obj[key].push(val);
  1162. } else {
  1163. obj[key] = [obj[key],val];
  1164. }
  1165. }
  1166. }
  1167. });
  1168. return obj;
  1169. }
  1170. function toKeyValue(obj) {
  1171. var parts = [];
  1172. forEach(obj, function(value, key) {
  1173. if (isArray(value)) {
  1174. forEach(value, function(arrayValue) {
  1175. parts.push(encodeUriQuery(key, true) +
  1176. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1177. });
  1178. } else {
  1179. parts.push(encodeUriQuery(key, true) +
  1180. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1181. }
  1182. });
  1183. return parts.length ? parts.join('&') : '';
  1184. }
  1185. /**
  1186. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1187. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1188. * segments:
  1189. * segment = *pchar
  1190. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1191. * pct-encoded = "%" HEXDIG HEXDIG
  1192. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1193. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1194. * / "*" / "+" / "," / ";" / "="
  1195. */
  1196. function encodeUriSegment(val) {
  1197. return encodeUriQuery(val, true).
  1198. replace(/%26/gi, '&').
  1199. replace(/%3D/gi, '=').
  1200. replace(/%2B/gi, '+');
  1201. }
  1202. /**
  1203. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1204. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1205. * encoded per http://tools.ietf.org/html/rfc3986:
  1206. * query = *( pchar / "/" / "?" )
  1207. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1208. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1209. * pct-encoded = "%" HEXDIG HEXDIG
  1210. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1211. * / "*" / "+" / "," / ";" / "="
  1212. */
  1213. function encodeUriQuery(val, pctEncodeSpaces) {
  1214. return encodeURIComponent(val).
  1215. replace(/%40/gi, '@').
  1216. replace(/%3A/gi, ':').
  1217. replace(/%24/g, '$').
  1218. replace(/%2C/gi, ',').
  1219. replace(/%3B/gi, ';').
  1220. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1221. }
  1222. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1223. function getNgAttribute(element, ngAttr) {
  1224. var attr, i, ii = ngAttrPrefixes.length;
  1225. for (i = 0; i < ii; ++i) {
  1226. attr = ngAttrPrefixes[i] + ngAttr;
  1227. if (isString(attr = element.getAttribute(attr))) {
  1228. return attr;
  1229. }
  1230. }
  1231. return null;
  1232. }
  1233. /**
  1234. * @ngdoc directive
  1235. * @name ngApp
  1236. * @module ng
  1237. *
  1238. * @element ANY
  1239. * @param {angular.Module} ngApp an optional application
  1240. * {@link angular.module module} name to load.
  1241. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1242. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1243. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1244. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1245. * tracking down the root of these bugs.
  1246. *
  1247. * @description
  1248. *
  1249. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1250. * designates the **root element** of the application and is typically placed near the root element
  1251. * of the page - e.g. on the `<body>` or `<html>` tags.
  1252. *
  1253. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1254. * found in the document will be used to define the root element to auto-bootstrap as an
  1255. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1256. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1257. *
  1258. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1259. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1260. * should contain the application code needed or have dependencies on other modules that will
  1261. * contain the code. See {@link angular.module} for more information.
  1262. *
  1263. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1264. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1265. * would not be resolved to `3`.
  1266. *
  1267. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1268. *
  1269. <example module="ngAppDemo">
  1270. <file name="index.html">
  1271. <div ng-controller="ngAppDemoController">
  1272. I can add: {{a}} + {{b}} = {{ a+b }}
  1273. </div>
  1274. </file>
  1275. <file name="script.js">
  1276. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1277. $scope.a = 1;
  1278. $scope.b = 2;
  1279. });
  1280. </file>
  1281. </example>
  1282. *
  1283. * Using `ngStrictDi`, you would see something like this:
  1284. *
  1285. <example ng-app-included="true">
  1286. <file name="index.html">
  1287. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1288. <div ng-controller="GoodController1">
  1289. I can add: {{a}} + {{b}} = {{ a+b }}
  1290. <p>This renders because the controller does not fail to
  1291. instantiate, by using explicit annotation style (see
  1292. script.js for details)
  1293. </p>
  1294. </div>
  1295. <div ng-controller="GoodController2">
  1296. Name: <input ng-model="name"><br />
  1297. Hello, {{name}}!
  1298. <p>This renders because the controller does not fail to
  1299. instantiate, by using explicit annotation style
  1300. (see script.js for details)
  1301. </p>
  1302. </div>
  1303. <div ng-controller="BadController">
  1304. I can add: {{a}} + {{b}} = {{ a+b }}
  1305. <p>The controller could not be instantiated, due to relying
  1306. on automatic function annotations (which are disabled in
  1307. strict mode). As such, the content of this section is not
  1308. interpolated, and there should be an error in your web console.
  1309. </p>
  1310. </div>
  1311. </div>
  1312. </file>
  1313. <file name="script.js">
  1314. angular.module('ngAppStrictDemo', [])
  1315. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1316. // rather than an explicit annotation
  1317. .controller('BadController', function($scope) {
  1318. $scope.a = 1;
  1319. $scope.b = 2;
  1320. })
  1321. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1322. // due to using explicit annotations using the array style and $inject property, respectively.
  1323. .controller('GoodController1', ['$scope', function($scope) {
  1324. $scope.a = 1;
  1325. $scope.b = 2;
  1326. }])
  1327. .controller('GoodController2', GoodController2);
  1328. function GoodController2($scope) {
  1329. $scope.name = "World";
  1330. }
  1331. GoodController2.$inject = ['$scope'];
  1332. </file>
  1333. <file name="style.css">
  1334. div[ng-controller] {
  1335. margin-bottom: 1em;
  1336. -webkit-border-radius: 4px;
  1337. border-radius: 4px;
  1338. border: 1px solid;
  1339. padding: .5em;
  1340. }
  1341. div[ng-controller^=Good] {
  1342. border-color: #d6e9c6;
  1343. background-color: #dff0d8;
  1344. color: #3c763d;
  1345. }
  1346. div[ng-controller^=Bad] {
  1347. border-color: #ebccd1;
  1348. background-color: #f2dede;
  1349. color: #a94442;
  1350. margin-bottom: 0;
  1351. }
  1352. </file>
  1353. </example>
  1354. */
  1355. function angularInit(element, bootstrap) {
  1356. var appElement,
  1357. module,
  1358. config = {};
  1359. // The element `element` has priority over any other element
  1360. forEach(ngAttrPrefixes, function(prefix) {
  1361. var name = prefix + 'app';
  1362. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1363. appElement = element;
  1364. module = element.getAttribute(name);
  1365. }
  1366. });
  1367. forEach(ngAttrPrefixes, function(prefix) {
  1368. var name = prefix + 'app';
  1369. var candidate;
  1370. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1371. appElement = candidate;
  1372. module = candidate.getAttribute(name);
  1373. }
  1374. });
  1375. if (appElement) {
  1376. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1377. bootstrap(appElement, module ? [module] : [], config);
  1378. }
  1379. }
  1380. /**
  1381. * @ngdoc function
  1382. * @name angular.bootstrap
  1383. * @module ng
  1384. * @description
  1385. * Use this function to manually start up angular application.
  1386. *
  1387. * See: {@link guide/bootstrap Bootstrap}
  1388. *
  1389. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1390. * They must use {@link ng.directive:ngApp ngApp}.
  1391. *
  1392. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1393. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1394. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1395. * multiple instances of Angular try to work on the DOM.
  1396. *
  1397. * ```html
  1398. * <!doctype html>
  1399. * <html>
  1400. * <body>
  1401. * <div ng-controller="WelcomeController">
  1402. * {{greeting}}
  1403. * </div>
  1404. *
  1405. * <script src="angular.js"></script>
  1406. * <script>
  1407. * var app = angular.module('demo', [])
  1408. * .controller('WelcomeController', function($scope) {
  1409. * $scope.greeting = 'Welcome!';
  1410. * });
  1411. * angular.bootstrap(document, ['demo']);
  1412. * </script>
  1413. * </body>
  1414. * </html>
  1415. * ```
  1416. *
  1417. * @param {DOMElement} element DOM element which is the root of angular application.
  1418. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1419. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1420. * function that will be invoked by the injector as a `config` block.
  1421. * See: {@link angular.module modules}
  1422. * @param {Object=} config an object for defining configuration options for the application. The
  1423. * following keys are supported:
  1424. *
  1425. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1426. * assist in finding bugs which break minified code. Defaults to `false`.
  1427. *
  1428. * @returns {auto.$injector} Returns the newly created injector for this app.
  1429. */
  1430. function bootstrap(element, modules, config) {
  1431. if (!isObject(config)) config = {};
  1432. var defaultConfig = {
  1433. strictDi: false
  1434. };
  1435. config = extend(defaultConfig, config);
  1436. var doBootstrap = function() {
  1437. element = jqLite(element);
  1438. if (element.injector()) {
  1439. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1440. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1441. throw ngMinErr(
  1442. 'btstrpd',
  1443. "App Already Bootstrapped with this Element '{0}'",
  1444. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1445. }
  1446. modules = modules || [];
  1447. modules.unshift(['$provide', function($provide) {
  1448. $provide.value('$rootElement', element);
  1449. }]);
  1450. if (config.debugInfoEnabled) {
  1451. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1452. modules.push(['$compileProvider', function($compileProvider) {
  1453. $compileProvider.debugInfoEnabled(true);
  1454. }]);
  1455. }
  1456. modules.unshift('ng');
  1457. var injector = createInjector(modules, config.strictDi);
  1458. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1459. function bootstrapApply(scope, element, compile, injector) {
  1460. scope.$apply(function() {
  1461. element.data('$injector', injector);
  1462. compile(element)(scope);
  1463. });
  1464. }]
  1465. );
  1466. return injector;
  1467. };
  1468. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1469. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1470. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1471. config.debugInfoEnabled = true;
  1472. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1473. }
  1474. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1475. return doBootstrap();
  1476. }
  1477. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1478. angular.resumeBootstrap = function(extraModules) {
  1479. forEach(extraModules, function(module) {
  1480. modules.push(module);
  1481. });
  1482. return doBootstrap();
  1483. };
  1484. if (isFunction(angular.resumeDeferredBootstrap)) {
  1485. angular.resumeDeferredBootstrap();
  1486. }
  1487. }
  1488. /**
  1489. * @ngdoc function
  1490. * @name angular.reloadWithDebugInfo
  1491. * @module ng
  1492. * @description
  1493. * Use this function to reload the current application with debug information turned on.
  1494. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1495. *
  1496. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1497. */
  1498. function reloadWithDebugInfo() {
  1499. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1500. window.location.reload();
  1501. }
  1502. /**
  1503. * @name angular.getTestability
  1504. * @module ng
  1505. * @description
  1506. * Get the testability service for the instance of Angular on the given
  1507. * element.
  1508. * @param {DOMElement} element DOM element which is the root of angular application.
  1509. */
  1510. function getTestability(rootElement) {
  1511. var injector = angular.element(rootElement).injector();
  1512. if (!injector) {
  1513. throw ngMinErr('test',
  1514. 'no injector found for element argument to getTestability');
  1515. }
  1516. return injector.get('$$testability');
  1517. }
  1518. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1519. function snake_case(name, separator) {
  1520. separator = separator || '_';
  1521. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1522. return (pos ? separator : '') + letter.toLowerCase();
  1523. });
  1524. }
  1525. var bindJQueryFired = false;
  1526. var skipDestroyOnNextJQueryCleanData;
  1527. function bindJQuery() {
  1528. var originalCleanData;
  1529. if (bindJQueryFired) {
  1530. return;
  1531. }
  1532. // bind to jQuery if present;
  1533. var jqName = jq();
  1534. jQuery = window.jQuery; // use default jQuery.
  1535. if (isDefined(jqName)) { // `ngJq` present
  1536. jQuery = jqName === null ? undefined : window[jqName]; // if empty; use jqLite. if not empty, use jQuery specified by `ngJq`.
  1537. }
  1538. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1539. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1540. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1541. // versions. It will not work for sure with jQuery <1.7, though.
  1542. if (jQuery && jQuery.fn.on) {
  1543. jqLite = jQuery;
  1544. extend(jQuery.fn, {
  1545. scope: JQLitePrototype.scope,
  1546. isolateScope: JQLitePrototype.isolateScope,
  1547. controller: JQLitePrototype.controller,
  1548. injector: JQLitePrototype.injector,
  1549. inheritedData: JQLitePrototype.inheritedData
  1550. });
  1551. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1552. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1553. // the $destroy event on all removed nodes.
  1554. originalCleanData = jQuery.cleanData;
  1555. jQuery.cleanData = function(elems) {
  1556. var events;
  1557. if (!skipDestroyOnNextJQueryCleanData) {
  1558. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1559. events = jQuery._data(elem, "events");
  1560. if (events && events.$destroy) {
  1561. jQuery(elem).triggerHandler('$destroy');
  1562. }
  1563. }
  1564. } else {
  1565. skipDestroyOnNextJQueryCleanData = false;
  1566. }
  1567. originalCleanData(elems);
  1568. };
  1569. } else {
  1570. jqLite = JQLite;
  1571. }
  1572. angular.element = jqLite;
  1573. // Prevent double-proxying.
  1574. bindJQueryFired = true;
  1575. }
  1576. /**
  1577. * throw error if the argument is falsy.
  1578. */
  1579. function assertArg(arg, name, reason) {
  1580. if (!arg) {
  1581. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1582. }
  1583. return arg;
  1584. }
  1585. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1586. if (acceptArrayAnnotation && isArray(arg)) {
  1587. arg = arg[arg.length - 1];
  1588. }
  1589. assertArg(isFunction(arg), name, 'not a function, got ' +
  1590. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1591. return arg;
  1592. }
  1593. /**
  1594. * throw error if the name given is hasOwnProperty
  1595. * @param {String} name the name to test
  1596. * @param {String} context the context in which the name is used, such as module or directive
  1597. */
  1598. function assertNotHasOwnProperty(name, context) {
  1599. if (name === 'hasOwnProperty') {
  1600. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1601. }
  1602. }
  1603. /**
  1604. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1605. * @param {Object} obj starting object
  1606. * @param {String} path path to traverse
  1607. * @param {boolean} [bindFnToScope=true]
  1608. * @returns {Object} value as accessible by path
  1609. */
  1610. //TODO(misko): this function needs to be removed
  1611. function getter(obj, path, bindFnToScope) {
  1612. if (!path) return obj;
  1613. var keys = path.split('.');
  1614. var key;
  1615. var lastInstance = obj;
  1616. var len = keys.length;
  1617. for (var i = 0; i < len; i++) {
  1618. key = keys[i];
  1619. if (obj) {
  1620. obj = (lastInstance = obj)[key];
  1621. }
  1622. }
  1623. if (!bindFnToScope && isFunction(obj)) {
  1624. return bind(lastInstance, obj);
  1625. }
  1626. return obj;
  1627. }
  1628. /**
  1629. * Return the DOM siblings between the first and last node in the given array.
  1630. * @param {Array} array like object
  1631. * @returns {jqLite} jqLite collection containing the nodes
  1632. */
  1633. function getBlockNodes(nodes) {
  1634. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1635. // collection, otherwise update the original collection.
  1636. var node = nodes[0];
  1637. var endNode = nodes[nodes.length - 1];
  1638. var blockNodes = [node];
  1639. do {
  1640. node = node.nextSibling;
  1641. if (!node) break;
  1642. blockNodes.push(node);
  1643. } while (node !== endNode);
  1644. return jqLite(blockNodes);
  1645. }
  1646. /**
  1647. * Creates a new object without a prototype. This object is useful for lookup without having to
  1648. * guard against prototypically inherited properties via hasOwnProperty.
  1649. *
  1650. * Related micro-benchmarks:
  1651. * - http://jsperf.com/object-create2
  1652. * - http://jsperf.com/proto-map-lookup/2
  1653. * - http://jsperf.com/for-in-vs-object-keys2
  1654. *
  1655. * @returns {Object}
  1656. */
  1657. function createMap() {
  1658. return Object.create(null);
  1659. }
  1660. var NODE_TYPE_ELEMENT = 1;
  1661. var NODE_TYPE_ATTRIBUTE = 2;
  1662. var NODE_TYPE_TEXT = 3;
  1663. var NODE_TYPE_COMMENT = 8;
  1664. var NODE_TYPE_DOCUMENT = 9;
  1665. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1666. /**
  1667. * @ngdoc type
  1668. * @name angular.Module
  1669. * @module ng
  1670. * @description
  1671. *
  1672. * Interface for configuring angular {@link angular.module modules}.
  1673. */
  1674. function setupModuleLoader(window) {
  1675. var $injectorMinErr = minErr('$injector');
  1676. var ngMinErr = minErr('ng');
  1677. function ensure(obj, name, factory) {
  1678. return obj[name] || (obj[name] = factory());
  1679. }
  1680. var angular = ensure(window, 'angular', Object);
  1681. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1682. angular.$$minErr = angular.$$minErr || minErr;
  1683. return ensure(angular, 'module', function() {
  1684. /** @type {Object.<string, angular.Module>} */
  1685. var modules = {};
  1686. /**
  1687. * @ngdoc function
  1688. * @name angular.module
  1689. * @module ng
  1690. * @description
  1691. *
  1692. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1693. * modules.
  1694. * All modules (angular core or 3rd party) that should be available to an application must be
  1695. * registered using this mechanism.
  1696. *
  1697. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1698. * existing module (the name passed as the first argument to `module`) is retrieved.
  1699. *
  1700. *
  1701. * # Module
  1702. *
  1703. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1704. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1705. *
  1706. * ```js
  1707. * // Create a new module
  1708. * var myModule = angular.module('myModule', []);
  1709. *
  1710. * // register a new service
  1711. * myModule.value('appName', 'MyCoolApp');
  1712. *
  1713. * // configure existing services inside initialization blocks.
  1714. * myModule.config(['$locationProvider', function($locationProvider) {
  1715. * // Configure existing providers
  1716. * $locationProvider.hashPrefix('!');
  1717. * }]);
  1718. * ```
  1719. *
  1720. * Then you can create an injector and load your modules like this:
  1721. *
  1722. * ```js
  1723. * var injector = angular.injector(['ng', 'myModule'])
  1724. * ```
  1725. *
  1726. * However it's more likely that you'll just use
  1727. * {@link ng.directive:ngApp ngApp} or
  1728. * {@link angular.bootstrap} to simplify this process for you.
  1729. *
  1730. * @param {!string} name The name of the module to create or retrieve.
  1731. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1732. * unspecified then the module is being retrieved for further configuration.
  1733. * @param {Function=} configFn Optional configuration function for the module. Same as
  1734. * {@link angular.Module#config Module#config()}.
  1735. * @returns {module} new module with the {@link angular.Module} api.
  1736. */
  1737. return function module(name, requires, configFn) {
  1738. var assertNotHasOwnProperty = function(name, context) {
  1739. if (name === 'hasOwnProperty') {
  1740. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1741. }
  1742. };
  1743. assertNotHasOwnProperty(name, 'module');
  1744. if (requires && modules.hasOwnProperty(name)) {
  1745. modules[name] = null;
  1746. }
  1747. return ensure(modules, name, function() {
  1748. if (!requires) {
  1749. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1750. "the module name or forgot to load it. If registering a module ensure that you " +
  1751. "specify the dependencies as the second argument.", name);
  1752. }
  1753. /** @type {!Array.<Array.<*>>} */
  1754. var invokeQueue = [];
  1755. /** @type {!Array.<Function>} */
  1756. var configBlocks = [];
  1757. /** @type {!Array.<Function>} */
  1758. var runBlocks = [];
  1759. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1760. /** @type {angular.Module} */
  1761. var moduleInstance = {
  1762. // Private state
  1763. _invokeQueue: invokeQueue,
  1764. _configBlocks: configBlocks,
  1765. _runBlocks: runBlocks,
  1766. /**
  1767. * @ngdoc property
  1768. * @name angular.Module#requires
  1769. * @module ng
  1770. *
  1771. * @description
  1772. * Holds the list of modules which the injector will load before the current module is
  1773. * loaded.
  1774. */
  1775. requires: requires,
  1776. /**
  1777. * @ngdoc property
  1778. * @name angular.Module#name
  1779. * @module ng
  1780. *
  1781. * @description
  1782. * Name of the module.
  1783. */
  1784. name: name,
  1785. /**
  1786. * @ngdoc method
  1787. * @name angular.Module#provider
  1788. * @module ng
  1789. * @param {string} name service name
  1790. * @param {Function} providerType Construction function for creating new instance of the
  1791. * service.
  1792. * @description
  1793. * See {@link auto.$provide#provider $provide.provider()}.
  1794. */
  1795. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1796. /**
  1797. * @ngdoc method
  1798. * @name angular.Module#factory
  1799. * @module ng
  1800. * @param {string} name service name
  1801. * @param {Function} providerFunction Function for creating new instance of the service.
  1802. * @description
  1803. * See {@link auto.$provide#factory $provide.factory()}.
  1804. */
  1805. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1806. /**
  1807. * @ngdoc method
  1808. * @name angular.Module#service
  1809. * @module ng
  1810. * @param {string} name service name
  1811. * @param {Function} constructor A constructor function that will be instantiated.
  1812. * @description
  1813. * See {@link auto.$provide#service $provide.service()}.
  1814. */
  1815. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1816. /**
  1817. * @ngdoc method
  1818. * @name angular.Module#value
  1819. * @module ng
  1820. * @param {string} name service name
  1821. * @param {*} object Service instance object.
  1822. * @description
  1823. * See {@link auto.$provide#value $provide.value()}.
  1824. */
  1825. value: invokeLater('$provide', 'value'),
  1826. /**
  1827. * @ngdoc method
  1828. * @name angular.Module#constant
  1829. * @module ng
  1830. * @param {string} name constant name
  1831. * @param {*} object Constant value.
  1832. * @description
  1833. * Because the constant are fixed, they get applied before other provide methods.
  1834. * See {@link auto.$provide#constant $provide.constant()}.
  1835. */
  1836. constant: invokeLater('$provide', 'constant', 'unshift'),
  1837. /**
  1838. * @ngdoc method
  1839. * @name angular.Module#decorator
  1840. * @module ng
  1841. * @param {string} The name of the service to decorate.
  1842. * @param {Function} This function will be invoked when the service needs to be
  1843. * instantiated and should return the decorated service instance.
  1844. * @description
  1845. * See {@link auto.$provide#decorator $provide.decorator()}.
  1846. */
  1847. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1848. /**
  1849. * @ngdoc method
  1850. * @name angular.Module#animation
  1851. * @module ng
  1852. * @param {string} name animation name
  1853. * @param {Function} animationFactory Factory function for creating new instance of an
  1854. * animation.
  1855. * @description
  1856. *
  1857. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1858. *
  1859. *
  1860. * Defines an animation hook that can be later used with
  1861. * {@link $animate $animate} service and directives that use this service.
  1862. *
  1863. * ```js
  1864. * module.animation('.animation-name', function($inject1, $inject2) {
  1865. * return {
  1866. * eventName : function(element, done) {
  1867. * //code to run the animation
  1868. * //once complete, then run done()
  1869. * return function cancellationFunction(element) {
  1870. * //code to cancel the animation
  1871. * }
  1872. * }
  1873. * }
  1874. * })
  1875. * ```
  1876. *
  1877. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1878. * {@link ngAnimate ngAnimate module} for more information.
  1879. */
  1880. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1881. /**
  1882. * @ngdoc method
  1883. * @name angular.Module#filter
  1884. * @module ng
  1885. * @param {string} name Filter name - this must be a valid angular expression identifier
  1886. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1887. * @description
  1888. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1889. *
  1890. * <div class="alert alert-warning">
  1891. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1892. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1893. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1894. * (`myapp_subsection_filterx`).
  1895. * </div>
  1896. */
  1897. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  1898. /**
  1899. * @ngdoc method
  1900. * @name angular.Module#controller
  1901. * @module ng
  1902. * @param {string|Object} name Controller name, or an object map of controllers where the
  1903. * keys are the names and the values are the constructors.
  1904. * @param {Function} constructor Controller constructor function.
  1905. * @description
  1906. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1907. */
  1908. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  1909. /**
  1910. * @ngdoc method
  1911. * @name angular.Module#directive
  1912. * @module ng
  1913. * @param {string|Object} name Directive name, or an object map of directives where the
  1914. * keys are the names and the values are the factories.
  1915. * @param {Function} directiveFactory Factory function for creating new instance of
  1916. * directives.
  1917. * @description
  1918. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1919. */
  1920. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  1921. /**
  1922. * @ngdoc method
  1923. * @name angular.Module#config
  1924. * @module ng
  1925. * @param {Function} configFn Execute this function on module load. Useful for service
  1926. * configuration.
  1927. * @description
  1928. * Use this method to register work which needs to be performed on module loading.
  1929. * For more about how to configure services, see
  1930. * {@link providers#provider-recipe Provider Recipe}.
  1931. */
  1932. config: config,
  1933. /**
  1934. * @ngdoc method
  1935. * @name angular.Module#run
  1936. * @module ng
  1937. * @param {Function} initializationFn Execute this function after injector creation.
  1938. * Useful for application initialization.
  1939. * @description
  1940. * Use this method to register work which should be performed when the injector is done
  1941. * loading all modules.
  1942. */
  1943. run: function(block) {
  1944. runBlocks.push(block);
  1945. return this;
  1946. }
  1947. };
  1948. if (configFn) {
  1949. config(configFn);
  1950. }
  1951. return moduleInstance;
  1952. /**
  1953. * @param {string} provider
  1954. * @param {string} method
  1955. * @param {String=} insertMethod
  1956. * @returns {angular.Module}
  1957. */
  1958. function invokeLater(provider, method, insertMethod, queue) {
  1959. if (!queue) queue = invokeQueue;
  1960. return function() {
  1961. queue[insertMethod || 'push']([provider, method, arguments]);
  1962. return moduleInstance;
  1963. };
  1964. }
  1965. /**
  1966. * @param {string} provider
  1967. * @param {string} method
  1968. * @returns {angular.Module}
  1969. */
  1970. function invokeLaterAndSetModuleName(provider, method) {
  1971. return function(recipeName, factoryFunction) {
  1972. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  1973. invokeQueue.push([provider, method, arguments]);
  1974. return moduleInstance;
  1975. };
  1976. }
  1977. });
  1978. };
  1979. });
  1980. }
  1981. /* global: toDebugString: true */
  1982. function serializeObject(obj) {
  1983. var seen = [];
  1984. return JSON.stringify(obj, function(key, val) {
  1985. val = toJsonReplacer(key, val);
  1986. if (isObject(val)) {
  1987. if (seen.indexOf(val) >= 0) return '<<already seen>>';
  1988. seen.push(val);
  1989. }
  1990. return val;
  1991. });
  1992. }
  1993. function toDebugString(obj) {
  1994. if (typeof obj === 'function') {
  1995. return obj.toString().replace(/ \{[\s\S]*$/, '');
  1996. } else if (typeof obj === 'undefined') {
  1997. return 'undefined';
  1998. } else if (typeof obj !== 'string') {
  1999. return serializeObject(obj);
  2000. }
  2001. return obj;
  2002. }
  2003. /* global angularModule: true,
  2004. version: true,
  2005. $LocaleProvider,
  2006. $CompileProvider,
  2007. htmlAnchorDirective,
  2008. inputDirective,
  2009. inputDirective,
  2010. formDirective,
  2011. scriptDirective,
  2012. selectDirective,
  2013. styleDirective,
  2014. optionDirective,
  2015. ngBindDirective,
  2016. ngBindHtmlDirective,
  2017. ngBindTemplateDirective,
  2018. ngClassDirective,
  2019. ngClassEvenDirective,
  2020. ngClassOddDirective,
  2021. ngCspDirective,
  2022. ngCloakDirective,
  2023. ngControllerDirective,
  2024. ngFormDirective,
  2025. ngHideDirective,
  2026. ngIfDirective,
  2027. ngIncludeDirective,
  2028. ngIncludeFillContentDirective,
  2029. ngInitDirective,
  2030. ngNonBindableDirective,
  2031. ngPluralizeDirective,
  2032. ngRepeatDirective,
  2033. ngShowDirective,
  2034. ngStyleDirective,
  2035. ngSwitchDirective,
  2036. ngSwitchWhenDirective,
  2037. ngSwitchDefaultDirective,
  2038. ngOptionsDirective,
  2039. ngTranscludeDirective,
  2040. ngModelDirective,
  2041. ngListDirective,
  2042. ngChangeDirective,
  2043. patternDirective,
  2044. patternDirective,
  2045. requiredDirective,
  2046. requiredDirective,
  2047. minlengthDirective,
  2048. minlengthDirective,
  2049. maxlengthDirective,
  2050. maxlengthDirective,
  2051. ngValueDirective,
  2052. ngModelOptionsDirective,
  2053. ngAttributeAliasDirectives,
  2054. ngEventDirectives,
  2055. $AnchorScrollProvider,
  2056. $AnimateProvider,
  2057. $$CoreAnimateQueueProvider,
  2058. $$CoreAnimateRunnerProvider,
  2059. $BrowserProvider,
  2060. $CacheFactoryProvider,
  2061. $ControllerProvider,
  2062. $DocumentProvider,
  2063. $ExceptionHandlerProvider,
  2064. $FilterProvider,
  2065. $InterpolateProvider,
  2066. $IntervalProvider,
  2067. $$HashMapProvider,
  2068. $HttpProvider,
  2069. $HttpParamSerializerProvider,
  2070. $HttpParamSerializerJQLikeProvider,
  2071. $HttpBackendProvider,
  2072. $LocationProvider,
  2073. $LogProvider,
  2074. $ParseProvider,
  2075. $RootScopeProvider,
  2076. $QProvider,
  2077. $$QProvider,
  2078. $$SanitizeUriProvider,
  2079. $SceProvider,
  2080. $SceDelegateProvider,
  2081. $SnifferProvider,
  2082. $TemplateCacheProvider,
  2083. $TemplateRequestProvider,
  2084. $$TestabilityProvider,
  2085. $TimeoutProvider,
  2086. $$RAFProvider,
  2087. $WindowProvider,
  2088. $$jqLiteProvider,
  2089. $$CookieReaderProvider
  2090. */
  2091. /**
  2092. * @ngdoc object
  2093. * @name angular.version
  2094. * @module ng
  2095. * @description
  2096. * An object that contains information about the current AngularJS version. This object has the
  2097. * following properties:
  2098. *
  2099. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2100. * - `major` – `{number}` – Major version number, such as "0".
  2101. * - `minor` – `{number}` – Minor version number, such as "9".
  2102. * - `dot` – `{number}` – Dot version number, such as "18".
  2103. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2104. */
  2105. var version = {
  2106. full: '1.4.3', // all of these placeholder strings will be replaced by grunt's
  2107. major: 1, // package task
  2108. minor: 4,
  2109. dot: 3,
  2110. codeName: 'foam-acceleration'
  2111. };
  2112. function publishExternalAPI(angular) {
  2113. extend(angular, {
  2114. 'bootstrap': bootstrap,
  2115. 'copy': copy,
  2116. 'extend': extend,
  2117. 'merge': merge,
  2118. 'equals': equals,
  2119. 'element': jqLite,
  2120. 'forEach': forEach,
  2121. 'injector': createInjector,
  2122. 'noop': noop,
  2123. 'bind': bind,
  2124. 'toJson': toJson,
  2125. 'fromJson': fromJson,
  2126. 'identity': identity,
  2127. 'isUndefined': isUndefined,
  2128. 'isDefined': isDefined,
  2129. 'isString': isString,
  2130. 'isFunction': isFunction,
  2131. 'isObject': isObject,
  2132. 'isNumber': isNumber,
  2133. 'isElement': isElement,
  2134. 'isArray': isArray,
  2135. 'version': version,
  2136. 'isDate': isDate,
  2137. 'lowercase': lowercase,
  2138. 'uppercase': uppercase,
  2139. 'callbacks': {counter: 0},
  2140. 'getTestability': getTestability,
  2141. '$$minErr': minErr,
  2142. '$$csp': csp,
  2143. 'reloadWithDebugInfo': reloadWithDebugInfo
  2144. });
  2145. angularModule = setupModuleLoader(window);
  2146. try {
  2147. angularModule('ngLocale');
  2148. } catch (e) {
  2149. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  2150. }
  2151. angularModule('ng', ['ngLocale'], ['$provide',
  2152. function ngModule($provide) {
  2153. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2154. $provide.provider({
  2155. $$sanitizeUri: $$SanitizeUriProvider
  2156. });
  2157. $provide.provider('$compile', $CompileProvider).
  2158. directive({
  2159. a: htmlAnchorDirective,
  2160. input: inputDirective,
  2161. textarea: inputDirective,
  2162. form: formDirective,
  2163. script: scriptDirective,
  2164. select: selectDirective,
  2165. style: styleDirective,
  2166. option: optionDirective,
  2167. ngBind: ngBindDirective,
  2168. ngBindHtml: ngBindHtmlDirective,
  2169. ngBindTemplate: ngBindTemplateDirective,
  2170. ngClass: ngClassDirective,
  2171. ngClassEven: ngClassEvenDirective,
  2172. ngClassOdd: ngClassOddDirective,
  2173. ngCloak: ngCloakDirective,
  2174. ngController: ngControllerDirective,
  2175. ngForm: ngFormDirective,
  2176. ngHide: ngHideDirective,
  2177. ngIf: ngIfDirective,
  2178. ngInclude: ngIncludeDirective,
  2179. ngInit: ngInitDirective,
  2180. ngNonBindable: ngNonBindableDirective,
  2181. ngPluralize: ngPluralizeDirective,
  2182. ngRepeat: ngRepeatDirective,
  2183. ngShow: ngShowDirective,
  2184. ngStyle: ngStyleDirective,
  2185. ngSwitch: ngSwitchDirective,
  2186. ngSwitchWhen: ngSwitchWhenDirective,
  2187. ngSwitchDefault: ngSwitchDefaultDirective,
  2188. ngOptions: ngOptionsDirective,
  2189. ngTransclude: ngTranscludeDirective,
  2190. ngModel: ngModelDirective,
  2191. ngList: ngListDirective,
  2192. ngChange: ngChangeDirective,
  2193. pattern: patternDirective,
  2194. ngPattern: patternDirective,
  2195. required: requiredDirective,
  2196. ngRequired: requiredDirective,
  2197. minlength: minlengthDirective,
  2198. ngMinlength: minlengthDirective,
  2199. maxlength: maxlengthDirective,
  2200. ngMaxlength: maxlengthDirective,
  2201. ngValue: ngValueDirective,
  2202. ngModelOptions: ngModelOptionsDirective
  2203. }).
  2204. directive({
  2205. ngInclude: ngIncludeFillContentDirective
  2206. }).
  2207. directive(ngAttributeAliasDirectives).
  2208. directive(ngEventDirectives);
  2209. $provide.provider({
  2210. $anchorScroll: $AnchorScrollProvider,
  2211. $animate: $AnimateProvider,
  2212. $$animateQueue: $$CoreAnimateQueueProvider,
  2213. $$AnimateRunner: $$CoreAnimateRunnerProvider,
  2214. $browser: $BrowserProvider,
  2215. $cacheFactory: $CacheFactoryProvider,
  2216. $controller: $ControllerProvider,
  2217. $document: $DocumentProvider,
  2218. $exceptionHandler: $ExceptionHandlerProvider,
  2219. $filter: $FilterProvider,
  2220. $interpolate: $InterpolateProvider,
  2221. $interval: $IntervalProvider,
  2222. $http: $HttpProvider,
  2223. $httpParamSerializer: $HttpParamSerializerProvider,
  2224. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2225. $httpBackend: $HttpBackendProvider,
  2226. $location: $LocationProvider,
  2227. $log: $LogProvider,
  2228. $parse: $ParseProvider,
  2229. $rootScope: $RootScopeProvider,
  2230. $q: $QProvider,
  2231. $$q: $$QProvider,
  2232. $sce: $SceProvider,
  2233. $sceDelegate: $SceDelegateProvider,
  2234. $sniffer: $SnifferProvider,
  2235. $templateCache: $TemplateCacheProvider,
  2236. $templateRequest: $TemplateRequestProvider,
  2237. $$testability: $$TestabilityProvider,
  2238. $timeout: $TimeoutProvider,
  2239. $window: $WindowProvider,
  2240. $$rAF: $$RAFProvider,
  2241. $$jqLite: $$jqLiteProvider,
  2242. $$HashMap: $$HashMapProvider,
  2243. $$cookieReader: $$CookieReaderProvider
  2244. });
  2245. }
  2246. ]);
  2247. }
  2248. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2249. * Any commits to this file should be reviewed with security in mind. *
  2250. * Changes to this file can potentially create security vulnerabilities. *
  2251. * An approval from 2 Core members with history of modifying *
  2252. * this file is required. *
  2253. * *
  2254. * Does the change somehow allow for arbitrary javascript to be executed? *
  2255. * Or allows for someone to change the prototype of built-in objects? *
  2256. * Or gives undesired access to variables likes document or window? *
  2257. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2258. /* global JQLitePrototype: true,
  2259. addEventListenerFn: true,
  2260. removeEventListenerFn: true,
  2261. BOOLEAN_ATTR: true,
  2262. ALIASED_ATTR: true,
  2263. */
  2264. //////////////////////////////////
  2265. //JQLite
  2266. //////////////////////////////////
  2267. /**
  2268. * @ngdoc function
  2269. * @name angular.element
  2270. * @module ng
  2271. * @kind function
  2272. *
  2273. * @description
  2274. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2275. *
  2276. * If jQuery is available, `angular.element` is an alias for the
  2277. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2278. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2279. *
  2280. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2281. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2282. * commonly needed functionality with the goal of having a very small footprint.</div>
  2283. *
  2284. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
  2285. *
  2286. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2287. * jqLite; they are never raw DOM references.</div>
  2288. *
  2289. * ## Angular's jqLite
  2290. * jqLite provides only the following jQuery methods:
  2291. *
  2292. * - [`addClass()`](http://api.jquery.com/addClass/)
  2293. * - [`after()`](http://api.jquery.com/after/)
  2294. * - [`append()`](http://api.jquery.com/append/)
  2295. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2296. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2297. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2298. * - [`clone()`](http://api.jquery.com/clone/)
  2299. * - [`contents()`](http://api.jquery.com/contents/)
  2300. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
  2301. * - [`data()`](http://api.jquery.com/data/)
  2302. * - [`detach()`](http://api.jquery.com/detach/)
  2303. * - [`empty()`](http://api.jquery.com/empty/)
  2304. * - [`eq()`](http://api.jquery.com/eq/)
  2305. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2306. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2307. * - [`html()`](http://api.jquery.com/html/)
  2308. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2309. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2310. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2311. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2312. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2313. * - [`prepend()`](http://api.jquery.com/prepend/)
  2314. * - [`prop()`](http://api.jquery.com/prop/)
  2315. * - [`ready()`](http://api.jquery.com/ready/)
  2316. * - [`remove()`](http://api.jquery.com/remove/)
  2317. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2318. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2319. * - [`removeData()`](http://api.jquery.com/removeData/)
  2320. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2321. * - [`text()`](http://api.jquery.com/text/)
  2322. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2323. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2324. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2325. * - [`val()`](http://api.jquery.com/val/)
  2326. * - [`wrap()`](http://api.jquery.com/wrap/)
  2327. *
  2328. * ## jQuery/jqLite Extras
  2329. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2330. *
  2331. * ### Events
  2332. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2333. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2334. * element before it is removed.
  2335. *
  2336. * ### Methods
  2337. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2338. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2339. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2340. * `'ngModel'`).
  2341. * - `injector()` - retrieves the injector of the current element or its parent.
  2342. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2343. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2344. * be enabled.
  2345. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2346. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2347. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2348. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2349. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2350. * parent element is reached.
  2351. *
  2352. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2353. * @returns {Object} jQuery object.
  2354. */
  2355. JQLite.expando = 'ng339';
  2356. var jqCache = JQLite.cache = {},
  2357. jqId = 1,
  2358. addEventListenerFn = function(element, type, fn) {
  2359. element.addEventListener(type, fn, false);
  2360. },
  2361. removeEventListenerFn = function(element, type, fn) {
  2362. element.removeEventListener(type, fn, false);
  2363. };
  2364. /*
  2365. * !!! This is an undocumented "private" function !!!
  2366. */
  2367. JQLite._data = function(node) {
  2368. //jQuery always returns an object on cache miss
  2369. return this.cache[node[this.expando]] || {};
  2370. };
  2371. function jqNextId() { return ++jqId; }
  2372. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2373. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2374. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2375. var jqLiteMinErr = minErr('jqLite');
  2376. /**
  2377. * Converts snake_case to camelCase.
  2378. * Also there is special case for Moz prefix starting with upper case letter.
  2379. * @param name Name to normalize
  2380. */
  2381. function camelCase(name) {
  2382. return name.
  2383. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2384. return offset ? letter.toUpperCase() : letter;
  2385. }).
  2386. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2387. }
  2388. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2389. var HTML_REGEXP = /<|&#?\w+;/;
  2390. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2391. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2392. var wrapMap = {
  2393. 'option': [1, '<select multiple="multiple">', '</select>'],
  2394. 'thead': [1, '<table>', '</table>'],
  2395. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2396. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2397. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2398. '_default': [0, "", ""]
  2399. };
  2400. wrapMap.optgroup = wrapMap.option;
  2401. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2402. wrapMap.th = wrapMap.td;
  2403. function jqLiteIsTextNode(html) {
  2404. return !HTML_REGEXP.test(html);
  2405. }
  2406. function jqLiteAcceptsData(node) {
  2407. // The window object can accept data but has no nodeType
  2408. // Otherwise we are only interested in elements (1) and documents (9)
  2409. var nodeType = node.nodeType;
  2410. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2411. }
  2412. function jqLiteHasData(node) {
  2413. for (var key in jqCache[node.ng339]) {
  2414. return true;
  2415. }
  2416. return false;
  2417. }
  2418. function jqLiteBuildFragment(html, context) {
  2419. var tmp, tag, wrap,
  2420. fragment = context.createDocumentFragment(),
  2421. nodes = [], i;
  2422. if (jqLiteIsTextNode(html)) {
  2423. // Convert non-html into a text node
  2424. nodes.push(context.createTextNode(html));
  2425. } else {
  2426. // Convert html into DOM nodes
  2427. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2428. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2429. wrap = wrapMap[tag] || wrapMap._default;
  2430. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2431. // Descend through wrappers to the right content
  2432. i = wrap[0];
  2433. while (i--) {
  2434. tmp = tmp.lastChild;
  2435. }
  2436. nodes = concat(nodes, tmp.childNodes);
  2437. tmp = fragment.firstChild;
  2438. tmp.textContent = "";
  2439. }
  2440. // Remove wrapper from fragment
  2441. fragment.textContent = "";
  2442. fragment.innerHTML = ""; // Clear inner HTML
  2443. forEach(nodes, function(node) {
  2444. fragment.appendChild(node);
  2445. });
  2446. return fragment;
  2447. }
  2448. function jqLiteParseHTML(html, context) {
  2449. context = context || document;
  2450. var parsed;
  2451. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2452. return [context.createElement(parsed[1])];
  2453. }
  2454. if ((parsed = jqLiteBuildFragment(html, context))) {
  2455. return parsed.childNodes;
  2456. }
  2457. return [];
  2458. }
  2459. /////////////////////////////////////////////
  2460. function JQLite(element) {
  2461. if (element instanceof JQLite) {
  2462. return element;
  2463. }
  2464. var argIsString;
  2465. if (isString(element)) {
  2466. element = trim(element);
  2467. argIsString = true;
  2468. }
  2469. if (!(this instanceof JQLite)) {
  2470. if (argIsString && element.charAt(0) != '<') {
  2471. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2472. }
  2473. return new JQLite(element);
  2474. }
  2475. if (argIsString) {
  2476. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2477. } else {
  2478. jqLiteAddNodes(this, element);
  2479. }
  2480. }
  2481. function jqLiteClone(element) {
  2482. return element.cloneNode(true);
  2483. }
  2484. function jqLiteDealoc(element, onlyDescendants) {
  2485. if (!onlyDescendants) jqLiteRemoveData(element);
  2486. if (element.querySelectorAll) {
  2487. var descendants = element.querySelectorAll('*');
  2488. for (var i = 0, l = descendants.length; i < l; i++) {
  2489. jqLiteRemoveData(descendants[i]);
  2490. }
  2491. }
  2492. }
  2493. function jqLiteOff(element, type, fn, unsupported) {
  2494. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2495. var expandoStore = jqLiteExpandoStore(element);
  2496. var events = expandoStore && expandoStore.events;
  2497. var handle = expandoStore && expandoStore.handle;
  2498. if (!handle) return; //no listeners registered
  2499. if (!type) {
  2500. for (type in events) {
  2501. if (type !== '$destroy') {
  2502. removeEventListenerFn(element, type, handle);
  2503. }
  2504. delete events[type];
  2505. }
  2506. } else {
  2507. forEach(type.split(' '), function(type) {
  2508. if (isDefined(fn)) {
  2509. var listenerFns = events[type];
  2510. arrayRemove(listenerFns || [], fn);
  2511. if (listenerFns && listenerFns.length > 0) {
  2512. return;
  2513. }
  2514. }
  2515. removeEventListenerFn(element, type, handle);
  2516. delete events[type];
  2517. });
  2518. }
  2519. }
  2520. function jqLiteRemoveData(element, name) {
  2521. var expandoId = element.ng339;
  2522. var expandoStore = expandoId && jqCache[expandoId];
  2523. if (expandoStore) {
  2524. if (name) {
  2525. delete expandoStore.data[name];
  2526. return;
  2527. }
  2528. if (expandoStore.handle) {
  2529. if (expandoStore.events.$destroy) {
  2530. expandoStore.handle({}, '$destroy');
  2531. }
  2532. jqLiteOff(element);
  2533. }
  2534. delete jqCache[expandoId];
  2535. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2536. }
  2537. }
  2538. function jqLiteExpandoStore(element, createIfNecessary) {
  2539. var expandoId = element.ng339,
  2540. expandoStore = expandoId && jqCache[expandoId];
  2541. if (createIfNecessary && !expandoStore) {
  2542. element.ng339 = expandoId = jqNextId();
  2543. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2544. }
  2545. return expandoStore;
  2546. }
  2547. function jqLiteData(element, key, value) {
  2548. if (jqLiteAcceptsData(element)) {
  2549. var isSimpleSetter = isDefined(value);
  2550. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2551. var massGetter = !key;
  2552. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2553. var data = expandoStore && expandoStore.data;
  2554. if (isSimpleSetter) { // data('key', value)
  2555. data[key] = value;
  2556. } else {
  2557. if (massGetter) { // data()
  2558. return data;
  2559. } else {
  2560. if (isSimpleGetter) { // data('key')
  2561. // don't force creation of expandoStore if it doesn't exist yet
  2562. return data && data[key];
  2563. } else { // mass-setter: data({key1: val1, key2: val2})
  2564. extend(data, key);
  2565. }
  2566. }
  2567. }
  2568. }
  2569. }
  2570. function jqLiteHasClass(element, selector) {
  2571. if (!element.getAttribute) return false;
  2572. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2573. indexOf(" " + selector + " ") > -1);
  2574. }
  2575. function jqLiteRemoveClass(element, cssClasses) {
  2576. if (cssClasses && element.setAttribute) {
  2577. forEach(cssClasses.split(' '), function(cssClass) {
  2578. element.setAttribute('class', trim(
  2579. (" " + (element.getAttribute('class') || '') + " ")
  2580. .replace(/[\n\t]/g, " ")
  2581. .replace(" " + trim(cssClass) + " ", " "))
  2582. );
  2583. });
  2584. }
  2585. }
  2586. function jqLiteAddClass(element, cssClasses) {
  2587. if (cssClasses && element.setAttribute) {
  2588. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2589. .replace(/[\n\t]/g, " ");
  2590. forEach(cssClasses.split(' '), function(cssClass) {
  2591. cssClass = trim(cssClass);
  2592. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2593. existingClasses += cssClass + ' ';
  2594. }
  2595. });
  2596. element.setAttribute('class', trim(existingClasses));
  2597. }
  2598. }
  2599. function jqLiteAddNodes(root, elements) {
  2600. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2601. if (elements) {
  2602. // if a Node (the most common case)
  2603. if (elements.nodeType) {
  2604. root[root.length++] = elements;
  2605. } else {
  2606. var length = elements.length;
  2607. // if an Array or NodeList and not a Window
  2608. if (typeof length === 'number' && elements.window !== elements) {
  2609. if (length) {
  2610. for (var i = 0; i < length; i++) {
  2611. root[root.length++] = elements[i];
  2612. }
  2613. }
  2614. } else {
  2615. root[root.length++] = elements;
  2616. }
  2617. }
  2618. }
  2619. }
  2620. function jqLiteController(element, name) {
  2621. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2622. }
  2623. function jqLiteInheritedData(element, name, value) {
  2624. // if element is the document object work with the html element instead
  2625. // this makes $(document).scope() possible
  2626. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2627. element = element.documentElement;
  2628. }
  2629. var names = isArray(name) ? name : [name];
  2630. while (element) {
  2631. for (var i = 0, ii = names.length; i < ii; i++) {
  2632. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2633. }
  2634. // If dealing with a document fragment node with a host element, and no parent, use the host
  2635. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2636. // to lookup parent controllers.
  2637. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2638. }
  2639. }
  2640. function jqLiteEmpty(element) {
  2641. jqLiteDealoc(element, true);
  2642. while (element.firstChild) {
  2643. element.removeChild(element.firstChild);
  2644. }
  2645. }
  2646. function jqLiteRemove(element, keepData) {
  2647. if (!keepData) jqLiteDealoc(element);
  2648. var parent = element.parentNode;
  2649. if (parent) parent.removeChild(element);
  2650. }
  2651. function jqLiteDocumentLoaded(action, win) {
  2652. win = win || window;
  2653. if (win.document.readyState === 'complete') {
  2654. // Force the action to be run async for consistent behaviour
  2655. // from the action's point of view
  2656. // i.e. it will definitely not be in a $apply
  2657. win.setTimeout(action);
  2658. } else {
  2659. // No need to unbind this handler as load is only ever called once
  2660. jqLite(win).on('load', action);
  2661. }
  2662. }
  2663. //////////////////////////////////////////
  2664. // Functions which are declared directly.
  2665. //////////////////////////////////////////
  2666. var JQLitePrototype = JQLite.prototype = {
  2667. ready: function(fn) {
  2668. var fired = false;
  2669. function trigger() {
  2670. if (fired) return;
  2671. fired = true;
  2672. fn();
  2673. }
  2674. // check if document is already loaded
  2675. if (document.readyState === 'complete') {
  2676. setTimeout(trigger);
  2677. } else {
  2678. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2679. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2680. // jshint -W064
  2681. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2682. // jshint +W064
  2683. }
  2684. },
  2685. toString: function() {
  2686. var value = [];
  2687. forEach(this, function(e) { value.push('' + e);});
  2688. return '[' + value.join(', ') + ']';
  2689. },
  2690. eq: function(index) {
  2691. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2692. },
  2693. length: 0,
  2694. push: push,
  2695. sort: [].sort,
  2696. splice: [].splice
  2697. };
  2698. //////////////////////////////////////////
  2699. // Functions iterating getter/setters.
  2700. // these functions return self on setter and
  2701. // value on get.
  2702. //////////////////////////////////////////
  2703. var BOOLEAN_ATTR = {};
  2704. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2705. BOOLEAN_ATTR[lowercase(value)] = value;
  2706. });
  2707. var BOOLEAN_ELEMENTS = {};
  2708. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2709. BOOLEAN_ELEMENTS[value] = true;
  2710. });
  2711. var ALIASED_ATTR = {
  2712. 'ngMinlength': 'minlength',
  2713. 'ngMaxlength': 'maxlength',
  2714. 'ngMin': 'min',
  2715. 'ngMax': 'max',
  2716. 'ngPattern': 'pattern'
  2717. };
  2718. function getBooleanAttrName(element, name) {
  2719. // check dom last since we will most likely fail on name
  2720. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2721. // booleanAttr is here twice to minimize DOM access
  2722. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2723. }
  2724. function getAliasedAttrName(element, name) {
  2725. var nodeName = element.nodeName;
  2726. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2727. }
  2728. forEach({
  2729. data: jqLiteData,
  2730. removeData: jqLiteRemoveData,
  2731. hasData: jqLiteHasData
  2732. }, function(fn, name) {
  2733. JQLite[name] = fn;
  2734. });
  2735. forEach({
  2736. data: jqLiteData,
  2737. inheritedData: jqLiteInheritedData,
  2738. scope: function(element) {
  2739. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2740. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2741. },
  2742. isolateScope: function(element) {
  2743. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2744. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2745. },
  2746. controller: jqLiteController,
  2747. injector: function(element) {
  2748. return jqLiteInheritedData(element, '$injector');
  2749. },
  2750. removeAttr: function(element, name) {
  2751. element.removeAttribute(name);
  2752. },
  2753. hasClass: jqLiteHasClass,
  2754. css: function(element, name, value) {
  2755. name = camelCase(name);
  2756. if (isDefined(value)) {
  2757. element.style[name] = value;
  2758. } else {
  2759. return element.style[name];
  2760. }
  2761. },
  2762. attr: function(element, name, value) {
  2763. var nodeType = element.nodeType;
  2764. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2765. return;
  2766. }
  2767. var lowercasedName = lowercase(name);
  2768. if (BOOLEAN_ATTR[lowercasedName]) {
  2769. if (isDefined(value)) {
  2770. if (!!value) {
  2771. element[name] = true;
  2772. element.setAttribute(name, lowercasedName);
  2773. } else {
  2774. element[name] = false;
  2775. element.removeAttribute(lowercasedName);
  2776. }
  2777. } else {
  2778. return (element[name] ||
  2779. (element.attributes.getNamedItem(name) || noop).specified)
  2780. ? lowercasedName
  2781. : undefined;
  2782. }
  2783. } else if (isDefined(value)) {
  2784. element.setAttribute(name, value);
  2785. } else if (element.getAttribute) {
  2786. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2787. // some elements (e.g. Document) don't have get attribute, so return undefined
  2788. var ret = element.getAttribute(name, 2);
  2789. // normalize non-existing attributes to undefined (as jQuery)
  2790. return ret === null ? undefined : ret;
  2791. }
  2792. },
  2793. prop: function(element, name, value) {
  2794. if (isDefined(value)) {
  2795. element[name] = value;
  2796. } else {
  2797. return element[name];
  2798. }
  2799. },
  2800. text: (function() {
  2801. getText.$dv = '';
  2802. return getText;
  2803. function getText(element, value) {
  2804. if (isUndefined(value)) {
  2805. var nodeType = element.nodeType;
  2806. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2807. }
  2808. element.textContent = value;
  2809. }
  2810. })(),
  2811. val: function(element, value) {
  2812. if (isUndefined(value)) {
  2813. if (element.multiple && nodeName_(element) === 'select') {
  2814. var result = [];
  2815. forEach(element.options, function(option) {
  2816. if (option.selected) {
  2817. result.push(option.value || option.text);
  2818. }
  2819. });
  2820. return result.length === 0 ? null : result;
  2821. }
  2822. return element.value;
  2823. }
  2824. element.value = value;
  2825. },
  2826. html: function(element, value) {
  2827. if (isUndefined(value)) {
  2828. return element.innerHTML;
  2829. }
  2830. jqLiteDealoc(element, true);
  2831. element.innerHTML = value;
  2832. },
  2833. empty: jqLiteEmpty
  2834. }, function(fn, name) {
  2835. /**
  2836. * Properties: writes return selection, reads return first value
  2837. */
  2838. JQLite.prototype[name] = function(arg1, arg2) {
  2839. var i, key;
  2840. var nodeCount = this.length;
  2841. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2842. // in a way that survives minification.
  2843. // jqLiteEmpty takes no arguments but is a setter.
  2844. if (fn !== jqLiteEmpty &&
  2845. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2846. if (isObject(arg1)) {
  2847. // we are a write, but the object properties are the key/values
  2848. for (i = 0; i < nodeCount; i++) {
  2849. if (fn === jqLiteData) {
  2850. // data() takes the whole object in jQuery
  2851. fn(this[i], arg1);
  2852. } else {
  2853. for (key in arg1) {
  2854. fn(this[i], key, arg1[key]);
  2855. }
  2856. }
  2857. }
  2858. // return self for chaining
  2859. return this;
  2860. } else {
  2861. // we are a read, so read the first child.
  2862. // TODO: do we still need this?
  2863. var value = fn.$dv;
  2864. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2865. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2866. for (var j = 0; j < jj; j++) {
  2867. var nodeValue = fn(this[j], arg1, arg2);
  2868. value = value ? value + nodeValue : nodeValue;
  2869. }
  2870. return value;
  2871. }
  2872. } else {
  2873. // we are a write, so apply to all children
  2874. for (i = 0; i < nodeCount; i++) {
  2875. fn(this[i], arg1, arg2);
  2876. }
  2877. // return self for chaining
  2878. return this;
  2879. }
  2880. };
  2881. });
  2882. function createEventHandler(element, events) {
  2883. var eventHandler = function(event, type) {
  2884. // jQuery specific api
  2885. event.isDefaultPrevented = function() {
  2886. return event.defaultPrevented;
  2887. };
  2888. var eventFns = events[type || event.type];
  2889. var eventFnsLength = eventFns ? eventFns.length : 0;
  2890. if (!eventFnsLength) return;
  2891. if (isUndefined(event.immediatePropagationStopped)) {
  2892. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2893. event.stopImmediatePropagation = function() {
  2894. event.immediatePropagationStopped = true;
  2895. if (event.stopPropagation) {
  2896. event.stopPropagation();
  2897. }
  2898. if (originalStopImmediatePropagation) {
  2899. originalStopImmediatePropagation.call(event);
  2900. }
  2901. };
  2902. }
  2903. event.isImmediatePropagationStopped = function() {
  2904. return event.immediatePropagationStopped === true;
  2905. };
  2906. // Copy event handlers in case event handlers array is modified during execution.
  2907. if ((eventFnsLength > 1)) {
  2908. eventFns = shallowCopy(eventFns);
  2909. }
  2910. for (var i = 0; i < eventFnsLength; i++) {
  2911. if (!event.isImmediatePropagationStopped()) {
  2912. eventFns[i].call(element, event);
  2913. }
  2914. }
  2915. };
  2916. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2917. // events on `element`
  2918. eventHandler.elem = element;
  2919. return eventHandler;
  2920. }
  2921. //////////////////////////////////////////
  2922. // Functions iterating traversal.
  2923. // These functions chain results into a single
  2924. // selector.
  2925. //////////////////////////////////////////
  2926. forEach({
  2927. removeData: jqLiteRemoveData,
  2928. on: function jqLiteOn(element, type, fn, unsupported) {
  2929. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2930. // Do not add event handlers to non-elements because they will not be cleaned up.
  2931. if (!jqLiteAcceptsData(element)) {
  2932. return;
  2933. }
  2934. var expandoStore = jqLiteExpandoStore(element, true);
  2935. var events = expandoStore.events;
  2936. var handle = expandoStore.handle;
  2937. if (!handle) {
  2938. handle = expandoStore.handle = createEventHandler(element, events);
  2939. }
  2940. // http://jsperf.com/string-indexof-vs-split
  2941. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2942. var i = types.length;
  2943. while (i--) {
  2944. type = types[i];
  2945. var eventFns = events[type];
  2946. if (!eventFns) {
  2947. events[type] = [];
  2948. if (type === 'mouseenter' || type === 'mouseleave') {
  2949. // Refer to jQuery's implementation of mouseenter & mouseleave
  2950. // Read about mouseenter and mouseleave:
  2951. // http://www.quirksmode.org/js/events_mouse.html#link8
  2952. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2953. var target = this, related = event.relatedTarget;
  2954. // For mousenter/leave call the handler if related is outside the target.
  2955. // NB: No relatedTarget if the mouse left/entered the browser window
  2956. if (!related || (related !== target && !target.contains(related))) {
  2957. handle(event, type);
  2958. }
  2959. });
  2960. } else {
  2961. if (type !== '$destroy') {
  2962. addEventListenerFn(element, type, handle);
  2963. }
  2964. }
  2965. eventFns = events[type];
  2966. }
  2967. eventFns.push(fn);
  2968. }
  2969. },
  2970. off: jqLiteOff,
  2971. one: function(element, type, fn) {
  2972. element = jqLite(element);
  2973. //add the listener twice so that when it is called
  2974. //you can remove the original function and still be
  2975. //able to call element.off(ev, fn) normally
  2976. element.on(type, function onFn() {
  2977. element.off(type, fn);
  2978. element.off(type, onFn);
  2979. });
  2980. element.on(type, fn);
  2981. },
  2982. replaceWith: function(element, replaceNode) {
  2983. var index, parent = element.parentNode;
  2984. jqLiteDealoc(element);
  2985. forEach(new JQLite(replaceNode), function(node) {
  2986. if (index) {
  2987. parent.insertBefore(node, index.nextSibling);
  2988. } else {
  2989. parent.replaceChild(node, element);
  2990. }
  2991. index = node;
  2992. });
  2993. },
  2994. children: function(element) {
  2995. var children = [];
  2996. forEach(element.childNodes, function(element) {
  2997. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2998. children.push(element);
  2999. }
  3000. });
  3001. return children;
  3002. },
  3003. contents: function(element) {
  3004. return element.contentDocument || element.childNodes || [];
  3005. },
  3006. append: function(element, node) {
  3007. var nodeType = element.nodeType;
  3008. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3009. node = new JQLite(node);
  3010. for (var i = 0, ii = node.length; i < ii; i++) {
  3011. var child = node[i];
  3012. element.appendChild(child);
  3013. }
  3014. },
  3015. prepend: function(element, node) {
  3016. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3017. var index = element.firstChild;
  3018. forEach(new JQLite(node), function(child) {
  3019. element.insertBefore(child, index);
  3020. });
  3021. }
  3022. },
  3023. wrap: function(element, wrapNode) {
  3024. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  3025. var parent = element.parentNode;
  3026. if (parent) {
  3027. parent.replaceChild(wrapNode, element);
  3028. }
  3029. wrapNode.appendChild(element);
  3030. },
  3031. remove: jqLiteRemove,
  3032. detach: function(element) {
  3033. jqLiteRemove(element, true);
  3034. },
  3035. after: function(element, newElement) {
  3036. var index = element, parent = element.parentNode;
  3037. newElement = new JQLite(newElement);
  3038. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3039. var node = newElement[i];
  3040. parent.insertBefore(node, index.nextSibling);
  3041. index = node;
  3042. }
  3043. },
  3044. addClass: jqLiteAddClass,
  3045. removeClass: jqLiteRemoveClass,
  3046. toggleClass: function(element, selector, condition) {
  3047. if (selector) {
  3048. forEach(selector.split(' '), function(className) {
  3049. var classCondition = condition;
  3050. if (isUndefined(classCondition)) {
  3051. classCondition = !jqLiteHasClass(element, className);
  3052. }
  3053. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3054. });
  3055. }
  3056. },
  3057. parent: function(element) {
  3058. var parent = element.parentNode;
  3059. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3060. },
  3061. next: function(element) {
  3062. return element.nextElementSibling;
  3063. },
  3064. find: function(element, selector) {
  3065. if (element.getElementsByTagName) {
  3066. return element.getElementsByTagName(selector);
  3067. } else {
  3068. return [];
  3069. }
  3070. },
  3071. clone: jqLiteClone,
  3072. triggerHandler: function(element, event, extraParameters) {
  3073. var dummyEvent, eventFnsCopy, handlerArgs;
  3074. var eventName = event.type || event;
  3075. var expandoStore = jqLiteExpandoStore(element);
  3076. var events = expandoStore && expandoStore.events;
  3077. var eventFns = events && events[eventName];
  3078. if (eventFns) {
  3079. // Create a dummy event to pass to the handlers
  3080. dummyEvent = {
  3081. preventDefault: function() { this.defaultPrevented = true; },
  3082. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3083. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3084. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3085. stopPropagation: noop,
  3086. type: eventName,
  3087. target: element
  3088. };
  3089. // If a custom event was provided then extend our dummy event with it
  3090. if (event.type) {
  3091. dummyEvent = extend(dummyEvent, event);
  3092. }
  3093. // Copy event handlers in case event handlers array is modified during execution.
  3094. eventFnsCopy = shallowCopy(eventFns);
  3095. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3096. forEach(eventFnsCopy, function(fn) {
  3097. if (!dummyEvent.isImmediatePropagationStopped()) {
  3098. fn.apply(element, handlerArgs);
  3099. }
  3100. });
  3101. }
  3102. }
  3103. }, function(fn, name) {
  3104. /**
  3105. * chaining functions
  3106. */
  3107. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3108. var value;
  3109. for (var i = 0, ii = this.length; i < ii; i++) {
  3110. if (isUndefined(value)) {
  3111. value = fn(this[i], arg1, arg2, arg3);
  3112. if (isDefined(value)) {
  3113. // any function which returns a value needs to be wrapped
  3114. value = jqLite(value);
  3115. }
  3116. } else {
  3117. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3118. }
  3119. }
  3120. return isDefined(value) ? value : this;
  3121. };
  3122. // bind legacy bind/unbind to on/off
  3123. JQLite.prototype.bind = JQLite.prototype.on;
  3124. JQLite.prototype.unbind = JQLite.prototype.off;
  3125. });
  3126. // Provider for private $$jqLite service
  3127. function $$jqLiteProvider() {
  3128. this.$get = function $$jqLite() {
  3129. return extend(JQLite, {
  3130. hasClass: function(node, classes) {
  3131. if (node.attr) node = node[0];
  3132. return jqLiteHasClass(node, classes);
  3133. },
  3134. addClass: function(node, classes) {
  3135. if (node.attr) node = node[0];
  3136. return jqLiteAddClass(node, classes);
  3137. },
  3138. removeClass: function(node, classes) {
  3139. if (node.attr) node = node[0];
  3140. return jqLiteRemoveClass(node, classes);
  3141. }
  3142. });
  3143. };
  3144. }
  3145. /**
  3146. * Computes a hash of an 'obj'.
  3147. * Hash of a:
  3148. * string is string
  3149. * number is number as string
  3150. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3151. * that is also assigned to the $$hashKey property of the object.
  3152. *
  3153. * @param obj
  3154. * @returns {string} hash string such that the same input will have the same hash string.
  3155. * The resulting string key is in 'type:hashKey' format.
  3156. */
  3157. function hashKey(obj, nextUidFn) {
  3158. var key = obj && obj.$$hashKey;
  3159. if (key) {
  3160. if (typeof key === 'function') {
  3161. key = obj.$$hashKey();
  3162. }
  3163. return key;
  3164. }
  3165. var objType = typeof obj;
  3166. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3167. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3168. } else {
  3169. key = objType + ':' + obj;
  3170. }
  3171. return key;
  3172. }
  3173. /**
  3174. * HashMap which can use objects as keys
  3175. */
  3176. function HashMap(array, isolatedUid) {
  3177. if (isolatedUid) {
  3178. var uid = 0;
  3179. this.nextUid = function() {
  3180. return ++uid;
  3181. };
  3182. }
  3183. forEach(array, this.put, this);
  3184. }
  3185. HashMap.prototype = {
  3186. /**
  3187. * Store key value pair
  3188. * @param key key to store can be any type
  3189. * @param value value to store can be any type
  3190. */
  3191. put: function(key, value) {
  3192. this[hashKey(key, this.nextUid)] = value;
  3193. },
  3194. /**
  3195. * @param key
  3196. * @returns {Object} the value for the key
  3197. */
  3198. get: function(key) {
  3199. return this[hashKey(key, this.nextUid)];
  3200. },
  3201. /**
  3202. * Remove the key/value pair
  3203. * @param key
  3204. */
  3205. remove: function(key) {
  3206. var value = this[key = hashKey(key, this.nextUid)];
  3207. delete this[key];
  3208. return value;
  3209. }
  3210. };
  3211. var $$HashMapProvider = [function() {
  3212. this.$get = [function() {
  3213. return HashMap;
  3214. }];
  3215. }];
  3216. /**
  3217. * @ngdoc function
  3218. * @module ng
  3219. * @name angular.injector
  3220. * @kind function
  3221. *
  3222. * @description
  3223. * Creates an injector object that can be used for retrieving services as well as for
  3224. * dependency injection (see {@link guide/di dependency injection}).
  3225. *
  3226. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3227. * {@link angular.module}. The `ng` module must be explicitly added.
  3228. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3229. * disallows argument name annotation inference.
  3230. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3231. *
  3232. * @example
  3233. * Typical usage
  3234. * ```js
  3235. * // create an injector
  3236. * var $injector = angular.injector(['ng']);
  3237. *
  3238. * // use the injector to kick off your application
  3239. * // use the type inference to auto inject arguments, or use implicit injection
  3240. * $injector.invoke(function($rootScope, $compile, $document) {
  3241. * $compile($document)($rootScope);
  3242. * $rootScope.$digest();
  3243. * });
  3244. * ```
  3245. *
  3246. * Sometimes you want to get access to the injector of a currently running Angular app
  3247. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3248. * application has been bootstrapped. You can do this using the extra `injector()` added
  3249. * to JQuery/jqLite elements. See {@link angular.element}.
  3250. *
  3251. * *This is fairly rare but could be the case if a third party library is injecting the
  3252. * markup.*
  3253. *
  3254. * In the following example a new block of HTML containing a `ng-controller`
  3255. * directive is added to the end of the document body by JQuery. We then compile and link
  3256. * it into the current AngularJS scope.
  3257. *
  3258. * ```js
  3259. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3260. * $(document.body).append($div);
  3261. *
  3262. * angular.element(document).injector().invoke(function($compile) {
  3263. * var scope = angular.element($div).scope();
  3264. * $compile($div)(scope);
  3265. * });
  3266. * ```
  3267. */
  3268. /**
  3269. * @ngdoc module
  3270. * @name auto
  3271. * @description
  3272. *
  3273. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3274. */
  3275. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  3276. var FN_ARG_SPLIT = /,/;
  3277. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3278. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3279. var $injectorMinErr = minErr('$injector');
  3280. function anonFn(fn) {
  3281. // For anonymous functions, showing at the very least the function signature can help in
  3282. // debugging.
  3283. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3284. args = fnText.match(FN_ARGS);
  3285. if (args) {
  3286. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3287. }
  3288. return 'fn';
  3289. }
  3290. function annotate(fn, strictDi, name) {
  3291. var $inject,
  3292. fnText,
  3293. argDecl,
  3294. last;
  3295. if (typeof fn === 'function') {
  3296. if (!($inject = fn.$inject)) {
  3297. $inject = [];
  3298. if (fn.length) {
  3299. if (strictDi) {
  3300. if (!isString(name) || !name) {
  3301. name = fn.name || anonFn(fn);
  3302. }
  3303. throw $injectorMinErr('strictdi',
  3304. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3305. }
  3306. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3307. argDecl = fnText.match(FN_ARGS);
  3308. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3309. arg.replace(FN_ARG, function(all, underscore, name) {
  3310. $inject.push(name);
  3311. });
  3312. });
  3313. }
  3314. fn.$inject = $inject;
  3315. }
  3316. } else if (isArray(fn)) {
  3317. last = fn.length - 1;
  3318. assertArgFn(fn[last], 'fn');
  3319. $inject = fn.slice(0, last);
  3320. } else {
  3321. assertArgFn(fn, 'fn', true);
  3322. }
  3323. return $inject;
  3324. }
  3325. ///////////////////////////////////////
  3326. /**
  3327. * @ngdoc service
  3328. * @name $injector
  3329. *
  3330. * @description
  3331. *
  3332. * `$injector` is used to retrieve object instances as defined by
  3333. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3334. * and load modules.
  3335. *
  3336. * The following always holds true:
  3337. *
  3338. * ```js
  3339. * var $injector = angular.injector();
  3340. * expect($injector.get('$injector')).toBe($injector);
  3341. * expect($injector.invoke(function($injector) {
  3342. * return $injector;
  3343. * })).toBe($injector);
  3344. * ```
  3345. *
  3346. * # Injection Function Annotation
  3347. *
  3348. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3349. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3350. *
  3351. * ```js
  3352. * // inferred (only works if code not minified/obfuscated)
  3353. * $injector.invoke(function(serviceA){});
  3354. *
  3355. * // annotated
  3356. * function explicit(serviceA) {};
  3357. * explicit.$inject = ['serviceA'];
  3358. * $injector.invoke(explicit);
  3359. *
  3360. * // inline
  3361. * $injector.invoke(['serviceA', function(serviceA){}]);
  3362. * ```
  3363. *
  3364. * ## Inference
  3365. *
  3366. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3367. * can then be parsed and the function arguments can be extracted. This method of discovering
  3368. * annotations is disallowed when the injector is in strict mode.
  3369. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3370. * argument names.
  3371. *
  3372. * ## `$inject` Annotation
  3373. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3374. *
  3375. * ## Inline
  3376. * As an array of injection names, where the last item in the array is the function to call.
  3377. */
  3378. /**
  3379. * @ngdoc method
  3380. * @name $injector#get
  3381. *
  3382. * @description
  3383. * Return an instance of the service.
  3384. *
  3385. * @param {string} name The name of the instance to retrieve.
  3386. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3387. * @return {*} The instance.
  3388. */
  3389. /**
  3390. * @ngdoc method
  3391. * @name $injector#invoke
  3392. *
  3393. * @description
  3394. * Invoke the method and supply the method arguments from the `$injector`.
  3395. *
  3396. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3397. * injected according to the {@link guide/di $inject Annotation} rules.
  3398. * @param {Object=} self The `this` for the invoked method.
  3399. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3400. * object first, before the `$injector` is consulted.
  3401. * @returns {*} the value returned by the invoked `fn` function.
  3402. */
  3403. /**
  3404. * @ngdoc method
  3405. * @name $injector#has
  3406. *
  3407. * @description
  3408. * Allows the user to query if the particular service exists.
  3409. *
  3410. * @param {string} name Name of the service to query.
  3411. * @returns {boolean} `true` if injector has given service.
  3412. */
  3413. /**
  3414. * @ngdoc method
  3415. * @name $injector#instantiate
  3416. * @description
  3417. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3418. * operator, and supplies all of the arguments to the constructor function as specified by the
  3419. * constructor annotation.
  3420. *
  3421. * @param {Function} Type Annotated constructor function.
  3422. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3423. * object first, before the `$injector` is consulted.
  3424. * @returns {Object} new instance of `Type`.
  3425. */
  3426. /**
  3427. * @ngdoc method
  3428. * @name $injector#annotate
  3429. *
  3430. * @description
  3431. * Returns an array of service names which the function is requesting for injection. This API is
  3432. * used by the injector to determine which services need to be injected into the function when the
  3433. * function is invoked. There are three ways in which the function can be annotated with the needed
  3434. * dependencies.
  3435. *
  3436. * # Argument names
  3437. *
  3438. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3439. * by converting the function into a string using `toString()` method and extracting the argument
  3440. * names.
  3441. * ```js
  3442. * // Given
  3443. * function MyController($scope, $route) {
  3444. * // ...
  3445. * }
  3446. *
  3447. * // Then
  3448. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3449. * ```
  3450. *
  3451. * You can disallow this method by using strict injection mode.
  3452. *
  3453. * This method does not work with code minification / obfuscation. For this reason the following
  3454. * annotation strategies are supported.
  3455. *
  3456. * # The `$inject` property
  3457. *
  3458. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3459. * represent names of services to be injected into the function.
  3460. * ```js
  3461. * // Given
  3462. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3463. * // ...
  3464. * }
  3465. * // Define function dependencies
  3466. * MyController['$inject'] = ['$scope', '$route'];
  3467. *
  3468. * // Then
  3469. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3470. * ```
  3471. *
  3472. * # The array notation
  3473. *
  3474. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3475. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3476. * a way that survives minification is a better choice:
  3477. *
  3478. * ```js
  3479. * // We wish to write this (not minification / obfuscation safe)
  3480. * injector.invoke(function($compile, $rootScope) {
  3481. * // ...
  3482. * });
  3483. *
  3484. * // We are forced to write break inlining
  3485. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3486. * // ...
  3487. * };
  3488. * tmpFn.$inject = ['$compile', '$rootScope'];
  3489. * injector.invoke(tmpFn);
  3490. *
  3491. * // To better support inline function the inline annotation is supported
  3492. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3493. * // ...
  3494. * }]);
  3495. *
  3496. * // Therefore
  3497. * expect(injector.annotate(
  3498. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3499. * ).toEqual(['$compile', '$rootScope']);
  3500. * ```
  3501. *
  3502. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3503. * be retrieved as described above.
  3504. *
  3505. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3506. *
  3507. * @returns {Array.<string>} The names of the services which the function requires.
  3508. */
  3509. /**
  3510. * @ngdoc service
  3511. * @name $provide
  3512. *
  3513. * @description
  3514. *
  3515. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3516. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3517. * {@link angular.Module}.
  3518. *
  3519. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3520. * factories** are functions which, in turn, are created by a **service provider**.
  3521. * The **service providers** are constructor functions. When instantiated they must contain a
  3522. * property called `$get`, which holds the **service factory** function.
  3523. *
  3524. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3525. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3526. * function to get the instance of the **service**.
  3527. *
  3528. * Often services have no configuration options and there is no need to add methods to the service
  3529. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3530. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3531. * services without specifying a provider.
  3532. *
  3533. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3534. * {@link auto.$injector $injector}
  3535. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3536. * providers and services.
  3537. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3538. * services, not providers.
  3539. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3540. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3541. * given factory function.
  3542. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3543. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3544. * a new object using the given constructor function.
  3545. *
  3546. * See the individual methods for more information and examples.
  3547. */
  3548. /**
  3549. * @ngdoc method
  3550. * @name $provide#provider
  3551. * @description
  3552. *
  3553. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3554. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3555. * service.
  3556. *
  3557. * Service provider names start with the name of the service they provide followed by `Provider`.
  3558. * For example, the {@link ng.$log $log} service has a provider called
  3559. * {@link ng.$logProvider $logProvider}.
  3560. *
  3561. * Service provider objects can have additional methods which allow configuration of the provider
  3562. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3563. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3564. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3565. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3566. * console or not.
  3567. *
  3568. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3569. 'Provider'` key.
  3570. * @param {(Object|function())} provider If the provider is:
  3571. *
  3572. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3573. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3574. * - `Constructor`: a new instance of the provider will be created using
  3575. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3576. *
  3577. * @returns {Object} registered provider instance
  3578. * @example
  3579. *
  3580. * The following example shows how to create a simple event tracking service and register it using
  3581. * {@link auto.$provide#provider $provide.provider()}.
  3582. *
  3583. * ```js
  3584. * // Define the eventTracker provider
  3585. * function EventTrackerProvider() {
  3586. * var trackingUrl = '/track';
  3587. *
  3588. * // A provider method for configuring where the tracked events should been saved
  3589. * this.setTrackingUrl = function(url) {
  3590. * trackingUrl = url;
  3591. * };
  3592. *
  3593. * // The service factory function
  3594. * this.$get = ['$http', function($http) {
  3595. * var trackedEvents = {};
  3596. * return {
  3597. * // Call this to track an event
  3598. * event: function(event) {
  3599. * var count = trackedEvents[event] || 0;
  3600. * count += 1;
  3601. * trackedEvents[event] = count;
  3602. * return count;
  3603. * },
  3604. * // Call this to save the tracked events to the trackingUrl
  3605. * save: function() {
  3606. * $http.post(trackingUrl, trackedEvents);
  3607. * }
  3608. * };
  3609. * }];
  3610. * }
  3611. *
  3612. * describe('eventTracker', function() {
  3613. * var postSpy;
  3614. *
  3615. * beforeEach(module(function($provide) {
  3616. * // Register the eventTracker provider
  3617. * $provide.provider('eventTracker', EventTrackerProvider);
  3618. * }));
  3619. *
  3620. * beforeEach(module(function(eventTrackerProvider) {
  3621. * // Configure eventTracker provider
  3622. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3623. * }));
  3624. *
  3625. * it('tracks events', inject(function(eventTracker) {
  3626. * expect(eventTracker.event('login')).toEqual(1);
  3627. * expect(eventTracker.event('login')).toEqual(2);
  3628. * }));
  3629. *
  3630. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3631. * postSpy = spyOn($http, 'post');
  3632. * eventTracker.event('login');
  3633. * eventTracker.save();
  3634. * expect(postSpy).toHaveBeenCalled();
  3635. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3636. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3637. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3638. * }));
  3639. * });
  3640. * ```
  3641. */
  3642. /**
  3643. * @ngdoc method
  3644. * @name $provide#factory
  3645. * @description
  3646. *
  3647. * Register a **service factory**, which will be called to return the service instance.
  3648. * This is short for registering a service where its provider consists of only a `$get` property,
  3649. * which is the given service factory function.
  3650. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3651. * configure your service in a provider.
  3652. *
  3653. * @param {string} name The name of the instance.
  3654. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3655. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3656. * @returns {Object} registered provider instance
  3657. *
  3658. * @example
  3659. * Here is an example of registering a service
  3660. * ```js
  3661. * $provide.factory('ping', ['$http', function($http) {
  3662. * return function ping() {
  3663. * return $http.send('/ping');
  3664. * };
  3665. * }]);
  3666. * ```
  3667. * You would then inject and use this service like this:
  3668. * ```js
  3669. * someModule.controller('Ctrl', ['ping', function(ping) {
  3670. * ping();
  3671. * }]);
  3672. * ```
  3673. */
  3674. /**
  3675. * @ngdoc method
  3676. * @name $provide#service
  3677. * @description
  3678. *
  3679. * Register a **service constructor**, which will be invoked with `new` to create the service
  3680. * instance.
  3681. * This is short for registering a service where its provider's `$get` property is the service
  3682. * constructor function that will be used to instantiate the service instance.
  3683. *
  3684. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3685. * as a type/class.
  3686. *
  3687. * @param {string} name The name of the instance.
  3688. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3689. * that will be instantiated.
  3690. * @returns {Object} registered provider instance
  3691. *
  3692. * @example
  3693. * Here is an example of registering a service using
  3694. * {@link auto.$provide#service $provide.service(class)}.
  3695. * ```js
  3696. * var Ping = function($http) {
  3697. * this.$http = $http;
  3698. * };
  3699. *
  3700. * Ping.$inject = ['$http'];
  3701. *
  3702. * Ping.prototype.send = function() {
  3703. * return this.$http.get('/ping');
  3704. * };
  3705. * $provide.service('ping', Ping);
  3706. * ```
  3707. * You would then inject and use this service like this:
  3708. * ```js
  3709. * someModule.controller('Ctrl', ['ping', function(ping) {
  3710. * ping.send();
  3711. * }]);
  3712. * ```
  3713. */
  3714. /**
  3715. * @ngdoc method
  3716. * @name $provide#value
  3717. * @description
  3718. *
  3719. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3720. * number, an array, an object or a function. This is short for registering a service where its
  3721. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3722. * service**.
  3723. *
  3724. * Value services are similar to constant services, except that they cannot be injected into a
  3725. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3726. * an Angular
  3727. * {@link auto.$provide#decorator decorator}.
  3728. *
  3729. * @param {string} name The name of the instance.
  3730. * @param {*} value The value.
  3731. * @returns {Object} registered provider instance
  3732. *
  3733. * @example
  3734. * Here are some examples of creating value services.
  3735. * ```js
  3736. * $provide.value('ADMIN_USER', 'admin');
  3737. *
  3738. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3739. *
  3740. * $provide.value('halfOf', function(value) {
  3741. * return value / 2;
  3742. * });
  3743. * ```
  3744. */
  3745. /**
  3746. * @ngdoc method
  3747. * @name $provide#constant
  3748. * @description
  3749. *
  3750. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3751. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3752. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3753. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3754. *
  3755. * @param {string} name The name of the constant.
  3756. * @param {*} value The constant value.
  3757. * @returns {Object} registered instance
  3758. *
  3759. * @example
  3760. * Here a some examples of creating constants:
  3761. * ```js
  3762. * $provide.constant('SHARD_HEIGHT', 306);
  3763. *
  3764. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3765. *
  3766. * $provide.constant('double', function(value) {
  3767. * return value * 2;
  3768. * });
  3769. * ```
  3770. */
  3771. /**
  3772. * @ngdoc method
  3773. * @name $provide#decorator
  3774. * @description
  3775. *
  3776. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3777. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3778. * service. The object returned by the decorator may be the original service, or a new service
  3779. * object which replaces or wraps and delegates to the original service.
  3780. *
  3781. * @param {string} name The name of the service to decorate.
  3782. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3783. * instantiated and should return the decorated service instance. The function is called using
  3784. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3785. * Local injection arguments:
  3786. *
  3787. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3788. * decorated or delegated to.
  3789. *
  3790. * @example
  3791. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3792. * calls to {@link ng.$log#error $log.warn()}.
  3793. * ```js
  3794. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3795. * $delegate.warn = $delegate.error;
  3796. * return $delegate;
  3797. * }]);
  3798. * ```
  3799. */
  3800. function createInjector(modulesToLoad, strictDi) {
  3801. strictDi = (strictDi === true);
  3802. var INSTANTIATING = {},
  3803. providerSuffix = 'Provider',
  3804. path = [],
  3805. loadedModules = new HashMap([], true),
  3806. providerCache = {
  3807. $provide: {
  3808. provider: supportObject(provider),
  3809. factory: supportObject(factory),
  3810. service: supportObject(service),
  3811. value: supportObject(value),
  3812. constant: supportObject(constant),
  3813. decorator: decorator
  3814. }
  3815. },
  3816. providerInjector = (providerCache.$injector =
  3817. createInternalInjector(providerCache, function(serviceName, caller) {
  3818. if (angular.isString(caller)) {
  3819. path.push(caller);
  3820. }
  3821. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3822. })),
  3823. instanceCache = {},
  3824. instanceInjector = (instanceCache.$injector =
  3825. createInternalInjector(instanceCache, function(serviceName, caller) {
  3826. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3827. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3828. }));
  3829. forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });
  3830. return instanceInjector;
  3831. ////////////////////////////////////
  3832. // $provider
  3833. ////////////////////////////////////
  3834. function supportObject(delegate) {
  3835. return function(key, value) {
  3836. if (isObject(key)) {
  3837. forEach(key, reverseParams(delegate));
  3838. } else {
  3839. return delegate(key, value);
  3840. }
  3841. };
  3842. }
  3843. function provider(name, provider_) {
  3844. assertNotHasOwnProperty(name, 'service');
  3845. if (isFunction(provider_) || isArray(provider_)) {
  3846. provider_ = providerInjector.instantiate(provider_);
  3847. }
  3848. if (!provider_.$get) {
  3849. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3850. }
  3851. return providerCache[name + providerSuffix] = provider_;
  3852. }
  3853. function enforceReturnValue(name, factory) {
  3854. return function enforcedReturnValue() {
  3855. var result = instanceInjector.invoke(factory, this);
  3856. if (isUndefined(result)) {
  3857. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3858. }
  3859. return result;
  3860. };
  3861. }
  3862. function factory(name, factoryFn, enforce) {
  3863. return provider(name, {
  3864. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3865. });
  3866. }
  3867. function service(name, constructor) {
  3868. return factory(name, ['$injector', function($injector) {
  3869. return $injector.instantiate(constructor);
  3870. }]);
  3871. }
  3872. function value(name, val) { return factory(name, valueFn(val), false); }
  3873. function constant(name, value) {
  3874. assertNotHasOwnProperty(name, 'constant');
  3875. providerCache[name] = value;
  3876. instanceCache[name] = value;
  3877. }
  3878. function decorator(serviceName, decorFn) {
  3879. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3880. orig$get = origProvider.$get;
  3881. origProvider.$get = function() {
  3882. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3883. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3884. };
  3885. }
  3886. ////////////////////////////////////
  3887. // Module Loading
  3888. ////////////////////////////////////
  3889. function loadModules(modulesToLoad) {
  3890. var runBlocks = [], moduleFn;
  3891. forEach(modulesToLoad, function(module) {
  3892. if (loadedModules.get(module)) return;
  3893. loadedModules.put(module, true);
  3894. function runInvokeQueue(queue) {
  3895. var i, ii;
  3896. for (i = 0, ii = queue.length; i < ii; i++) {
  3897. var invokeArgs = queue[i],
  3898. provider = providerInjector.get(invokeArgs[0]);
  3899. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3900. }
  3901. }
  3902. try {
  3903. if (isString(module)) {
  3904. moduleFn = angularModule(module);
  3905. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3906. runInvokeQueue(moduleFn._invokeQueue);
  3907. runInvokeQueue(moduleFn._configBlocks);
  3908. } else if (isFunction(module)) {
  3909. runBlocks.push(providerInjector.invoke(module));
  3910. } else if (isArray(module)) {
  3911. runBlocks.push(providerInjector.invoke(module));
  3912. } else {
  3913. assertArgFn(module, 'module');
  3914. }
  3915. } catch (e) {
  3916. if (isArray(module)) {
  3917. module = module[module.length - 1];
  3918. }
  3919. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3920. // Safari & FF's stack traces don't contain error.message content
  3921. // unlike those of Chrome and IE
  3922. // So if stack doesn't contain message, we create a new string that contains both.
  3923. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3924. /* jshint -W022 */
  3925. e = e.message + '\n' + e.stack;
  3926. }
  3927. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3928. module, e.stack || e.message || e);
  3929. }
  3930. });
  3931. return runBlocks;
  3932. }
  3933. ////////////////////////////////////
  3934. // internal Injector
  3935. ////////////////////////////////////
  3936. function createInternalInjector(cache, factory) {
  3937. function getService(serviceName, caller) {
  3938. if (cache.hasOwnProperty(serviceName)) {
  3939. if (cache[serviceName] === INSTANTIATING) {
  3940. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3941. serviceName + ' <- ' + path.join(' <- '));
  3942. }
  3943. return cache[serviceName];
  3944. } else {
  3945. try {
  3946. path.unshift(serviceName);
  3947. cache[serviceName] = INSTANTIATING;
  3948. return cache[serviceName] = factory(serviceName, caller);
  3949. } catch (err) {
  3950. if (cache[serviceName] === INSTANTIATING) {
  3951. delete cache[serviceName];
  3952. }
  3953. throw err;
  3954. } finally {
  3955. path.shift();
  3956. }
  3957. }
  3958. }
  3959. function invoke(fn, self, locals, serviceName) {
  3960. if (typeof locals === 'string') {
  3961. serviceName = locals;
  3962. locals = null;
  3963. }
  3964. var args = [],
  3965. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  3966. length, i,
  3967. key;
  3968. for (i = 0, length = $inject.length; i < length; i++) {
  3969. key = $inject[i];
  3970. if (typeof key !== 'string') {
  3971. throw $injectorMinErr('itkn',
  3972. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3973. }
  3974. args.push(
  3975. locals && locals.hasOwnProperty(key)
  3976. ? locals[key]
  3977. : getService(key, serviceName)
  3978. );
  3979. }
  3980. if (isArray(fn)) {
  3981. fn = fn[length];
  3982. }
  3983. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3984. // #5388
  3985. return fn.apply(self, args);
  3986. }
  3987. function instantiate(Type, locals, serviceName) {
  3988. // Check if Type is annotated and use just the given function at n-1 as parameter
  3989. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3990. // Object creation: http://jsperf.com/create-constructor/2
  3991. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  3992. var returnedValue = invoke(Type, instance, locals, serviceName);
  3993. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3994. }
  3995. return {
  3996. invoke: invoke,
  3997. instantiate: instantiate,
  3998. get: getService,
  3999. annotate: createInjector.$$annotate,
  4000. has: function(name) {
  4001. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4002. }
  4003. };
  4004. }
  4005. }
  4006. createInjector.$$annotate = annotate;
  4007. /**
  4008. * @ngdoc provider
  4009. * @name $anchorScrollProvider
  4010. *
  4011. * @description
  4012. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4013. * {@link ng.$location#hash $location.hash()} changes.
  4014. */
  4015. function $AnchorScrollProvider() {
  4016. var autoScrollingEnabled = true;
  4017. /**
  4018. * @ngdoc method
  4019. * @name $anchorScrollProvider#disableAutoScrolling
  4020. *
  4021. * @description
  4022. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4023. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4024. * Use this method to disable automatic scrolling.
  4025. *
  4026. * If automatic scrolling is disabled, one must explicitly call
  4027. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4028. * current hash.
  4029. */
  4030. this.disableAutoScrolling = function() {
  4031. autoScrollingEnabled = false;
  4032. };
  4033. /**
  4034. * @ngdoc service
  4035. * @name $anchorScroll
  4036. * @kind function
  4037. * @requires $window
  4038. * @requires $location
  4039. * @requires $rootScope
  4040. *
  4041. * @description
  4042. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4043. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4044. * in the
  4045. * [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  4046. *
  4047. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4048. * match any anchor whenever it changes. This can be disabled by calling
  4049. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4050. *
  4051. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4052. * vertical scroll-offset (either fixed or dynamic).
  4053. *
  4054. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4055. * {@link ng.$location#hash $location.hash()} will be used.
  4056. *
  4057. * @property {(number|function|jqLite)} yOffset
  4058. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4059. * positioned elements at the top of the page, such as navbars, headers etc.
  4060. *
  4061. * `yOffset` can be specified in various ways:
  4062. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4063. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4064. * a number representing the offset (in pixels).<br /><br />
  4065. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4066. * the top of the page to the element's bottom will be used as offset.<br />
  4067. * **Note**: The element will be taken into account only as long as its `position` is set to
  4068. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4069. * their height and/or positioning according to the viewport's size.
  4070. *
  4071. * <br />
  4072. * <div class="alert alert-warning">
  4073. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4074. * not some child element.
  4075. * </div>
  4076. *
  4077. * @example
  4078. <example module="anchorScrollExample">
  4079. <file name="index.html">
  4080. <div id="scrollArea" ng-controller="ScrollController">
  4081. <a ng-click="gotoBottom()">Go to bottom</a>
  4082. <a id="bottom"></a> You're at the bottom!
  4083. </div>
  4084. </file>
  4085. <file name="script.js">
  4086. angular.module('anchorScrollExample', [])
  4087. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4088. function ($scope, $location, $anchorScroll) {
  4089. $scope.gotoBottom = function() {
  4090. // set the location.hash to the id of
  4091. // the element you wish to scroll to.
  4092. $location.hash('bottom');
  4093. // call $anchorScroll()
  4094. $anchorScroll();
  4095. };
  4096. }]);
  4097. </file>
  4098. <file name="style.css">
  4099. #scrollArea {
  4100. height: 280px;
  4101. overflow: auto;
  4102. }
  4103. #bottom {
  4104. display: block;
  4105. margin-top: 2000px;
  4106. }
  4107. </file>
  4108. </example>
  4109. *
  4110. * <hr />
  4111. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4112. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4113. *
  4114. * @example
  4115. <example module="anchorScrollOffsetExample">
  4116. <file name="index.html">
  4117. <div class="fixed-header" ng-controller="headerCtrl">
  4118. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4119. Go to anchor {{x}}
  4120. </a>
  4121. </div>
  4122. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4123. Anchor {{x}} of 5
  4124. </div>
  4125. </file>
  4126. <file name="script.js">
  4127. angular.module('anchorScrollOffsetExample', [])
  4128. .run(['$anchorScroll', function($anchorScroll) {
  4129. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4130. }])
  4131. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4132. function ($anchorScroll, $location, $scope) {
  4133. $scope.gotoAnchor = function(x) {
  4134. var newHash = 'anchor' + x;
  4135. if ($location.hash() !== newHash) {
  4136. // set the $location.hash to `newHash` and
  4137. // $anchorScroll will automatically scroll to it
  4138. $location.hash('anchor' + x);
  4139. } else {
  4140. // call $anchorScroll() explicitly,
  4141. // since $location.hash hasn't changed
  4142. $anchorScroll();
  4143. }
  4144. };
  4145. }
  4146. ]);
  4147. </file>
  4148. <file name="style.css">
  4149. body {
  4150. padding-top: 50px;
  4151. }
  4152. .anchor {
  4153. border: 2px dashed DarkOrchid;
  4154. padding: 10px 10px 200px 10px;
  4155. }
  4156. .fixed-header {
  4157. background-color: rgba(0, 0, 0, 0.2);
  4158. height: 50px;
  4159. position: fixed;
  4160. top: 0; left: 0; right: 0;
  4161. }
  4162. .fixed-header > a {
  4163. display: inline-block;
  4164. margin: 5px 15px;
  4165. }
  4166. </file>
  4167. </example>
  4168. */
  4169. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4170. var document = $window.document;
  4171. // Helper function to get first anchor from a NodeList
  4172. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4173. // and working in all supported browsers.)
  4174. function getFirstAnchor(list) {
  4175. var result = null;
  4176. Array.prototype.some.call(list, function(element) {
  4177. if (nodeName_(element) === 'a') {
  4178. result = element;
  4179. return true;
  4180. }
  4181. });
  4182. return result;
  4183. }
  4184. function getYOffset() {
  4185. var offset = scroll.yOffset;
  4186. if (isFunction(offset)) {
  4187. offset = offset();
  4188. } else if (isElement(offset)) {
  4189. var elem = offset[0];
  4190. var style = $window.getComputedStyle(elem);
  4191. if (style.position !== 'fixed') {
  4192. offset = 0;
  4193. } else {
  4194. offset = elem.getBoundingClientRect().bottom;
  4195. }
  4196. } else if (!isNumber(offset)) {
  4197. offset = 0;
  4198. }
  4199. return offset;
  4200. }
  4201. function scrollTo(elem) {
  4202. if (elem) {
  4203. elem.scrollIntoView();
  4204. var offset = getYOffset();
  4205. if (offset) {
  4206. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4207. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4208. // top of the viewport.
  4209. //
  4210. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4211. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4212. // way down the page.
  4213. //
  4214. // This is often the case for elements near the bottom of the page.
  4215. //
  4216. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4217. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4218. // desired position.
  4219. var elemTop = elem.getBoundingClientRect().top;
  4220. $window.scrollBy(0, elemTop - offset);
  4221. }
  4222. } else {
  4223. $window.scrollTo(0, 0);
  4224. }
  4225. }
  4226. function scroll(hash) {
  4227. hash = isString(hash) ? hash : $location.hash();
  4228. var elm;
  4229. // empty hash, scroll to the top of the page
  4230. if (!hash) scrollTo(null);
  4231. // element with given id
  4232. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4233. // first anchor with given name :-D
  4234. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4235. // no element and hash == 'top', scroll to the top of the page
  4236. else if (hash === 'top') scrollTo(null);
  4237. }
  4238. // does not scroll when user clicks on anchor link that is currently on
  4239. // (no url change, no $location.hash() change), browser native does scroll
  4240. if (autoScrollingEnabled) {
  4241. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4242. function autoScrollWatchAction(newVal, oldVal) {
  4243. // skip the initial scroll if $location.hash is empty
  4244. if (newVal === oldVal && newVal === '') return;
  4245. jqLiteDocumentLoaded(function() {
  4246. $rootScope.$evalAsync(scroll);
  4247. });
  4248. });
  4249. }
  4250. return scroll;
  4251. }];
  4252. }
  4253. var $animateMinErr = minErr('$animate');
  4254. var ELEMENT_NODE = 1;
  4255. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4256. function mergeClasses(a,b) {
  4257. if (!a && !b) return '';
  4258. if (!a) return b;
  4259. if (!b) return a;
  4260. if (isArray(a)) a = a.join(' ');
  4261. if (isArray(b)) b = b.join(' ');
  4262. return a + ' ' + b;
  4263. }
  4264. function extractElementNode(element) {
  4265. for (var i = 0; i < element.length; i++) {
  4266. var elm = element[i];
  4267. if (elm.nodeType === ELEMENT_NODE) {
  4268. return elm;
  4269. }
  4270. }
  4271. }
  4272. function splitClasses(classes) {
  4273. if (isString(classes)) {
  4274. classes = classes.split(' ');
  4275. }
  4276. // Use createMap() to prevent class assumptions involving property names in
  4277. // Object.prototype
  4278. var obj = createMap();
  4279. forEach(classes, function(klass) {
  4280. // sometimes the split leaves empty string values
  4281. // incase extra spaces were applied to the options
  4282. if (klass.length) {
  4283. obj[klass] = true;
  4284. }
  4285. });
  4286. return obj;
  4287. }
  4288. // if any other type of options value besides an Object value is
  4289. // passed into the $animate.method() animation then this helper code
  4290. // will be run which will ignore it. While this patch is not the
  4291. // greatest solution to this, a lot of existing plugins depend on
  4292. // $animate to either call the callback (< 1.2) or return a promise
  4293. // that can be changed. This helper function ensures that the options
  4294. // are wiped clean incase a callback function is provided.
  4295. function prepareAnimateOptions(options) {
  4296. return isObject(options)
  4297. ? options
  4298. : {};
  4299. }
  4300. var $$CoreAnimateRunnerProvider = function() {
  4301. this.$get = ['$q', '$$rAF', function($q, $$rAF) {
  4302. function AnimateRunner() {}
  4303. AnimateRunner.all = noop;
  4304. AnimateRunner.chain = noop;
  4305. AnimateRunner.prototype = {
  4306. end: noop,
  4307. cancel: noop,
  4308. resume: noop,
  4309. pause: noop,
  4310. complete: noop,
  4311. then: function(pass, fail) {
  4312. return $q(function(resolve) {
  4313. $$rAF(function() {
  4314. resolve();
  4315. });
  4316. }).then(pass, fail);
  4317. }
  4318. };
  4319. return AnimateRunner;
  4320. }];
  4321. };
  4322. // this is prefixed with Core since it conflicts with
  4323. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4324. var $$CoreAnimateQueueProvider = function() {
  4325. var postDigestQueue = new HashMap();
  4326. var postDigestElements = [];
  4327. this.$get = ['$$AnimateRunner', '$rootScope',
  4328. function($$AnimateRunner, $rootScope) {
  4329. return {
  4330. enabled: noop,
  4331. on: noop,
  4332. off: noop,
  4333. pin: noop,
  4334. push: function(element, event, options, domOperation) {
  4335. domOperation && domOperation();
  4336. options = options || {};
  4337. options.from && element.css(options.from);
  4338. options.to && element.css(options.to);
  4339. if (options.addClass || options.removeClass) {
  4340. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4341. }
  4342. return new $$AnimateRunner(); // jshint ignore:line
  4343. }
  4344. };
  4345. function addRemoveClassesPostDigest(element, add, remove) {
  4346. var data = postDigestQueue.get(element);
  4347. var classVal;
  4348. if (!data) {
  4349. postDigestQueue.put(element, data = {});
  4350. postDigestElements.push(element);
  4351. }
  4352. if (add) {
  4353. forEach(add.split(' '), function(className) {
  4354. if (className) {
  4355. data[className] = true;
  4356. }
  4357. });
  4358. }
  4359. if (remove) {
  4360. forEach(remove.split(' '), function(className) {
  4361. if (className) {
  4362. data[className] = false;
  4363. }
  4364. });
  4365. }
  4366. if (postDigestElements.length > 1) return;
  4367. $rootScope.$$postDigest(function() {
  4368. forEach(postDigestElements, function(element) {
  4369. var data = postDigestQueue.get(element);
  4370. if (data) {
  4371. var existing = splitClasses(element.attr('class'));
  4372. var toAdd = '';
  4373. var toRemove = '';
  4374. forEach(data, function(status, className) {
  4375. var hasClass = !!existing[className];
  4376. if (status !== hasClass) {
  4377. if (status) {
  4378. toAdd += (toAdd.length ? ' ' : '') + className;
  4379. } else {
  4380. toRemove += (toRemove.length ? ' ' : '') + className;
  4381. }
  4382. }
  4383. });
  4384. forEach(element, function(elm) {
  4385. toAdd && jqLiteAddClass(elm, toAdd);
  4386. toRemove && jqLiteRemoveClass(elm, toRemove);
  4387. });
  4388. postDigestQueue.remove(element);
  4389. }
  4390. });
  4391. postDigestElements.length = 0;
  4392. });
  4393. }
  4394. }];
  4395. };
  4396. /**
  4397. * @ngdoc provider
  4398. * @name $animateProvider
  4399. *
  4400. * @description
  4401. * Default implementation of $animate that doesn't perform any animations, instead just
  4402. * synchronously performs DOM updates and resolves the returned runner promise.
  4403. *
  4404. * In order to enable animations the `ngAnimate` module has to be loaded.
  4405. *
  4406. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4407. */
  4408. var $AnimateProvider = ['$provide', function($provide) {
  4409. var provider = this;
  4410. this.$$registeredAnimations = Object.create(null);
  4411. /**
  4412. * @ngdoc method
  4413. * @name $animateProvider#register
  4414. *
  4415. * @description
  4416. * Registers a new injectable animation factory function. The factory function produces the
  4417. * animation object which contains callback functions for each event that is expected to be
  4418. * animated.
  4419. *
  4420. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4421. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4422. * on the type of animation additional arguments will be injected into the animation function. The
  4423. * list below explains the function signatures for the different animation methods:
  4424. *
  4425. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4426. * - addClass: function(element, addedClasses, doneFunction, options)
  4427. * - removeClass: function(element, removedClasses, doneFunction, options)
  4428. * - enter, leave, move: function(element, doneFunction, options)
  4429. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4430. *
  4431. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4432. *
  4433. * ```js
  4434. * return {
  4435. * //enter, leave, move signature
  4436. * eventFn : function(element, done, options) {
  4437. * //code to run the animation
  4438. * //once complete, then run done()
  4439. * return function endFunction(wasCancelled) {
  4440. * //code to cancel the animation
  4441. * }
  4442. * }
  4443. * }
  4444. * ```
  4445. *
  4446. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4447. * @param {Function} factory The factory function that will be executed to return the animation
  4448. * object.
  4449. */
  4450. this.register = function(name, factory) {
  4451. if (name && name.charAt(0) !== '.') {
  4452. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4453. }
  4454. var key = name + '-animation';
  4455. provider.$$registeredAnimations[name.substr(1)] = key;
  4456. $provide.factory(key, factory);
  4457. };
  4458. /**
  4459. * @ngdoc method
  4460. * @name $animateProvider#classNameFilter
  4461. *
  4462. * @description
  4463. * Sets and/or returns the CSS class regular expression that is checked when performing
  4464. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4465. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4466. * When setting the `classNameFilter` value, animations will only be performed on elements
  4467. * that successfully match the filter expression. This in turn can boost performance
  4468. * for low-powered devices as well as applications containing a lot of structural operations.
  4469. * @param {RegExp=} expression The className expression which will be checked against all animations
  4470. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4471. */
  4472. this.classNameFilter = function(expression) {
  4473. if (arguments.length === 1) {
  4474. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4475. if (this.$$classNameFilter) {
  4476. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4477. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4478. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4479. }
  4480. }
  4481. }
  4482. return this.$$classNameFilter;
  4483. };
  4484. this.$get = ['$$animateQueue', function($$animateQueue) {
  4485. function domInsert(element, parentElement, afterElement) {
  4486. // if for some reason the previous element was removed
  4487. // from the dom sometime before this code runs then let's
  4488. // just stick to using the parent element as the anchor
  4489. if (afterElement) {
  4490. var afterNode = extractElementNode(afterElement);
  4491. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4492. afterElement = null;
  4493. }
  4494. }
  4495. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4496. }
  4497. /**
  4498. * @ngdoc service
  4499. * @name $animate
  4500. * @description The $animate service exposes a series of DOM utility methods that provide support
  4501. * for animation hooks. The default behavior is the application of DOM operations, however,
  4502. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4503. * to ensure that animation runs with the triggered DOM operation.
  4504. *
  4505. * By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't
  4506. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4507. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4508. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4509. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4510. *
  4511. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4512. *
  4513. * To learn more about enabling animation support, click here to visit the
  4514. * {@link ngAnimate ngAnimate module page}.
  4515. */
  4516. return {
  4517. // we don't call it directly since non-existant arguments may
  4518. // be interpreted as null within the sub enabled function
  4519. /**
  4520. *
  4521. * @ngdoc method
  4522. * @name $animate#on
  4523. * @kind function
  4524. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4525. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4526. * is fired with the following params:
  4527. *
  4528. * ```js
  4529. * $animate.on('enter', container,
  4530. * function callback(element, phase) {
  4531. * // cool we detected an enter animation within the container
  4532. * }
  4533. * );
  4534. * ```
  4535. *
  4536. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4537. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4538. * as well as among its children
  4539. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4540. *
  4541. * The arguments present in the callback function are:
  4542. * * `element` - The captured DOM element that the animation was fired on.
  4543. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4544. */
  4545. on: $$animateQueue.on,
  4546. /**
  4547. *
  4548. * @ngdoc method
  4549. * @name $animate#off
  4550. * @kind function
  4551. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4552. * can be used in three different ways depending on the arguments:
  4553. *
  4554. * ```js
  4555. * // remove all the animation event listeners listening for `enter`
  4556. * $animate.off('enter');
  4557. *
  4558. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4559. * $animate.off('enter', container);
  4560. *
  4561. * // remove the event listener function provided by `listenerFn` that is set
  4562. * // to listen for `enter` on the given `element` as well as its children
  4563. * $animate.off('enter', container, callback);
  4564. * ```
  4565. *
  4566. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  4567. * @param {DOMElement=} container the container element the event listener was placed on
  4568. * @param {Function=} callback the callback function that was registered as the listener
  4569. */
  4570. off: $$animateQueue.off,
  4571. /**
  4572. * @ngdoc method
  4573. * @name $animate#pin
  4574. * @kind function
  4575. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4576. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4577. * element despite being outside the realm of the application or within another application. Say for example if the application
  4578. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4579. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4580. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4581. *
  4582. * Note that this feature is only active when the `ngAnimate` module is used.
  4583. *
  4584. * @param {DOMElement} element the external element that will be pinned
  4585. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4586. */
  4587. pin: $$animateQueue.pin,
  4588. /**
  4589. *
  4590. * @ngdoc method
  4591. * @name $animate#enabled
  4592. * @kind function
  4593. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4594. * function can be called in four ways:
  4595. *
  4596. * ```js
  4597. * // returns true or false
  4598. * $animate.enabled();
  4599. *
  4600. * // changes the enabled state for all animations
  4601. * $animate.enabled(false);
  4602. * $animate.enabled(true);
  4603. *
  4604. * // returns true or false if animations are enabled for an element
  4605. * $animate.enabled(element);
  4606. *
  4607. * // changes the enabled state for an element and its children
  4608. * $animate.enabled(element, true);
  4609. * $animate.enabled(element, false);
  4610. * ```
  4611. *
  4612. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4613. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4614. *
  4615. * @return {boolean} whether or not animations are enabled
  4616. */
  4617. enabled: $$animateQueue.enabled,
  4618. /**
  4619. * @ngdoc method
  4620. * @name $animate#cancel
  4621. * @kind function
  4622. * @description Cancels the provided animation.
  4623. *
  4624. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4625. */
  4626. cancel: function(runner) {
  4627. runner.end && runner.end();
  4628. },
  4629. /**
  4630. *
  4631. * @ngdoc method
  4632. * @name $animate#enter
  4633. * @kind function
  4634. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4635. * as the first child within the `parent` element and then triggers an animation.
  4636. * A promise is returned that will be resolved during the next digest once the animation
  4637. * has completed.
  4638. *
  4639. * @param {DOMElement} element the element which will be inserted into the DOM
  4640. * @param {DOMElement} parent the parent element which will append the element as
  4641. * a child (so long as the after element is not present)
  4642. * @param {DOMElement=} after the sibling element after which the element will be appended
  4643. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4644. *
  4645. * @return {Promise} the animation callback promise
  4646. */
  4647. enter: function(element, parent, after, options) {
  4648. parent = parent && jqLite(parent);
  4649. after = after && jqLite(after);
  4650. parent = parent || after.parent();
  4651. domInsert(element, parent, after);
  4652. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4653. },
  4654. /**
  4655. *
  4656. * @ngdoc method
  4657. * @name $animate#move
  4658. * @kind function
  4659. * @description Inserts (moves) the element into its new position in the DOM either after
  4660. * the `after` element (if provided) or as the first child within the `parent` element
  4661. * and then triggers an animation. A promise is returned that will be resolved
  4662. * during the next digest once the animation has completed.
  4663. *
  4664. * @param {DOMElement} element the element which will be moved into the new DOM position
  4665. * @param {DOMElement} parent the parent element which will append the element as
  4666. * a child (so long as the after element is not present)
  4667. * @param {DOMElement=} after the sibling element after which the element will be appended
  4668. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4669. *
  4670. * @return {Promise} the animation callback promise
  4671. */
  4672. move: function(element, parent, after, options) {
  4673. parent = parent && jqLite(parent);
  4674. after = after && jqLite(after);
  4675. parent = parent || after.parent();
  4676. domInsert(element, parent, after);
  4677. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4678. },
  4679. /**
  4680. * @ngdoc method
  4681. * @name $animate#leave
  4682. * @kind function
  4683. * @description Triggers an animation and then removes the element from the DOM.
  4684. * When the function is called a promise is returned that will be resolved during the next
  4685. * digest once the animation has completed.
  4686. *
  4687. * @param {DOMElement} element the element which will be removed from the DOM
  4688. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4689. *
  4690. * @return {Promise} the animation callback promise
  4691. */
  4692. leave: function(element, options) {
  4693. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4694. element.remove();
  4695. });
  4696. },
  4697. /**
  4698. * @ngdoc method
  4699. * @name $animate#addClass
  4700. * @kind function
  4701. *
  4702. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4703. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4704. * animation if element already contains the CSS class or if the class is removed at a later step.
  4705. * Note that class-based animations are treated differently compared to structural animations
  4706. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4707. * depending if CSS or JavaScript animations are used.
  4708. *
  4709. * @param {DOMElement} element the element which the CSS classes will be applied to
  4710. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4711. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4712. *
  4713. * @return {Promise} the animation callback promise
  4714. */
  4715. addClass: function(element, className, options) {
  4716. options = prepareAnimateOptions(options);
  4717. options.addClass = mergeClasses(options.addclass, className);
  4718. return $$animateQueue.push(element, 'addClass', options);
  4719. },
  4720. /**
  4721. * @ngdoc method
  4722. * @name $animate#removeClass
  4723. * @kind function
  4724. *
  4725. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4726. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4727. * animation if element does not contain the CSS class or if the class is added at a later step.
  4728. * Note that class-based animations are treated differently compared to structural animations
  4729. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4730. * depending if CSS or JavaScript animations are used.
  4731. *
  4732. * @param {DOMElement} element the element which the CSS classes will be applied to
  4733. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4734. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4735. *
  4736. * @return {Promise} the animation callback promise
  4737. */
  4738. removeClass: function(element, className, options) {
  4739. options = prepareAnimateOptions(options);
  4740. options.removeClass = mergeClasses(options.removeClass, className);
  4741. return $$animateQueue.push(element, 'removeClass', options);
  4742. },
  4743. /**
  4744. * @ngdoc method
  4745. * @name $animate#setClass
  4746. * @kind function
  4747. *
  4748. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  4749. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  4750. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  4751. * passed. Note that class-based animations are treated differently compared to structural animations
  4752. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4753. * depending if CSS or JavaScript animations are used.
  4754. *
  4755. * @param {DOMElement} element the element which the CSS classes will be applied to
  4756. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  4757. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4758. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4759. *
  4760. * @return {Promise} the animation callback promise
  4761. */
  4762. setClass: function(element, add, remove, options) {
  4763. options = prepareAnimateOptions(options);
  4764. options.addClass = mergeClasses(options.addClass, add);
  4765. options.removeClass = mergeClasses(options.removeClass, remove);
  4766. return $$animateQueue.push(element, 'setClass', options);
  4767. },
  4768. /**
  4769. * @ngdoc method
  4770. * @name $animate#animate
  4771. * @kind function
  4772. *
  4773. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  4774. * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
  4775. * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
  4776. * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
  4777. * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
  4778. *
  4779. * @param {DOMElement} element the element which the CSS styles will be applied to
  4780. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  4781. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  4782. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  4783. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  4784. * (Note that if no animation is detected then this value will not be appplied to the element.)
  4785. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4786. *
  4787. * @return {Promise} the animation callback promise
  4788. */
  4789. animate: function(element, from, to, className, options) {
  4790. options = prepareAnimateOptions(options);
  4791. options.from = options.from ? extend(options.from, from) : from;
  4792. options.to = options.to ? extend(options.to, to) : to;
  4793. className = className || 'ng-inline-animate';
  4794. options.tempClasses = mergeClasses(options.tempClasses, className);
  4795. return $$animateQueue.push(element, 'animate', options);
  4796. }
  4797. };
  4798. }];
  4799. }];
  4800. function $$AsyncCallbackProvider() {
  4801. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  4802. return $$rAF.supported
  4803. ? function(fn) { return $$rAF(fn); }
  4804. : function(fn) {
  4805. return $timeout(fn, 0, false);
  4806. };
  4807. }];
  4808. }
  4809. /* global stripHash: true */
  4810. /**
  4811. * ! This is a private undocumented service !
  4812. *
  4813. * @name $browser
  4814. * @requires $log
  4815. * @description
  4816. * This object has two goals:
  4817. *
  4818. * - hide all the global state in the browser caused by the window object
  4819. * - abstract away all the browser specific features and inconsistencies
  4820. *
  4821. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4822. * service, which can be used for convenient testing of the application without the interaction with
  4823. * the real browser apis.
  4824. */
  4825. /**
  4826. * @param {object} window The global window object.
  4827. * @param {object} document jQuery wrapped document.
  4828. * @param {object} $log window.console or an object with the same interface.
  4829. * @param {object} $sniffer $sniffer service
  4830. */
  4831. function Browser(window, document, $log, $sniffer) {
  4832. var self = this,
  4833. rawDocument = document[0],
  4834. location = window.location,
  4835. history = window.history,
  4836. setTimeout = window.setTimeout,
  4837. clearTimeout = window.clearTimeout,
  4838. pendingDeferIds = {};
  4839. self.isMock = false;
  4840. var outstandingRequestCount = 0;
  4841. var outstandingRequestCallbacks = [];
  4842. // TODO(vojta): remove this temporary api
  4843. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4844. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4845. /**
  4846. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4847. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4848. */
  4849. function completeOutstandingRequest(fn) {
  4850. try {
  4851. fn.apply(null, sliceArgs(arguments, 1));
  4852. } finally {
  4853. outstandingRequestCount--;
  4854. if (outstandingRequestCount === 0) {
  4855. while (outstandingRequestCallbacks.length) {
  4856. try {
  4857. outstandingRequestCallbacks.pop()();
  4858. } catch (e) {
  4859. $log.error(e);
  4860. }
  4861. }
  4862. }
  4863. }
  4864. }
  4865. function getHash(url) {
  4866. var index = url.indexOf('#');
  4867. return index === -1 ? '' : url.substr(index);
  4868. }
  4869. /**
  4870. * @private
  4871. * Note: this method is used only by scenario runner
  4872. * TODO(vojta): prefix this method with $$ ?
  4873. * @param {function()} callback Function that will be called when no outstanding request
  4874. */
  4875. self.notifyWhenNoOutstandingRequests = function(callback) {
  4876. if (outstandingRequestCount === 0) {
  4877. callback();
  4878. } else {
  4879. outstandingRequestCallbacks.push(callback);
  4880. }
  4881. };
  4882. //////////////////////////////////////////////////////////////
  4883. // URL API
  4884. //////////////////////////////////////////////////////////////
  4885. var cachedState, lastHistoryState,
  4886. lastBrowserUrl = location.href,
  4887. baseElement = document.find('base'),
  4888. reloadLocation = null;
  4889. cacheState();
  4890. lastHistoryState = cachedState;
  4891. /**
  4892. * @name $browser#url
  4893. *
  4894. * @description
  4895. * GETTER:
  4896. * Without any argument, this method just returns current value of location.href.
  4897. *
  4898. * SETTER:
  4899. * With at least one argument, this method sets url to new value.
  4900. * If html5 history api supported, pushState/replaceState is used, otherwise
  4901. * location.href/location.replace is used.
  4902. * Returns its own instance to allow chaining
  4903. *
  4904. * NOTE: this api is intended for use only by the $location service. Please use the
  4905. * {@link ng.$location $location service} to change url.
  4906. *
  4907. * @param {string} url New url (when used as setter)
  4908. * @param {boolean=} replace Should new url replace current history record?
  4909. * @param {object=} state object to use with pushState/replaceState
  4910. */
  4911. self.url = function(url, replace, state) {
  4912. // In modern browsers `history.state` is `null` by default; treating it separately
  4913. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  4914. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  4915. if (isUndefined(state)) {
  4916. state = null;
  4917. }
  4918. // Android Browser BFCache causes location, history reference to become stale.
  4919. if (location !== window.location) location = window.location;
  4920. if (history !== window.history) history = window.history;
  4921. // setter
  4922. if (url) {
  4923. var sameState = lastHistoryState === state;
  4924. // Don't change anything if previous and current URLs and states match. This also prevents
  4925. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  4926. // See https://github.com/angular/angular.js/commit/ffb2701
  4927. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  4928. return self;
  4929. }
  4930. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4931. lastBrowserUrl = url;
  4932. lastHistoryState = state;
  4933. // Don't use history API if only the hash changed
  4934. // due to a bug in IE10/IE11 which leads
  4935. // to not firing a `hashchange` nor `popstate` event
  4936. // in some cases (see #9143).
  4937. if ($sniffer.history && (!sameBase || !sameState)) {
  4938. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  4939. cacheState();
  4940. // Do the assignment again so that those two variables are referentially identical.
  4941. lastHistoryState = cachedState;
  4942. } else {
  4943. if (!sameBase || reloadLocation) {
  4944. reloadLocation = url;
  4945. }
  4946. if (replace) {
  4947. location.replace(url);
  4948. } else if (!sameBase) {
  4949. location.href = url;
  4950. } else {
  4951. location.hash = getHash(url);
  4952. }
  4953. }
  4954. return self;
  4955. // getter
  4956. } else {
  4957. // - reloadLocation is needed as browsers don't allow to read out
  4958. // the new location.href if a reload happened.
  4959. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4960. return reloadLocation || location.href.replace(/%27/g,"'");
  4961. }
  4962. };
  4963. /**
  4964. * @name $browser#state
  4965. *
  4966. * @description
  4967. * This method is a getter.
  4968. *
  4969. * Return history.state or null if history.state is undefined.
  4970. *
  4971. * @returns {object} state
  4972. */
  4973. self.state = function() {
  4974. return cachedState;
  4975. };
  4976. var urlChangeListeners = [],
  4977. urlChangeInit = false;
  4978. function cacheStateAndFireUrlChange() {
  4979. cacheState();
  4980. fireUrlChange();
  4981. }
  4982. function getCurrentState() {
  4983. try {
  4984. return history.state;
  4985. } catch (e) {
  4986. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  4987. }
  4988. }
  4989. // This variable should be used *only* inside the cacheState function.
  4990. var lastCachedState = null;
  4991. function cacheState() {
  4992. // This should be the only place in $browser where `history.state` is read.
  4993. cachedState = getCurrentState();
  4994. cachedState = isUndefined(cachedState) ? null : cachedState;
  4995. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  4996. if (equals(cachedState, lastCachedState)) {
  4997. cachedState = lastCachedState;
  4998. }
  4999. lastCachedState = cachedState;
  5000. }
  5001. function fireUrlChange() {
  5002. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5003. return;
  5004. }
  5005. lastBrowserUrl = self.url();
  5006. lastHistoryState = cachedState;
  5007. forEach(urlChangeListeners, function(listener) {
  5008. listener(self.url(), cachedState);
  5009. });
  5010. }
  5011. /**
  5012. * @name $browser#onUrlChange
  5013. *
  5014. * @description
  5015. * Register callback function that will be called, when url changes.
  5016. *
  5017. * It's only called when the url is changed from outside of angular:
  5018. * - user types different url into address bar
  5019. * - user clicks on history (forward/back) button
  5020. * - user clicks on a link
  5021. *
  5022. * It's not called when url is changed by $browser.url() method
  5023. *
  5024. * The listener gets called with new url as parameter.
  5025. *
  5026. * NOTE: this api is intended for use only by the $location service. Please use the
  5027. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5028. *
  5029. * @param {function(string)} listener Listener function to be called when url changes.
  5030. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5031. */
  5032. self.onUrlChange = function(callback) {
  5033. // TODO(vojta): refactor to use node's syntax for events
  5034. if (!urlChangeInit) {
  5035. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5036. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5037. // changed by push/replaceState
  5038. // html5 history api - popstate event
  5039. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5040. // hashchange event
  5041. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5042. urlChangeInit = true;
  5043. }
  5044. urlChangeListeners.push(callback);
  5045. return callback;
  5046. };
  5047. /**
  5048. * @private
  5049. * Remove popstate and hashchange handler from window.
  5050. *
  5051. * NOTE: this api is intended for use only by $rootScope.
  5052. */
  5053. self.$$applicationDestroyed = function() {
  5054. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5055. };
  5056. /**
  5057. * Checks whether the url has changed outside of Angular.
  5058. * Needs to be exported to be able to check for changes that have been done in sync,
  5059. * as hashchange/popstate events fire in async.
  5060. */
  5061. self.$$checkUrlChange = fireUrlChange;
  5062. //////////////////////////////////////////////////////////////
  5063. // Misc API
  5064. //////////////////////////////////////////////////////////////
  5065. /**
  5066. * @name $browser#baseHref
  5067. *
  5068. * @description
  5069. * Returns current <base href>
  5070. * (always relative - without domain)
  5071. *
  5072. * @returns {string} The current base href
  5073. */
  5074. self.baseHref = function() {
  5075. var href = baseElement.attr('href');
  5076. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5077. };
  5078. /**
  5079. * @name $browser#defer
  5080. * @param {function()} fn A function, who's execution should be deferred.
  5081. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5082. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5083. *
  5084. * @description
  5085. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5086. *
  5087. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5088. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5089. * via `$browser.defer.flush()`.
  5090. *
  5091. */
  5092. self.defer = function(fn, delay) {
  5093. var timeoutId;
  5094. outstandingRequestCount++;
  5095. timeoutId = setTimeout(function() {
  5096. delete pendingDeferIds[timeoutId];
  5097. completeOutstandingRequest(fn);
  5098. }, delay || 0);
  5099. pendingDeferIds[timeoutId] = true;
  5100. return timeoutId;
  5101. };
  5102. /**
  5103. * @name $browser#defer.cancel
  5104. *
  5105. * @description
  5106. * Cancels a deferred task identified with `deferId`.
  5107. *
  5108. * @param {*} deferId Token returned by the `$browser.defer` function.
  5109. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5110. * canceled.
  5111. */
  5112. self.defer.cancel = function(deferId) {
  5113. if (pendingDeferIds[deferId]) {
  5114. delete pendingDeferIds[deferId];
  5115. clearTimeout(deferId);
  5116. completeOutstandingRequest(noop);
  5117. return true;
  5118. }
  5119. return false;
  5120. };
  5121. }
  5122. function $BrowserProvider() {
  5123. this.$get = ['$window', '$log', '$sniffer', '$document',
  5124. function($window, $log, $sniffer, $document) {
  5125. return new Browser($window, $document, $log, $sniffer);
  5126. }];
  5127. }
  5128. /**
  5129. * @ngdoc service
  5130. * @name $cacheFactory
  5131. *
  5132. * @description
  5133. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5134. * them.
  5135. *
  5136. * ```js
  5137. *
  5138. * var cache = $cacheFactory('cacheId');
  5139. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5140. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5141. *
  5142. * cache.put("key", "value");
  5143. * cache.put("another key", "another value");
  5144. *
  5145. * // We've specified no options on creation
  5146. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5147. *
  5148. * ```
  5149. *
  5150. *
  5151. * @param {string} cacheId Name or id of the newly created cache.
  5152. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5153. *
  5154. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5155. *
  5156. * @returns {object} Newly created cache object with the following set of methods:
  5157. *
  5158. * - `{object}` `info()` — Returns id, size, and options of cache.
  5159. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5160. * it.
  5161. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5162. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5163. * - `{void}` `removeAll()` — Removes all cached values.
  5164. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5165. *
  5166. * @example
  5167. <example module="cacheExampleApp">
  5168. <file name="index.html">
  5169. <div ng-controller="CacheController">
  5170. <input ng-model="newCacheKey" placeholder="Key">
  5171. <input ng-model="newCacheValue" placeholder="Value">
  5172. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5173. <p ng-if="keys.length">Cached Values</p>
  5174. <div ng-repeat="key in keys">
  5175. <span ng-bind="key"></span>
  5176. <span>: </span>
  5177. <b ng-bind="cache.get(key)"></b>
  5178. </div>
  5179. <p>Cache Info</p>
  5180. <div ng-repeat="(key, value) in cache.info()">
  5181. <span ng-bind="key"></span>
  5182. <span>: </span>
  5183. <b ng-bind="value"></b>
  5184. </div>
  5185. </div>
  5186. </file>
  5187. <file name="script.js">
  5188. angular.module('cacheExampleApp', []).
  5189. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5190. $scope.keys = [];
  5191. $scope.cache = $cacheFactory('cacheId');
  5192. $scope.put = function(key, value) {
  5193. if ($scope.cache.get(key) === undefined) {
  5194. $scope.keys.push(key);
  5195. }
  5196. $scope.cache.put(key, value === undefined ? null : value);
  5197. };
  5198. }]);
  5199. </file>
  5200. <file name="style.css">
  5201. p {
  5202. margin: 10px 0 3px;
  5203. }
  5204. </file>
  5205. </example>
  5206. */
  5207. function $CacheFactoryProvider() {
  5208. this.$get = function() {
  5209. var caches = {};
  5210. function cacheFactory(cacheId, options) {
  5211. if (cacheId in caches) {
  5212. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5213. }
  5214. var size = 0,
  5215. stats = extend({}, options, {id: cacheId}),
  5216. data = {},
  5217. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5218. lruHash = {},
  5219. freshEnd = null,
  5220. staleEnd = null;
  5221. /**
  5222. * @ngdoc type
  5223. * @name $cacheFactory.Cache
  5224. *
  5225. * @description
  5226. * A cache object used to store and retrieve data, primarily used by
  5227. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5228. * templates and other data.
  5229. *
  5230. * ```js
  5231. * angular.module('superCache')
  5232. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5233. * return $cacheFactory('super-cache');
  5234. * }]);
  5235. * ```
  5236. *
  5237. * Example test:
  5238. *
  5239. * ```js
  5240. * it('should behave like a cache', inject(function(superCache) {
  5241. * superCache.put('key', 'value');
  5242. * superCache.put('another key', 'another value');
  5243. *
  5244. * expect(superCache.info()).toEqual({
  5245. * id: 'super-cache',
  5246. * size: 2
  5247. * });
  5248. *
  5249. * superCache.remove('another key');
  5250. * expect(superCache.get('another key')).toBeUndefined();
  5251. *
  5252. * superCache.removeAll();
  5253. * expect(superCache.info()).toEqual({
  5254. * id: 'super-cache',
  5255. * size: 0
  5256. * });
  5257. * }));
  5258. * ```
  5259. */
  5260. return caches[cacheId] = {
  5261. /**
  5262. * @ngdoc method
  5263. * @name $cacheFactory.Cache#put
  5264. * @kind function
  5265. *
  5266. * @description
  5267. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5268. * retrieved later, and incrementing the size of the cache if the key was not already
  5269. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5270. * entries from the set.
  5271. *
  5272. * It will not insert undefined values into the cache.
  5273. *
  5274. * @param {string} key the key under which the cached data is stored.
  5275. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5276. * will not be stored.
  5277. * @returns {*} the value stored.
  5278. */
  5279. put: function(key, value) {
  5280. if (isUndefined(value)) return;
  5281. if (capacity < Number.MAX_VALUE) {
  5282. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5283. refresh(lruEntry);
  5284. }
  5285. if (!(key in data)) size++;
  5286. data[key] = value;
  5287. if (size > capacity) {
  5288. this.remove(staleEnd.key);
  5289. }
  5290. return value;
  5291. },
  5292. /**
  5293. * @ngdoc method
  5294. * @name $cacheFactory.Cache#get
  5295. * @kind function
  5296. *
  5297. * @description
  5298. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5299. *
  5300. * @param {string} key the key of the data to be retrieved
  5301. * @returns {*} the value stored.
  5302. */
  5303. get: function(key) {
  5304. if (capacity < Number.MAX_VALUE) {
  5305. var lruEntry = lruHash[key];
  5306. if (!lruEntry) return;
  5307. refresh(lruEntry);
  5308. }
  5309. return data[key];
  5310. },
  5311. /**
  5312. * @ngdoc method
  5313. * @name $cacheFactory.Cache#remove
  5314. * @kind function
  5315. *
  5316. * @description
  5317. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5318. *
  5319. * @param {string} key the key of the entry to be removed
  5320. */
  5321. remove: function(key) {
  5322. if (capacity < Number.MAX_VALUE) {
  5323. var lruEntry = lruHash[key];
  5324. if (!lruEntry) return;
  5325. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5326. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5327. link(lruEntry.n,lruEntry.p);
  5328. delete lruHash[key];
  5329. }
  5330. delete data[key];
  5331. size--;
  5332. },
  5333. /**
  5334. * @ngdoc method
  5335. * @name $cacheFactory.Cache#removeAll
  5336. * @kind function
  5337. *
  5338. * @description
  5339. * Clears the cache object of any entries.
  5340. */
  5341. removeAll: function() {
  5342. data = {};
  5343. size = 0;
  5344. lruHash = {};
  5345. freshEnd = staleEnd = null;
  5346. },
  5347. /**
  5348. * @ngdoc method
  5349. * @name $cacheFactory.Cache#destroy
  5350. * @kind function
  5351. *
  5352. * @description
  5353. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5354. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5355. */
  5356. destroy: function() {
  5357. data = null;
  5358. stats = null;
  5359. lruHash = null;
  5360. delete caches[cacheId];
  5361. },
  5362. /**
  5363. * @ngdoc method
  5364. * @name $cacheFactory.Cache#info
  5365. * @kind function
  5366. *
  5367. * @description
  5368. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5369. *
  5370. * @returns {object} an object with the following properties:
  5371. * <ul>
  5372. * <li>**id**: the id of the cache instance</li>
  5373. * <li>**size**: the number of entries kept in the cache instance</li>
  5374. * <li>**...**: any additional properties from the options object when creating the
  5375. * cache.</li>
  5376. * </ul>
  5377. */
  5378. info: function() {
  5379. return extend({}, stats, {size: size});
  5380. }
  5381. };
  5382. /**
  5383. * makes the `entry` the freshEnd of the LRU linked list
  5384. */
  5385. function refresh(entry) {
  5386. if (entry != freshEnd) {
  5387. if (!staleEnd) {
  5388. staleEnd = entry;
  5389. } else if (staleEnd == entry) {
  5390. staleEnd = entry.n;
  5391. }
  5392. link(entry.n, entry.p);
  5393. link(entry, freshEnd);
  5394. freshEnd = entry;
  5395. freshEnd.n = null;
  5396. }
  5397. }
  5398. /**
  5399. * bidirectionally links two entries of the LRU linked list
  5400. */
  5401. function link(nextEntry, prevEntry) {
  5402. if (nextEntry != prevEntry) {
  5403. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5404. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5405. }
  5406. }
  5407. }
  5408. /**
  5409. * @ngdoc method
  5410. * @name $cacheFactory#info
  5411. *
  5412. * @description
  5413. * Get information about all the caches that have been created
  5414. *
  5415. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5416. */
  5417. cacheFactory.info = function() {
  5418. var info = {};
  5419. forEach(caches, function(cache, cacheId) {
  5420. info[cacheId] = cache.info();
  5421. });
  5422. return info;
  5423. };
  5424. /**
  5425. * @ngdoc method
  5426. * @name $cacheFactory#get
  5427. *
  5428. * @description
  5429. * Get access to a cache object by the `cacheId` used when it was created.
  5430. *
  5431. * @param {string} cacheId Name or id of a cache to access.
  5432. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5433. */
  5434. cacheFactory.get = function(cacheId) {
  5435. return caches[cacheId];
  5436. };
  5437. return cacheFactory;
  5438. };
  5439. }
  5440. /**
  5441. * @ngdoc service
  5442. * @name $templateCache
  5443. *
  5444. * @description
  5445. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5446. * can load templates directly into the cache in a `script` tag, or by consuming the
  5447. * `$templateCache` service directly.
  5448. *
  5449. * Adding via the `script` tag:
  5450. *
  5451. * ```html
  5452. * <script type="text/ng-template" id="templateId.html">
  5453. * <p>This is the content of the template</p>
  5454. * </script>
  5455. * ```
  5456. *
  5457. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5458. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5459. * element with ng-app attribute), otherwise the template will be ignored.
  5460. *
  5461. * Adding via the `$templateCache` service:
  5462. *
  5463. * ```js
  5464. * var myApp = angular.module('myApp', []);
  5465. * myApp.run(function($templateCache) {
  5466. * $templateCache.put('templateId.html', 'This is the content of the template');
  5467. * });
  5468. * ```
  5469. *
  5470. * To retrieve the template later, simply use it in your HTML:
  5471. * ```html
  5472. * <div ng-include=" 'templateId.html' "></div>
  5473. * ```
  5474. *
  5475. * or get it via Javascript:
  5476. * ```js
  5477. * $templateCache.get('templateId.html')
  5478. * ```
  5479. *
  5480. * See {@link ng.$cacheFactory $cacheFactory}.
  5481. *
  5482. */
  5483. function $TemplateCacheProvider() {
  5484. this.$get = ['$cacheFactory', function($cacheFactory) {
  5485. return $cacheFactory('templates');
  5486. }];
  5487. }
  5488. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5489. * Any commits to this file should be reviewed with security in mind. *
  5490. * Changes to this file can potentially create security vulnerabilities. *
  5491. * An approval from 2 Core members with history of modifying *
  5492. * this file is required. *
  5493. * *
  5494. * Does the change somehow allow for arbitrary javascript to be executed? *
  5495. * Or allows for someone to change the prototype of built-in objects? *
  5496. * Or gives undesired access to variables likes document or window? *
  5497. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5498. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5499. *
  5500. * DOM-related variables:
  5501. *
  5502. * - "node" - DOM Node
  5503. * - "element" - DOM Element or Node
  5504. * - "$node" or "$element" - jqLite-wrapped node or element
  5505. *
  5506. *
  5507. * Compiler related stuff:
  5508. *
  5509. * - "linkFn" - linking fn of a single directive
  5510. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5511. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5512. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5513. */
  5514. /**
  5515. * @ngdoc service
  5516. * @name $compile
  5517. * @kind function
  5518. *
  5519. * @description
  5520. * Compiles an HTML string or DOM into a template and produces a template function, which
  5521. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5522. *
  5523. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5524. * {@link ng.$compileProvider#directive directives}.
  5525. *
  5526. * <div class="alert alert-warning">
  5527. * **Note:** This document is an in-depth reference of all directive options.
  5528. * For a gentle introduction to directives with examples of common use cases,
  5529. * see the {@link guide/directive directive guide}.
  5530. * </div>
  5531. *
  5532. * ## Comprehensive Directive API
  5533. *
  5534. * There are many different options for a directive.
  5535. *
  5536. * The difference resides in the return value of the factory function.
  5537. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5538. * or just the `postLink` function (all other properties will have the default values).
  5539. *
  5540. * <div class="alert alert-success">
  5541. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5542. * </div>
  5543. *
  5544. * Here's an example directive declared with a Directive Definition Object:
  5545. *
  5546. * ```js
  5547. * var myModule = angular.module(...);
  5548. *
  5549. * myModule.directive('directiveName', function factory(injectables) {
  5550. * var directiveDefinitionObject = {
  5551. * priority: 0,
  5552. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5553. * // or
  5554. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5555. * transclude: false,
  5556. * restrict: 'A',
  5557. * templateNamespace: 'html',
  5558. * scope: false,
  5559. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5560. * controllerAs: 'stringIdentifier',
  5561. * bindToController: false,
  5562. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5563. * compile: function compile(tElement, tAttrs, transclude) {
  5564. * return {
  5565. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5566. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5567. * }
  5568. * // or
  5569. * // return function postLink( ... ) { ... }
  5570. * },
  5571. * // or
  5572. * // link: {
  5573. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5574. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5575. * // }
  5576. * // or
  5577. * // link: function postLink( ... ) { ... }
  5578. * };
  5579. * return directiveDefinitionObject;
  5580. * });
  5581. * ```
  5582. *
  5583. * <div class="alert alert-warning">
  5584. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5585. * </div>
  5586. *
  5587. * Therefore the above can be simplified as:
  5588. *
  5589. * ```js
  5590. * var myModule = angular.module(...);
  5591. *
  5592. * myModule.directive('directiveName', function factory(injectables) {
  5593. * var directiveDefinitionObject = {
  5594. * link: function postLink(scope, iElement, iAttrs) { ... }
  5595. * };
  5596. * return directiveDefinitionObject;
  5597. * // or
  5598. * // return function postLink(scope, iElement, iAttrs) { ... }
  5599. * });
  5600. * ```
  5601. *
  5602. *
  5603. *
  5604. * ### Directive Definition Object
  5605. *
  5606. * The directive definition object provides instructions to the {@link ng.$compile
  5607. * compiler}. The attributes are:
  5608. *
  5609. * #### `multiElement`
  5610. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5611. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5612. * together as the directive elements. It is recommended that this feature be used on directives
  5613. * which are not strictly behavioural (such as {@link ngClick}), and which
  5614. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5615. *
  5616. * #### `priority`
  5617. * When there are multiple directives defined on a single DOM element, sometimes it
  5618. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5619. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5620. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5621. * are also run in priority order, but post-link functions are run in reverse order. The order
  5622. * of directives with the same priority is undefined. The default priority is `0`.
  5623. *
  5624. * #### `terminal`
  5625. * If set to true then the current `priority` will be the last set of directives
  5626. * which will execute (any directives at the current priority will still execute
  5627. * as the order of execution on same `priority` is undefined). Note that expressions
  5628. * and other directives used in the directive's template will also be excluded from execution.
  5629. *
  5630. * #### `scope`
  5631. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5632. * same element request a new scope, only one new scope is created. The new scope rule does not
  5633. * apply for the root of the template since the root of the template always gets a new scope.
  5634. *
  5635. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5636. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5637. * when creating reusable components, which should not accidentally read or modify data in the
  5638. * parent scope.
  5639. *
  5640. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5641. * derived from the parent scope. These local properties are useful for aliasing values for
  5642. * templates. Locals definition is a hash of local scope property to its source:
  5643. *
  5644. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5645. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5646. * attribute name is assumed to be the same as the local name.
  5647. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5648. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5649. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5650. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5651. * component scope).
  5652. *
  5653. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5654. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5655. * name is specified then the attribute name is assumed to be the same as the local name.
  5656. * Given `<widget my-attr="parentModel">` and widget definition of
  5657. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5658. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5659. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5660. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5661. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5662. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5663. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5664. *
  5665. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5666. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5667. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5668. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5669. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5670. * pass data from the isolated scope via an expression to the parent scope, this can be
  5671. * done by passing a map of local variable names and values into the expression wrapper fn.
  5672. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5673. * by calling the `localFn` as `localFn({amount: 22})`.
  5674. *
  5675. *
  5676. * #### `bindToController`
  5677. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5678. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5679. * is instantiated, the initial values of the isolate scope bindings are already available.
  5680. *
  5681. * #### `controller`
  5682. * Controller constructor function. The controller is instantiated before the
  5683. * pre-linking phase and it is shared with other directives (see
  5684. * `require` attribute). This allows the directives to communicate with each other and augment
  5685. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5686. *
  5687. * * `$scope` - Current scope associated with the element
  5688. * * `$element` - Current element
  5689. * * `$attrs` - Current attributes object for the element
  5690. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5691. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5692. * * `scope`: optional argument to override the scope.
  5693. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5694. * * `futureParentElement`:
  5695. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5696. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5697. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5698. * and when the `cloneLinkinFn` is passed,
  5699. * as those elements need to created and cloned in a special way when they are defined outside their
  5700. * usual containers (e.g. like `<svg>`).
  5701. * * See also the `directive.templateNamespace` property.
  5702. *
  5703. *
  5704. * #### `require`
  5705. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5706. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5707. * injected argument will be an array in corresponding order. If no such directive can be
  5708. * found, or if the directive does not have a controller, then an error is raised (unless no link function
  5709. * is specified, in which case error checking is skipped). The name can be prefixed with:
  5710. *
  5711. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5712. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5713. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5714. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5715. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5716. * `null` to the `link` fn if not found.
  5717. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5718. * `null` to the `link` fn if not found.
  5719. *
  5720. *
  5721. * #### `controllerAs`
  5722. * Identifier name for a reference to the controller in the directive's scope.
  5723. * This allows the controller to be referenced from the directive template. The directive
  5724. * needs to define a scope for this configuration to be used. Useful in the case when
  5725. * directive is used as component.
  5726. *
  5727. *
  5728. * #### `restrict`
  5729. * String of subset of `EACM` which restricts the directive to a specific directive
  5730. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5731. *
  5732. * * `E` - Element name (default): `<my-directive></my-directive>`
  5733. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5734. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5735. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5736. *
  5737. *
  5738. * #### `templateNamespace`
  5739. * String representing the document type used by the markup in the template.
  5740. * AngularJS needs this information as those elements need to be created and cloned
  5741. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5742. *
  5743. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5744. * top-level elements such as `<svg>` or `<math>`.
  5745. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5746. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5747. *
  5748. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5749. *
  5750. * #### `template`
  5751. * HTML markup that may:
  5752. * * Replace the contents of the directive's element (default).
  5753. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5754. * * Wrap the contents of the directive's element (if `transclude` is true).
  5755. *
  5756. * Value may be:
  5757. *
  5758. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5759. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5760. * function api below) and returns a string value.
  5761. *
  5762. *
  5763. * #### `templateUrl`
  5764. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5765. *
  5766. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5767. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5768. * sibling and parent elements as though this element had not contained any directives.
  5769. *
  5770. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5771. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5772. * case when only one deeply nested directive has `templateUrl`.
  5773. *
  5774. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5775. *
  5776. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5777. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5778. * a string value representing the url. In either case, the template URL is passed through {@link
  5779. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5780. *
  5781. *
  5782. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5783. * specify what the template should replace. Defaults to `false`.
  5784. *
  5785. * * `true` - the template will replace the directive's element.
  5786. * * `false` - the template will replace the contents of the directive's element.
  5787. *
  5788. * The replacement process migrates all of the attributes / classes from the old element to the new
  5789. * one. See the {@link guide/directive#template-expanding-directive
  5790. * Directives Guide} for an example.
  5791. *
  5792. * There are very few scenarios where element replacement is required for the application function,
  5793. * the main one being reusable custom components that are used within SVG contexts
  5794. * (because SVG doesn't work with custom elements in the DOM tree).
  5795. *
  5796. * #### `transclude`
  5797. * Extract the contents of the element where the directive appears and make it available to the directive.
  5798. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5799. * {@link $compile#transclusion Transclusion} section below.
  5800. *
  5801. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5802. * directive's element or the entire element:
  5803. *
  5804. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5805. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5806. * element that defined at a lower priority than this directive. When used, the `template`
  5807. * property is ignored.
  5808. *
  5809. *
  5810. * #### `compile`
  5811. *
  5812. * ```js
  5813. * function compile(tElement, tAttrs, transclude) { ... }
  5814. * ```
  5815. *
  5816. * The compile function deals with transforming the template DOM. Since most directives do not do
  5817. * template transformation, it is not used often. The compile function takes the following arguments:
  5818. *
  5819. * * `tElement` - template element - The element where the directive has been declared. It is
  5820. * safe to do template transformation on the element and child elements only.
  5821. *
  5822. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5823. * between all directive compile functions.
  5824. *
  5825. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5826. *
  5827. * <div class="alert alert-warning">
  5828. * **Note:** The template instance and the link instance may be different objects if the template has
  5829. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5830. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5831. * should be done in a linking function rather than in a compile function.
  5832. * </div>
  5833. * <div class="alert alert-warning">
  5834. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5835. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5836. * stack overflow errors.
  5837. *
  5838. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5839. * a directive's template instead of relying on automatic template compilation via `template` or
  5840. * `templateUrl` declaration or manual compilation inside the compile function.
  5841. * </div>
  5842. *
  5843. * <div class="alert alert-danger">
  5844. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5845. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5846. * to the link function instead.
  5847. * </div>
  5848. * A compile function can have a return value which can be either a function or an object.
  5849. *
  5850. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5851. * `link` property of the config object when the compile function is empty.
  5852. *
  5853. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5854. * control when a linking function should be called during the linking phase. See info about
  5855. * pre-linking and post-linking functions below.
  5856. *
  5857. *
  5858. * #### `link`
  5859. * This property is used only if the `compile` property is not defined.
  5860. *
  5861. * ```js
  5862. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5863. * ```
  5864. *
  5865. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5866. * executed after the template has been cloned. This is where most of the directive logic will be
  5867. * put.
  5868. *
  5869. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5870. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5871. *
  5872. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5873. * manipulate the children of the element only in `postLink` function since the children have
  5874. * already been linked.
  5875. *
  5876. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5877. * between all directive linking functions.
  5878. *
  5879. * * `controller` - the directive's required controller instance(s) - Instances are shared
  5880. * among all directives, which allows the directives to use the controllers as a communication
  5881. * channel. The exact value depends on the directive's `require` property:
  5882. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  5883. * * `string`: the controller instance
  5884. * * `array`: array of controller instances
  5885. *
  5886. * If a required controller cannot be found, and it is optional, the instance is `null`,
  5887. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  5888. *
  5889. * Note that you can also require the directive's own controller - it will be made available like
  5890. * like any other controller.
  5891. *
  5892. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5893. * This is the same as the `$transclude`
  5894. * parameter of directive controllers, see there for details.
  5895. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5896. *
  5897. * #### Pre-linking function
  5898. *
  5899. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5900. * compiler linking function will fail to locate the correct elements for linking.
  5901. *
  5902. * #### Post-linking function
  5903. *
  5904. * Executed after the child elements are linked.
  5905. *
  5906. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5907. * and linked since they are waiting for their template to load asynchronously and their own
  5908. * compilation and linking has been suspended until that occurs.
  5909. *
  5910. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  5911. * for their async templates to be resolved.
  5912. *
  5913. *
  5914. * ### Transclusion
  5915. *
  5916. * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
  5917. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  5918. * scope from where they were taken.
  5919. *
  5920. * Transclusion is used (often with {@link ngTransclude}) to insert the
  5921. * original contents of a directive's element into a specified place in the template of the directive.
  5922. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  5923. * content has access to the properties on the scope from which it was taken, even if the directive
  5924. * has isolated scope.
  5925. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  5926. *
  5927. * This makes it possible for the widget to have private state for its template, while the transcluded
  5928. * content has access to its originating scope.
  5929. *
  5930. * <div class="alert alert-warning">
  5931. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  5932. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  5933. * Testing Transclusion Directives}.
  5934. * </div>
  5935. *
  5936. * #### Transclusion Functions
  5937. *
  5938. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  5939. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  5940. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  5941. *
  5942. * <div class="alert alert-info">
  5943. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  5944. * ngTransclude will deal with it for us.
  5945. * </div>
  5946. *
  5947. * If you want to manually control the insertion and removal of the transcluded content in your directive
  5948. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  5949. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  5950. *
  5951. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  5952. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  5953. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  5954. *
  5955. * <div class="alert alert-info">
  5956. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  5957. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  5958. * </div>
  5959. *
  5960. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  5961. * attach function**:
  5962. *
  5963. * ```js
  5964. * var transcludedContent, transclusionScope;
  5965. *
  5966. * $transclude(function(clone, scope) {
  5967. * element.append(clone);
  5968. * transcludedContent = clone;
  5969. * transclusionScope = scope;
  5970. * });
  5971. * ```
  5972. *
  5973. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  5974. * associated transclusion scope:
  5975. *
  5976. * ```js
  5977. * transcludedContent.remove();
  5978. * transclusionScope.$destroy();
  5979. * ```
  5980. *
  5981. * <div class="alert alert-info">
  5982. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  5983. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  5984. * then you are also responsible for calling `$destroy` on the transclusion scope.
  5985. * </div>
  5986. *
  5987. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  5988. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  5989. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  5990. *
  5991. *
  5992. * #### Transclusion Scopes
  5993. *
  5994. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  5995. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  5996. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  5997. * was taken.
  5998. *
  5999. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6000. * like this:
  6001. *
  6002. * ```html
  6003. * <div ng-app>
  6004. * <div isolate>
  6005. * <div transclusion>
  6006. * </div>
  6007. * </div>
  6008. * </div>
  6009. * ```
  6010. *
  6011. * The `$parent` scope hierarchy will look like this:
  6012. *
  6013. * ```
  6014. * - $rootScope
  6015. * - isolate
  6016. * - transclusion
  6017. * ```
  6018. *
  6019. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6020. *
  6021. * ```
  6022. * - $rootScope
  6023. * - transclusion
  6024. * - isolate
  6025. * ```
  6026. *
  6027. *
  6028. * ### Attributes
  6029. *
  6030. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6031. * `link()` or `compile()` functions. It has a variety of uses.
  6032. *
  6033. * accessing *Normalized attribute names:*
  6034. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  6035. * the attributes object allows for normalized access to
  6036. * the attributes.
  6037. *
  6038. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6039. * object which allows the directives to use the attributes object as inter directive
  6040. * communication.
  6041. *
  6042. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6043. * allowing other directives to read the interpolated value.
  6044. *
  6045. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6046. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6047. * the only way to easily get the actual value because during the linking phase the interpolation
  6048. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6049. *
  6050. * ```js
  6051. * function linkingFn(scope, elm, attrs, ctrl) {
  6052. * // get the attribute value
  6053. * console.log(attrs.ngModel);
  6054. *
  6055. * // change the attribute
  6056. * attrs.$set('ngModel', 'new value');
  6057. *
  6058. * // observe changes to interpolated attribute
  6059. * attrs.$observe('ngModel', function(value) {
  6060. * console.log('ngModel has changed value to ' + value);
  6061. * });
  6062. * }
  6063. * ```
  6064. *
  6065. * ## Example
  6066. *
  6067. * <div class="alert alert-warning">
  6068. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6069. * to illustrate how `$compile` works.
  6070. * </div>
  6071. *
  6072. <example module="compileExample">
  6073. <file name="index.html">
  6074. <script>
  6075. angular.module('compileExample', [], function($compileProvider) {
  6076. // configure new 'compile' directive by passing a directive
  6077. // factory function. The factory function injects the '$compile'
  6078. $compileProvider.directive('compile', function($compile) {
  6079. // directive factory creates a link function
  6080. return function(scope, element, attrs) {
  6081. scope.$watch(
  6082. function(scope) {
  6083. // watch the 'compile' expression for changes
  6084. return scope.$eval(attrs.compile);
  6085. },
  6086. function(value) {
  6087. // when the 'compile' expression changes
  6088. // assign it into the current DOM
  6089. element.html(value);
  6090. // compile the new DOM and link it to the current
  6091. // scope.
  6092. // NOTE: we only compile .childNodes so that
  6093. // we don't get into infinite loop compiling ourselves
  6094. $compile(element.contents())(scope);
  6095. }
  6096. );
  6097. };
  6098. });
  6099. })
  6100. .controller('GreeterController', ['$scope', function($scope) {
  6101. $scope.name = 'Angular';
  6102. $scope.html = 'Hello {{name}}';
  6103. }]);
  6104. </script>
  6105. <div ng-controller="GreeterController">
  6106. <input ng-model="name"> <br/>
  6107. <textarea ng-model="html"></textarea> <br/>
  6108. <div compile="html"></div>
  6109. </div>
  6110. </file>
  6111. <file name="protractor.js" type="protractor">
  6112. it('should auto compile', function() {
  6113. var textarea = $('textarea');
  6114. var output = $('div[compile]');
  6115. // The initial state reads 'Hello Angular'.
  6116. expect(output.getText()).toBe('Hello Angular');
  6117. textarea.clear();
  6118. textarea.sendKeys('{{name}}!');
  6119. expect(output.getText()).toBe('Angular!');
  6120. });
  6121. </file>
  6122. </example>
  6123. *
  6124. *
  6125. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6126. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6127. *
  6128. * <div class="alert alert-danger">
  6129. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6130. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6131. * `parentBoundTranscludeFn` to the link function instead.
  6132. * </div>
  6133. *
  6134. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6135. * root element(s), not their children)
  6136. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6137. * (a DOM element/tree) to a scope. Where:
  6138. *
  6139. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6140. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6141. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6142. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6143. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6144. *
  6145. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6146. * * `scope` - is the current scope with which the linking function is working with.
  6147. *
  6148. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6149. * keys may be used to control linking behavior:
  6150. *
  6151. * * `parentBoundTranscludeFn` - the transclude function made available to
  6152. * directives; if given, it will be passed through to the link functions of
  6153. * directives found in `element` during compilation.
  6154. * * `transcludeControllers` - an object hash with keys that map controller names
  6155. * to controller instances; if given, it will make the controllers
  6156. * available to directives.
  6157. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6158. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6159. * elements (e.g. SVG elements). See also the directive.controller property.
  6160. *
  6161. * Calling the linking function returns the element of the template. It is either the original
  6162. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6163. *
  6164. * After linking the view is not updated until after a call to $digest which typically is done by
  6165. * Angular automatically.
  6166. *
  6167. * If you need access to the bound view, there are two ways to do it:
  6168. *
  6169. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6170. * before you send them to the compiler and keep this reference around.
  6171. * ```js
  6172. * var element = $compile('<p>{{total}}</p>')(scope);
  6173. * ```
  6174. *
  6175. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6176. * example would not point to the clone, but rather to the original template that was cloned. In
  6177. * this case, you can access the clone via the cloneAttachFn:
  6178. * ```js
  6179. * var templateElement = angular.element('<p>{{total}}</p>'),
  6180. * scope = ....;
  6181. *
  6182. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6183. * //attach the clone to DOM document at the right place
  6184. * });
  6185. *
  6186. * //now we have reference to the cloned DOM via `clonedElement`
  6187. * ```
  6188. *
  6189. *
  6190. * For information on how the compiler works, see the
  6191. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6192. */
  6193. var $compileMinErr = minErr('$compile');
  6194. /**
  6195. * @ngdoc provider
  6196. * @name $compileProvider
  6197. *
  6198. * @description
  6199. */
  6200. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6201. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6202. var hasDirectives = {},
  6203. Suffix = 'Directive',
  6204. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6205. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6206. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6207. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6208. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6209. // The assumption is that future DOM event attribute names will begin with
  6210. // 'on' and be composed of only English letters.
  6211. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6212. function parseIsolateBindings(scope, directiveName, isController) {
  6213. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  6214. var bindings = {};
  6215. forEach(scope, function(definition, scopeName) {
  6216. var match = definition.match(LOCAL_REGEXP);
  6217. if (!match) {
  6218. throw $compileMinErr('iscp',
  6219. "Invalid {3} for directive '{0}'." +
  6220. " Definition: {... {1}: '{2}' ...}",
  6221. directiveName, scopeName, definition,
  6222. (isController ? "controller bindings definition" :
  6223. "isolate scope definition"));
  6224. }
  6225. bindings[scopeName] = {
  6226. mode: match[1][0],
  6227. collection: match[2] === '*',
  6228. optional: match[3] === '?',
  6229. attrName: match[4] || scopeName
  6230. };
  6231. });
  6232. return bindings;
  6233. }
  6234. function parseDirectiveBindings(directive, directiveName) {
  6235. var bindings = {
  6236. isolateScope: null,
  6237. bindToController: null
  6238. };
  6239. if (isObject(directive.scope)) {
  6240. if (directive.bindToController === true) {
  6241. bindings.bindToController = parseIsolateBindings(directive.scope,
  6242. directiveName, true);
  6243. bindings.isolateScope = {};
  6244. } else {
  6245. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6246. directiveName, false);
  6247. }
  6248. }
  6249. if (isObject(directive.bindToController)) {
  6250. bindings.bindToController =
  6251. parseIsolateBindings(directive.bindToController, directiveName, true);
  6252. }
  6253. if (isObject(bindings.bindToController)) {
  6254. var controller = directive.controller;
  6255. var controllerAs = directive.controllerAs;
  6256. if (!controller) {
  6257. // There is no controller, there may or may not be a controllerAs property
  6258. throw $compileMinErr('noctrl',
  6259. "Cannot bind to controller without directive '{0}'s controller.",
  6260. directiveName);
  6261. } else if (!identifierForController(controller, controllerAs)) {
  6262. // There is a controller, but no identifier or controllerAs property
  6263. throw $compileMinErr('noident',
  6264. "Cannot bind to controller without identifier for directive '{0}'.",
  6265. directiveName);
  6266. }
  6267. }
  6268. return bindings;
  6269. }
  6270. function assertValidDirectiveName(name) {
  6271. var letter = name.charAt(0);
  6272. if (!letter || letter !== lowercase(letter)) {
  6273. throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
  6274. }
  6275. if (name !== name.trim()) {
  6276. throw $compileMinErr('baddir',
  6277. "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6278. name);
  6279. }
  6280. }
  6281. /**
  6282. * @ngdoc method
  6283. * @name $compileProvider#directive
  6284. * @kind function
  6285. *
  6286. * @description
  6287. * Register a new directive with the compiler.
  6288. *
  6289. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6290. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6291. * names and the values are the factories.
  6292. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  6293. * {@link guide/directive} for more info.
  6294. * @returns {ng.$compileProvider} Self for chaining.
  6295. */
  6296. this.directive = function registerDirective(name, directiveFactory) {
  6297. assertNotHasOwnProperty(name, 'directive');
  6298. if (isString(name)) {
  6299. assertValidDirectiveName(name);
  6300. assertArg(directiveFactory, 'directiveFactory');
  6301. if (!hasDirectives.hasOwnProperty(name)) {
  6302. hasDirectives[name] = [];
  6303. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6304. function($injector, $exceptionHandler) {
  6305. var directives = [];
  6306. forEach(hasDirectives[name], function(directiveFactory, index) {
  6307. try {
  6308. var directive = $injector.invoke(directiveFactory);
  6309. if (isFunction(directive)) {
  6310. directive = { compile: valueFn(directive) };
  6311. } else if (!directive.compile && directive.link) {
  6312. directive.compile = valueFn(directive.link);
  6313. }
  6314. directive.priority = directive.priority || 0;
  6315. directive.index = index;
  6316. directive.name = directive.name || name;
  6317. directive.require = directive.require || (directive.controller && directive.name);
  6318. directive.restrict = directive.restrict || 'EA';
  6319. var bindings = directive.$$bindings =
  6320. parseDirectiveBindings(directive, directive.name);
  6321. if (isObject(bindings.isolateScope)) {
  6322. directive.$$isolateBindings = bindings.isolateScope;
  6323. }
  6324. directive.$$moduleName = directiveFactory.$$moduleName;
  6325. directives.push(directive);
  6326. } catch (e) {
  6327. $exceptionHandler(e);
  6328. }
  6329. });
  6330. return directives;
  6331. }]);
  6332. }
  6333. hasDirectives[name].push(directiveFactory);
  6334. } else {
  6335. forEach(name, reverseParams(registerDirective));
  6336. }
  6337. return this;
  6338. };
  6339. /**
  6340. * @ngdoc method
  6341. * @name $compileProvider#aHrefSanitizationWhitelist
  6342. * @kind function
  6343. *
  6344. * @description
  6345. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6346. * urls during a[href] sanitization.
  6347. *
  6348. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  6349. *
  6350. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  6351. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  6352. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6353. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6354. *
  6355. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6356. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6357. * chaining otherwise.
  6358. */
  6359. this.aHrefSanitizationWhitelist = function(regexp) {
  6360. if (isDefined(regexp)) {
  6361. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  6362. return this;
  6363. } else {
  6364. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  6365. }
  6366. };
  6367. /**
  6368. * @ngdoc method
  6369. * @name $compileProvider#imgSrcSanitizationWhitelist
  6370. * @kind function
  6371. *
  6372. * @description
  6373. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6374. * urls during img[src] sanitization.
  6375. *
  6376. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6377. *
  6378. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  6379. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  6380. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6381. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6382. *
  6383. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6384. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6385. * chaining otherwise.
  6386. */
  6387. this.imgSrcSanitizationWhitelist = function(regexp) {
  6388. if (isDefined(regexp)) {
  6389. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  6390. return this;
  6391. } else {
  6392. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  6393. }
  6394. };
  6395. /**
  6396. * @ngdoc method
  6397. * @name $compileProvider#debugInfoEnabled
  6398. *
  6399. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6400. * current debugInfoEnabled state
  6401. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  6402. *
  6403. * @kind function
  6404. *
  6405. * @description
  6406. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  6407. * binding information and a reference to the current scope on to DOM elements.
  6408. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  6409. * * `ng-binding` CSS class
  6410. * * `$binding` data property containing an array of the binding expressions
  6411. *
  6412. * You may want to disable this in production for a significant performance boost. See
  6413. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  6414. *
  6415. * The default value is true.
  6416. */
  6417. var debugInfoEnabled = true;
  6418. this.debugInfoEnabled = function(enabled) {
  6419. if (isDefined(enabled)) {
  6420. debugInfoEnabled = enabled;
  6421. return this;
  6422. }
  6423. return debugInfoEnabled;
  6424. };
  6425. this.$get = [
  6426. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6427. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6428. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6429. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6430. var Attributes = function(element, attributesToCopy) {
  6431. if (attributesToCopy) {
  6432. var keys = Object.keys(attributesToCopy);
  6433. var i, l, key;
  6434. for (i = 0, l = keys.length; i < l; i++) {
  6435. key = keys[i];
  6436. this[key] = attributesToCopy[key];
  6437. }
  6438. } else {
  6439. this.$attr = {};
  6440. }
  6441. this.$$element = element;
  6442. };
  6443. Attributes.prototype = {
  6444. /**
  6445. * @ngdoc method
  6446. * @name $compile.directive.Attributes#$normalize
  6447. * @kind function
  6448. *
  6449. * @description
  6450. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6451. * `data-`) to its normalized, camelCase form.
  6452. *
  6453. * Also there is special case for Moz prefix starting with upper case letter.
  6454. *
  6455. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6456. *
  6457. * @param {string} name Name to normalize
  6458. */
  6459. $normalize: directiveNormalize,
  6460. /**
  6461. * @ngdoc method
  6462. * @name $compile.directive.Attributes#$addClass
  6463. * @kind function
  6464. *
  6465. * @description
  6466. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6467. * are enabled then an animation will be triggered for the class addition.
  6468. *
  6469. * @param {string} classVal The className value that will be added to the element
  6470. */
  6471. $addClass: function(classVal) {
  6472. if (classVal && classVal.length > 0) {
  6473. $animate.addClass(this.$$element, classVal);
  6474. }
  6475. },
  6476. /**
  6477. * @ngdoc method
  6478. * @name $compile.directive.Attributes#$removeClass
  6479. * @kind function
  6480. *
  6481. * @description
  6482. * Removes the CSS class value specified by the classVal parameter from the element. If
  6483. * animations are enabled then an animation will be triggered for the class removal.
  6484. *
  6485. * @param {string} classVal The className value that will be removed from the element
  6486. */
  6487. $removeClass: function(classVal) {
  6488. if (classVal && classVal.length > 0) {
  6489. $animate.removeClass(this.$$element, classVal);
  6490. }
  6491. },
  6492. /**
  6493. * @ngdoc method
  6494. * @name $compile.directive.Attributes#$updateClass
  6495. * @kind function
  6496. *
  6497. * @description
  6498. * Adds and removes the appropriate CSS class values to the element based on the difference
  6499. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6500. *
  6501. * @param {string} newClasses The current CSS className value
  6502. * @param {string} oldClasses The former CSS className value
  6503. */
  6504. $updateClass: function(newClasses, oldClasses) {
  6505. var toAdd = tokenDifference(newClasses, oldClasses);
  6506. if (toAdd && toAdd.length) {
  6507. $animate.addClass(this.$$element, toAdd);
  6508. }
  6509. var toRemove = tokenDifference(oldClasses, newClasses);
  6510. if (toRemove && toRemove.length) {
  6511. $animate.removeClass(this.$$element, toRemove);
  6512. }
  6513. },
  6514. /**
  6515. * Set a normalized attribute on the element in a way such that all directives
  6516. * can share the attribute. This function properly handles boolean attributes.
  6517. * @param {string} key Normalized key. (ie ngAttribute)
  6518. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6519. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6520. * Defaults to true.
  6521. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6522. */
  6523. $set: function(key, value, writeAttr, attrName) {
  6524. // TODO: decide whether or not to throw an error if "class"
  6525. //is set through this function since it may cause $updateClass to
  6526. //become unstable.
  6527. var node = this.$$element[0],
  6528. booleanKey = getBooleanAttrName(node, key),
  6529. aliasedKey = getAliasedAttrName(node, key),
  6530. observer = key,
  6531. nodeName;
  6532. if (booleanKey) {
  6533. this.$$element.prop(key, value);
  6534. attrName = booleanKey;
  6535. } else if (aliasedKey) {
  6536. this[aliasedKey] = value;
  6537. observer = aliasedKey;
  6538. }
  6539. this[key] = value;
  6540. // translate normalized key to actual key
  6541. if (attrName) {
  6542. this.$attr[key] = attrName;
  6543. } else {
  6544. attrName = this.$attr[key];
  6545. if (!attrName) {
  6546. this.$attr[key] = attrName = snake_case(key, '-');
  6547. }
  6548. }
  6549. nodeName = nodeName_(this.$$element);
  6550. if ((nodeName === 'a' && key === 'href') ||
  6551. (nodeName === 'img' && key === 'src')) {
  6552. // sanitize a[href] and img[src] values
  6553. this[key] = value = $$sanitizeUri(value, key === 'src');
  6554. } else if (nodeName === 'img' && key === 'srcset') {
  6555. // sanitize img[srcset] values
  6556. var result = "";
  6557. // first check if there are spaces because it's not the same pattern
  6558. var trimmedSrcset = trim(value);
  6559. // ( 999x ,| 999w ,| ,|, )
  6560. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6561. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6562. // split srcset into tuple of uri and descriptor except for the last item
  6563. var rawUris = trimmedSrcset.split(pattern);
  6564. // for each tuples
  6565. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6566. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6567. var innerIdx = i * 2;
  6568. // sanitize the uri
  6569. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6570. // add the descriptor
  6571. result += (" " + trim(rawUris[innerIdx + 1]));
  6572. }
  6573. // split the last item into uri and descriptor
  6574. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6575. // sanitize the last uri
  6576. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6577. // and add the last descriptor if any
  6578. if (lastTuple.length === 2) {
  6579. result += (" " + trim(lastTuple[1]));
  6580. }
  6581. this[key] = value = result;
  6582. }
  6583. if (writeAttr !== false) {
  6584. if (value === null || value === undefined) {
  6585. this.$$element.removeAttr(attrName);
  6586. } else {
  6587. this.$$element.attr(attrName, value);
  6588. }
  6589. }
  6590. // fire observers
  6591. var $$observers = this.$$observers;
  6592. $$observers && forEach($$observers[observer], function(fn) {
  6593. try {
  6594. fn(value);
  6595. } catch (e) {
  6596. $exceptionHandler(e);
  6597. }
  6598. });
  6599. },
  6600. /**
  6601. * @ngdoc method
  6602. * @name $compile.directive.Attributes#$observe
  6603. * @kind function
  6604. *
  6605. * @description
  6606. * Observes an interpolated attribute.
  6607. *
  6608. * The observer function will be invoked once during the next `$digest` following
  6609. * compilation. The observer is then invoked whenever the interpolated value
  6610. * changes.
  6611. *
  6612. * @param {string} key Normalized key. (ie ngAttribute) .
  6613. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6614. the interpolated value of the attribute changes.
  6615. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6616. * @returns {function()} Returns a deregistration function for this observer.
  6617. */
  6618. $observe: function(key, fn) {
  6619. var attrs = this,
  6620. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6621. listeners = ($$observers[key] || ($$observers[key] = []));
  6622. listeners.push(fn);
  6623. $rootScope.$evalAsync(function() {
  6624. if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
  6625. // no one registered attribute interpolation function, so lets call it manually
  6626. fn(attrs[key]);
  6627. }
  6628. });
  6629. return function() {
  6630. arrayRemove(listeners, fn);
  6631. };
  6632. }
  6633. };
  6634. function safeAddClass($element, className) {
  6635. try {
  6636. $element.addClass(className);
  6637. } catch (e) {
  6638. // ignore, since it means that we are trying to set class on
  6639. // SVG element, where class name is read-only.
  6640. }
  6641. }
  6642. var startSymbol = $interpolate.startSymbol(),
  6643. endSymbol = $interpolate.endSymbol(),
  6644. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6645. ? identity
  6646. : function denormalizeTemplate(template) {
  6647. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6648. },
  6649. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6650. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6651. var bindings = $element.data('$binding') || [];
  6652. if (isArray(binding)) {
  6653. bindings = bindings.concat(binding);
  6654. } else {
  6655. bindings.push(binding);
  6656. }
  6657. $element.data('$binding', bindings);
  6658. } : noop;
  6659. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6660. safeAddClass($element, 'ng-binding');
  6661. } : noop;
  6662. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6663. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6664. $element.data(dataName, scope);
  6665. } : noop;
  6666. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6667. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6668. } : noop;
  6669. return compile;
  6670. //================================
  6671. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6672. previousCompileContext) {
  6673. if (!($compileNodes instanceof jqLite)) {
  6674. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6675. // modify it.
  6676. $compileNodes = jqLite($compileNodes);
  6677. }
  6678. // We can not compile top level text elements since text nodes can be merged and we will
  6679. // not be able to attach scope data to them, so we will wrap them in <span>
  6680. forEach($compileNodes, function(node, index) {
  6681. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6682. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6683. }
  6684. });
  6685. var compositeLinkFn =
  6686. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6687. maxPriority, ignoreDirective, previousCompileContext);
  6688. compile.$$addScopeClass($compileNodes);
  6689. var namespace = null;
  6690. return function publicLinkFn(scope, cloneConnectFn, options) {
  6691. assertArg(scope, 'scope');
  6692. options = options || {};
  6693. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6694. transcludeControllers = options.transcludeControllers,
  6695. futureParentElement = options.futureParentElement;
  6696. // When `parentBoundTranscludeFn` is passed, it is a
  6697. // `controllersBoundTransclude` function (it was previously passed
  6698. // as `transclude` to directive.link) so we must unwrap it to get
  6699. // its `boundTranscludeFn`
  6700. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6701. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6702. }
  6703. if (!namespace) {
  6704. namespace = detectNamespaceForChildElements(futureParentElement);
  6705. }
  6706. var $linkNode;
  6707. if (namespace !== 'html') {
  6708. // When using a directive with replace:true and templateUrl the $compileNodes
  6709. // (or a child element inside of them)
  6710. // might change, so we need to recreate the namespace adapted compileNodes
  6711. // for call to the link function.
  6712. // Note: This will already clone the nodes...
  6713. $linkNode = jqLite(
  6714. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6715. );
  6716. } else if (cloneConnectFn) {
  6717. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6718. // and sometimes changes the structure of the DOM.
  6719. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6720. } else {
  6721. $linkNode = $compileNodes;
  6722. }
  6723. if (transcludeControllers) {
  6724. for (var controllerName in transcludeControllers) {
  6725. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6726. }
  6727. }
  6728. compile.$$addScopeInfo($linkNode, scope);
  6729. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6730. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6731. return $linkNode;
  6732. };
  6733. }
  6734. function detectNamespaceForChildElements(parentElement) {
  6735. // TODO: Make this detect MathML as well...
  6736. var node = parentElement && parentElement[0];
  6737. if (!node) {
  6738. return 'html';
  6739. } else {
  6740. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6741. }
  6742. }
  6743. /**
  6744. * Compile function matches each node in nodeList against the directives. Once all directives
  6745. * for a particular node are collected their compile functions are executed. The compile
  6746. * functions return values - the linking functions - are combined into a composite linking
  6747. * function, which is the a linking function for the node.
  6748. *
  6749. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6750. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6751. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6752. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6753. * the rootElement must be set the jqLite collection of the compile root. This is
  6754. * needed so that the jqLite collection items can be replaced with widgets.
  6755. * @param {number=} maxPriority Max directive priority.
  6756. * @returns {Function} A composite linking function of all of the matched directives or null.
  6757. */
  6758. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6759. previousCompileContext) {
  6760. var linkFns = [],
  6761. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6762. for (var i = 0; i < nodeList.length; i++) {
  6763. attrs = new Attributes();
  6764. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6765. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6766. ignoreDirective);
  6767. nodeLinkFn = (directives.length)
  6768. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6769. null, [], [], previousCompileContext)
  6770. : null;
  6771. if (nodeLinkFn && nodeLinkFn.scope) {
  6772. compile.$$addScopeClass(attrs.$$element);
  6773. }
  6774. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6775. !(childNodes = nodeList[i].childNodes) ||
  6776. !childNodes.length)
  6777. ? null
  6778. : compileNodes(childNodes,
  6779. nodeLinkFn ? (
  6780. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6781. && nodeLinkFn.transclude) : transcludeFn);
  6782. if (nodeLinkFn || childLinkFn) {
  6783. linkFns.push(i, nodeLinkFn, childLinkFn);
  6784. linkFnFound = true;
  6785. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6786. }
  6787. //use the previous context only for the first element in the virtual group
  6788. previousCompileContext = null;
  6789. }
  6790. // return a linking function if we have found anything, null otherwise
  6791. return linkFnFound ? compositeLinkFn : null;
  6792. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6793. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6794. var stableNodeList;
  6795. if (nodeLinkFnFound) {
  6796. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6797. // offsets don't get screwed up
  6798. var nodeListLength = nodeList.length;
  6799. stableNodeList = new Array(nodeListLength);
  6800. // create a sparse array by only copying the elements which have a linkFn
  6801. for (i = 0; i < linkFns.length; i+=3) {
  6802. idx = linkFns[i];
  6803. stableNodeList[idx] = nodeList[idx];
  6804. }
  6805. } else {
  6806. stableNodeList = nodeList;
  6807. }
  6808. for (i = 0, ii = linkFns.length; i < ii;) {
  6809. node = stableNodeList[linkFns[i++]];
  6810. nodeLinkFn = linkFns[i++];
  6811. childLinkFn = linkFns[i++];
  6812. if (nodeLinkFn) {
  6813. if (nodeLinkFn.scope) {
  6814. childScope = scope.$new();
  6815. compile.$$addScopeInfo(jqLite(node), childScope);
  6816. var destroyBindings = nodeLinkFn.$$destroyBindings;
  6817. if (destroyBindings) {
  6818. nodeLinkFn.$$destroyBindings = null;
  6819. childScope.$on('$destroyed', destroyBindings);
  6820. }
  6821. } else {
  6822. childScope = scope;
  6823. }
  6824. if (nodeLinkFn.transcludeOnThisElement) {
  6825. childBoundTranscludeFn = createBoundTranscludeFn(
  6826. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  6827. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6828. childBoundTranscludeFn = parentBoundTranscludeFn;
  6829. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6830. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6831. } else {
  6832. childBoundTranscludeFn = null;
  6833. }
  6834. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,
  6835. nodeLinkFn);
  6836. } else if (childLinkFn) {
  6837. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6838. }
  6839. }
  6840. }
  6841. }
  6842. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  6843. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6844. if (!transcludedScope) {
  6845. transcludedScope = scope.$new(false, containingScope);
  6846. transcludedScope.$$transcluded = true;
  6847. }
  6848. return transcludeFn(transcludedScope, cloneFn, {
  6849. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6850. transcludeControllers: controllers,
  6851. futureParentElement: futureParentElement
  6852. });
  6853. };
  6854. return boundTranscludeFn;
  6855. }
  6856. /**
  6857. * Looks for directives on the given node and adds them to the directive collection which is
  6858. * sorted.
  6859. *
  6860. * @param node Node to search.
  6861. * @param directives An array to which the directives are added to. This array is sorted before
  6862. * the function returns.
  6863. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6864. * @param {number=} maxPriority Max directive priority.
  6865. */
  6866. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6867. var nodeType = node.nodeType,
  6868. attrsMap = attrs.$attr,
  6869. match,
  6870. className;
  6871. switch (nodeType) {
  6872. case NODE_TYPE_ELEMENT: /* Element */
  6873. // use the node name: <directive>
  6874. addDirective(directives,
  6875. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6876. // iterate over the attributes
  6877. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6878. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6879. var attrStartName = false;
  6880. var attrEndName = false;
  6881. attr = nAttrs[j];
  6882. name = attr.name;
  6883. value = trim(attr.value);
  6884. // support ngAttr attribute binding
  6885. ngAttrName = directiveNormalize(name);
  6886. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6887. name = name.replace(PREFIX_REGEXP, '')
  6888. .substr(8).replace(/_(.)/g, function(match, letter) {
  6889. return letter.toUpperCase();
  6890. });
  6891. }
  6892. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6893. if (directiveIsMultiElement(directiveNName)) {
  6894. if (ngAttrName === directiveNName + 'Start') {
  6895. attrStartName = name;
  6896. attrEndName = name.substr(0, name.length - 5) + 'end';
  6897. name = name.substr(0, name.length - 6);
  6898. }
  6899. }
  6900. nName = directiveNormalize(name.toLowerCase());
  6901. attrsMap[nName] = name;
  6902. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6903. attrs[nName] = value;
  6904. if (getBooleanAttrName(node, nName)) {
  6905. attrs[nName] = true; // presence means true
  6906. }
  6907. }
  6908. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6909. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  6910. attrEndName);
  6911. }
  6912. // use class as directive
  6913. className = node.className;
  6914. if (isObject(className)) {
  6915. // Maybe SVGAnimatedString
  6916. className = className.animVal;
  6917. }
  6918. if (isString(className) && className !== '') {
  6919. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  6920. nName = directiveNormalize(match[2]);
  6921. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  6922. attrs[nName] = trim(match[3]);
  6923. }
  6924. className = className.substr(match.index + match[0].length);
  6925. }
  6926. }
  6927. break;
  6928. case NODE_TYPE_TEXT: /* Text Node */
  6929. if (msie === 11) {
  6930. // Workaround for #11781
  6931. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  6932. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  6933. node.parentNode.removeChild(node.nextSibling);
  6934. }
  6935. }
  6936. addTextInterpolateDirective(directives, node.nodeValue);
  6937. break;
  6938. case NODE_TYPE_COMMENT: /* Comment */
  6939. try {
  6940. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  6941. if (match) {
  6942. nName = directiveNormalize(match[1]);
  6943. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  6944. attrs[nName] = trim(match[2]);
  6945. }
  6946. }
  6947. } catch (e) {
  6948. // turns out that under some circumstances IE9 throws errors when one attempts to read
  6949. // comment's node value.
  6950. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  6951. }
  6952. break;
  6953. }
  6954. directives.sort(byPriority);
  6955. return directives;
  6956. }
  6957. /**
  6958. * Given a node with an directive-start it collects all of the siblings until it finds
  6959. * directive-end.
  6960. * @param node
  6961. * @param attrStart
  6962. * @param attrEnd
  6963. * @returns {*}
  6964. */
  6965. function groupScan(node, attrStart, attrEnd) {
  6966. var nodes = [];
  6967. var depth = 0;
  6968. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  6969. do {
  6970. if (!node) {
  6971. throw $compileMinErr('uterdir',
  6972. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  6973. attrStart, attrEnd);
  6974. }
  6975. if (node.nodeType == NODE_TYPE_ELEMENT) {
  6976. if (node.hasAttribute(attrStart)) depth++;
  6977. if (node.hasAttribute(attrEnd)) depth--;
  6978. }
  6979. nodes.push(node);
  6980. node = node.nextSibling;
  6981. } while (depth > 0);
  6982. } else {
  6983. nodes.push(node);
  6984. }
  6985. return jqLite(nodes);
  6986. }
  6987. /**
  6988. * Wrapper for linking function which converts normal linking function into a grouped
  6989. * linking function.
  6990. * @param linkFn
  6991. * @param attrStart
  6992. * @param attrEnd
  6993. * @returns {Function}
  6994. */
  6995. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  6996. return function(scope, element, attrs, controllers, transcludeFn) {
  6997. element = groupScan(element[0], attrStart, attrEnd);
  6998. return linkFn(scope, element, attrs, controllers, transcludeFn);
  6999. };
  7000. }
  7001. /**
  7002. * Once the directives have been collected, their compile functions are executed. This method
  7003. * is responsible for inlining directive templates as well as terminating the application
  7004. * of the directives if the terminal directive has been reached.
  7005. *
  7006. * @param {Array} directives Array of collected directives to execute their compile function.
  7007. * this needs to be pre-sorted by priority order.
  7008. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  7009. * @param {Object} templateAttrs The shared attribute function
  7010. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7011. * scope argument is auto-generated to the new
  7012. * child of the transcluded parent scope.
  7013. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  7014. * argument has the root jqLite array so that we can replace nodes
  7015. * on it.
  7016. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  7017. * compiling the transclusion.
  7018. * @param {Array.<Function>} preLinkFns
  7019. * @param {Array.<Function>} postLinkFns
  7020. * @param {Object} previousCompileContext Context used for previous compilation of the current
  7021. * node
  7022. * @returns {Function} linkFn
  7023. */
  7024. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  7025. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  7026. previousCompileContext) {
  7027. previousCompileContext = previousCompileContext || {};
  7028. var terminalPriority = -Number.MAX_VALUE,
  7029. newScopeDirective = previousCompileContext.newScopeDirective,
  7030. controllerDirectives = previousCompileContext.controllerDirectives,
  7031. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7032. templateDirective = previousCompileContext.templateDirective,
  7033. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7034. hasTranscludeDirective = false,
  7035. hasTemplate = false,
  7036. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7037. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7038. directive,
  7039. directiveName,
  7040. $template,
  7041. replaceDirective = originalReplaceDirective,
  7042. childTranscludeFn = transcludeFn,
  7043. linkFn,
  7044. directiveValue;
  7045. // executes all directives on the current element
  7046. for (var i = 0, ii = directives.length; i < ii; i++) {
  7047. directive = directives[i];
  7048. var attrStart = directive.$$start;
  7049. var attrEnd = directive.$$end;
  7050. // collect multiblock sections
  7051. if (attrStart) {
  7052. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7053. }
  7054. $template = undefined;
  7055. if (terminalPriority > directive.priority) {
  7056. break; // prevent further processing of directives
  7057. }
  7058. if (directiveValue = directive.scope) {
  7059. // skip the check for directives with async templates, we'll check the derived sync
  7060. // directive when the template arrives
  7061. if (!directive.templateUrl) {
  7062. if (isObject(directiveValue)) {
  7063. // This directive is trying to add an isolated scope.
  7064. // Check that there is no scope of any kind already
  7065. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7066. directive, $compileNode);
  7067. newIsolateScopeDirective = directive;
  7068. } else {
  7069. // This directive is trying to add a child scope.
  7070. // Check that there is no isolated scope already
  7071. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7072. $compileNode);
  7073. }
  7074. }
  7075. newScopeDirective = newScopeDirective || directive;
  7076. }
  7077. directiveName = directive.name;
  7078. if (!directive.templateUrl && directive.controller) {
  7079. directiveValue = directive.controller;
  7080. controllerDirectives = controllerDirectives || createMap();
  7081. assertNoDuplicate("'" + directiveName + "' controller",
  7082. controllerDirectives[directiveName], directive, $compileNode);
  7083. controllerDirectives[directiveName] = directive;
  7084. }
  7085. if (directiveValue = directive.transclude) {
  7086. hasTranscludeDirective = true;
  7087. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  7088. // This option should only be used by directives that know how to safely handle element transclusion,
  7089. // where the transcluded nodes are added or replaced after linking.
  7090. if (!directive.$$tlb) {
  7091. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  7092. nonTlbTranscludeDirective = directive;
  7093. }
  7094. if (directiveValue == 'element') {
  7095. hasElementTranscludeDirective = true;
  7096. terminalPriority = directive.priority;
  7097. $template = $compileNode;
  7098. $compileNode = templateAttrs.$$element =
  7099. jqLite(document.createComment(' ' + directiveName + ': ' +
  7100. templateAttrs[directiveName] + ' '));
  7101. compileNode = $compileNode[0];
  7102. replaceWith(jqCollection, sliceArgs($template), compileNode);
  7103. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  7104. replaceDirective && replaceDirective.name, {
  7105. // Don't pass in:
  7106. // - controllerDirectives - otherwise we'll create duplicates controllers
  7107. // - newIsolateScopeDirective or templateDirective - combining templates with
  7108. // element transclusion doesn't make sense.
  7109. //
  7110. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  7111. // on the same element more than once.
  7112. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7113. });
  7114. } else {
  7115. $template = jqLite(jqLiteClone(compileNode)).contents();
  7116. $compileNode.empty(); // clear contents
  7117. childTranscludeFn = compile($template, transcludeFn);
  7118. }
  7119. }
  7120. if (directive.template) {
  7121. hasTemplate = true;
  7122. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7123. templateDirective = directive;
  7124. directiveValue = (isFunction(directive.template))
  7125. ? directive.template($compileNode, templateAttrs)
  7126. : directive.template;
  7127. directiveValue = denormalizeTemplate(directiveValue);
  7128. if (directive.replace) {
  7129. replaceDirective = directive;
  7130. if (jqLiteIsTextNode(directiveValue)) {
  7131. $template = [];
  7132. } else {
  7133. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  7134. }
  7135. compileNode = $template[0];
  7136. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7137. throw $compileMinErr('tplrt',
  7138. "Template for directive '{0}' must have exactly one root element. {1}",
  7139. directiveName, '');
  7140. }
  7141. replaceWith(jqCollection, $compileNode, compileNode);
  7142. var newTemplateAttrs = {$attr: {}};
  7143. // combine directives from the original node and from the template:
  7144. // - take the array of directives for this element
  7145. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  7146. // - collect directives from the template and sort them by priority
  7147. // - combine directives as: processed + template + unprocessed
  7148. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  7149. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  7150. if (newIsolateScopeDirective) {
  7151. markDirectivesAsIsolate(templateDirectives);
  7152. }
  7153. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  7154. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  7155. ii = directives.length;
  7156. } else {
  7157. $compileNode.html(directiveValue);
  7158. }
  7159. }
  7160. if (directive.templateUrl) {
  7161. hasTemplate = true;
  7162. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7163. templateDirective = directive;
  7164. if (directive.replace) {
  7165. replaceDirective = directive;
  7166. }
  7167. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  7168. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  7169. controllerDirectives: controllerDirectives,
  7170. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  7171. newIsolateScopeDirective: newIsolateScopeDirective,
  7172. templateDirective: templateDirective,
  7173. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7174. });
  7175. ii = directives.length;
  7176. } else if (directive.compile) {
  7177. try {
  7178. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  7179. if (isFunction(linkFn)) {
  7180. addLinkFns(null, linkFn, attrStart, attrEnd);
  7181. } else if (linkFn) {
  7182. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  7183. }
  7184. } catch (e) {
  7185. $exceptionHandler(e, startingTag($compileNode));
  7186. }
  7187. }
  7188. if (directive.terminal) {
  7189. nodeLinkFn.terminal = true;
  7190. terminalPriority = Math.max(terminalPriority, directive.priority);
  7191. }
  7192. }
  7193. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  7194. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  7195. nodeLinkFn.templateOnThisElement = hasTemplate;
  7196. nodeLinkFn.transclude = childTranscludeFn;
  7197. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  7198. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  7199. return nodeLinkFn;
  7200. ////////////////////
  7201. function addLinkFns(pre, post, attrStart, attrEnd) {
  7202. if (pre) {
  7203. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  7204. pre.require = directive.require;
  7205. pre.directiveName = directiveName;
  7206. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7207. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  7208. }
  7209. preLinkFns.push(pre);
  7210. }
  7211. if (post) {
  7212. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  7213. post.require = directive.require;
  7214. post.directiveName = directiveName;
  7215. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7216. post = cloneAndAnnotateFn(post, {isolateScope: true});
  7217. }
  7218. postLinkFns.push(post);
  7219. }
  7220. }
  7221. function getControllers(directiveName, require, $element, elementControllers) {
  7222. var value;
  7223. if (isString(require)) {
  7224. var match = require.match(REQUIRE_PREFIX_REGEXP);
  7225. var name = require.substring(match[0].length);
  7226. var inheritType = match[1] || match[3];
  7227. var optional = match[2] === '?';
  7228. //If only parents then start at the parent element
  7229. if (inheritType === '^^') {
  7230. $element = $element.parent();
  7231. //Otherwise attempt getting the controller from elementControllers in case
  7232. //the element is transcluded (and has no data) and to avoid .data if possible
  7233. } else {
  7234. value = elementControllers && elementControllers[name];
  7235. value = value && value.instance;
  7236. }
  7237. if (!value) {
  7238. var dataName = '$' + name + 'Controller';
  7239. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  7240. }
  7241. if (!value && !optional) {
  7242. throw $compileMinErr('ctreq',
  7243. "Controller '{0}', required by directive '{1}', can't be found!",
  7244. name, directiveName);
  7245. }
  7246. } else if (isArray(require)) {
  7247. value = [];
  7248. for (var i = 0, ii = require.length; i < ii; i++) {
  7249. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  7250. }
  7251. }
  7252. return value || null;
  7253. }
  7254. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
  7255. var elementControllers = createMap();
  7256. for (var controllerKey in controllerDirectives) {
  7257. var directive = controllerDirectives[controllerKey];
  7258. var locals = {
  7259. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  7260. $element: $element,
  7261. $attrs: attrs,
  7262. $transclude: transcludeFn
  7263. };
  7264. var controller = directive.controller;
  7265. if (controller == '@') {
  7266. controller = attrs[directive.name];
  7267. }
  7268. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  7269. // For directives with element transclusion the element is a comment,
  7270. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  7271. // clean up (http://bugs.jquery.com/ticket/8335).
  7272. // Instead, we save the controllers for the element in a local hash and attach to .data
  7273. // later, once we have the actual element.
  7274. elementControllers[directive.name] = controllerInstance;
  7275. if (!hasElementTranscludeDirective) {
  7276. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  7277. }
  7278. }
  7279. return elementControllers;
  7280. }
  7281. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,
  7282. thisLinkFn) {
  7283. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  7284. attrs;
  7285. if (compileNode === linkNode) {
  7286. attrs = templateAttrs;
  7287. $element = templateAttrs.$$element;
  7288. } else {
  7289. $element = jqLite(linkNode);
  7290. attrs = new Attributes($element, templateAttrs);
  7291. }
  7292. if (newIsolateScopeDirective) {
  7293. isolateScope = scope.$new(true);
  7294. }
  7295. if (boundTranscludeFn) {
  7296. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  7297. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  7298. transcludeFn = controllersBoundTransclude;
  7299. transcludeFn.$$boundTransclude = boundTranscludeFn;
  7300. }
  7301. if (controllerDirectives) {
  7302. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
  7303. }
  7304. if (newIsolateScopeDirective) {
  7305. // Initialize isolate scope bindings for new isolate scope directive.
  7306. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  7307. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  7308. compile.$$addScopeClass($element, true);
  7309. isolateScope.$$isolateBindings =
  7310. newIsolateScopeDirective.$$isolateBindings;
  7311. initializeDirectiveBindings(scope, attrs, isolateScope,
  7312. isolateScope.$$isolateBindings,
  7313. newIsolateScopeDirective, isolateScope);
  7314. }
  7315. if (elementControllers) {
  7316. // Initialize bindToController bindings for new/isolate scopes
  7317. var scopeDirective = newIsolateScopeDirective || newScopeDirective;
  7318. var bindings;
  7319. var controllerForBindings;
  7320. if (scopeDirective && elementControllers[scopeDirective.name]) {
  7321. bindings = scopeDirective.$$bindings.bindToController;
  7322. controller = elementControllers[scopeDirective.name];
  7323. if (controller && controller.identifier && bindings) {
  7324. controllerForBindings = controller;
  7325. thisLinkFn.$$destroyBindings =
  7326. initializeDirectiveBindings(scope, attrs, controller.instance,
  7327. bindings, scopeDirective);
  7328. }
  7329. }
  7330. for (i in elementControllers) {
  7331. controller = elementControllers[i];
  7332. var controllerResult = controller();
  7333. if (controllerResult !== controller.instance) {
  7334. // If the controller constructor has a return value, overwrite the instance
  7335. // from setupControllers and update the element data
  7336. controller.instance = controllerResult;
  7337. $element.data('$' + i + 'Controller', controllerResult);
  7338. if (controller === controllerForBindings) {
  7339. // Remove and re-install bindToController bindings
  7340. thisLinkFn.$$destroyBindings();
  7341. thisLinkFn.$$destroyBindings =
  7342. initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);
  7343. }
  7344. }
  7345. }
  7346. }
  7347. // PRELINKING
  7348. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  7349. linkFn = preLinkFns[i];
  7350. invokeLinkFn(linkFn,
  7351. linkFn.isolateScope ? isolateScope : scope,
  7352. $element,
  7353. attrs,
  7354. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7355. transcludeFn
  7356. );
  7357. }
  7358. // RECURSION
  7359. // We only pass the isolate scope, if the isolate directive has a template,
  7360. // otherwise the child elements do not belong to the isolate directive.
  7361. var scopeToChild = scope;
  7362. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  7363. scopeToChild = isolateScope;
  7364. }
  7365. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  7366. // POSTLINKING
  7367. for (i = postLinkFns.length - 1; i >= 0; i--) {
  7368. linkFn = postLinkFns[i];
  7369. invokeLinkFn(linkFn,
  7370. linkFn.isolateScope ? isolateScope : scope,
  7371. $element,
  7372. attrs,
  7373. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7374. transcludeFn
  7375. );
  7376. }
  7377. // This is the function that is injected as `$transclude`.
  7378. // Note: all arguments are optional!
  7379. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  7380. var transcludeControllers;
  7381. // No scope passed in:
  7382. if (!isScope(scope)) {
  7383. futureParentElement = cloneAttachFn;
  7384. cloneAttachFn = scope;
  7385. scope = undefined;
  7386. }
  7387. if (hasElementTranscludeDirective) {
  7388. transcludeControllers = elementControllers;
  7389. }
  7390. if (!futureParentElement) {
  7391. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7392. }
  7393. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7394. }
  7395. }
  7396. }
  7397. function markDirectivesAsIsolate(directives) {
  7398. // mark all directives as needing isolate scope.
  7399. for (var j = 0, jj = directives.length; j < jj; j++) {
  7400. directives[j] = inherit(directives[j], {$$isolateScope: true});
  7401. }
  7402. }
  7403. /**
  7404. * looks up the directive and decorates it with exception handling and proper parameters. We
  7405. * call this the boundDirective.
  7406. *
  7407. * @param {string} name name of the directive to look up.
  7408. * @param {string} location The directive must be found in specific format.
  7409. * String containing any of theses characters:
  7410. *
  7411. * * `E`: element name
  7412. * * `A': attribute
  7413. * * `C`: class
  7414. * * `M`: comment
  7415. * @returns {boolean} true if directive was added.
  7416. */
  7417. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7418. endAttrName) {
  7419. if (name === ignoreDirective) return null;
  7420. var match = null;
  7421. if (hasDirectives.hasOwnProperty(name)) {
  7422. for (var directive, directives = $injector.get(name + Suffix),
  7423. i = 0, ii = directives.length; i < ii; i++) {
  7424. try {
  7425. directive = directives[i];
  7426. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  7427. directive.restrict.indexOf(location) != -1) {
  7428. if (startAttrName) {
  7429. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7430. }
  7431. tDirectives.push(directive);
  7432. match = directive;
  7433. }
  7434. } catch (e) { $exceptionHandler(e); }
  7435. }
  7436. }
  7437. return match;
  7438. }
  7439. /**
  7440. * looks up the directive and returns true if it is a multi-element directive,
  7441. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7442. * together.
  7443. *
  7444. * @param {string} name name of the directive to look up.
  7445. * @returns true if directive was registered as multi-element.
  7446. */
  7447. function directiveIsMultiElement(name) {
  7448. if (hasDirectives.hasOwnProperty(name)) {
  7449. for (var directive, directives = $injector.get(name + Suffix),
  7450. i = 0, ii = directives.length; i < ii; i++) {
  7451. directive = directives[i];
  7452. if (directive.multiElement) {
  7453. return true;
  7454. }
  7455. }
  7456. }
  7457. return false;
  7458. }
  7459. /**
  7460. * When the element is replaced with HTML template then the new attributes
  7461. * on the template need to be merged with the existing attributes in the DOM.
  7462. * The desired effect is to have both of the attributes present.
  7463. *
  7464. * @param {object} dst destination attributes (original DOM)
  7465. * @param {object} src source attributes (from the directive template)
  7466. */
  7467. function mergeTemplateAttributes(dst, src) {
  7468. var srcAttr = src.$attr,
  7469. dstAttr = dst.$attr,
  7470. $element = dst.$$element;
  7471. // reapply the old attributes to the new element
  7472. forEach(dst, function(value, key) {
  7473. if (key.charAt(0) != '$') {
  7474. if (src[key] && src[key] !== value) {
  7475. value += (key === 'style' ? ';' : ' ') + src[key];
  7476. }
  7477. dst.$set(key, value, true, srcAttr[key]);
  7478. }
  7479. });
  7480. // copy the new attributes on the old attrs object
  7481. forEach(src, function(value, key) {
  7482. if (key == 'class') {
  7483. safeAddClass($element, value);
  7484. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7485. } else if (key == 'style') {
  7486. $element.attr('style', $element.attr('style') + ';' + value);
  7487. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7488. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7489. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7490. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7491. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7492. dst[key] = value;
  7493. dstAttr[key] = srcAttr[key];
  7494. }
  7495. });
  7496. }
  7497. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7498. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7499. var linkQueue = [],
  7500. afterTemplateNodeLinkFn,
  7501. afterTemplateChildLinkFn,
  7502. beforeTemplateCompileNode = $compileNode[0],
  7503. origAsyncDirective = directives.shift(),
  7504. derivedSyncDirective = inherit(origAsyncDirective, {
  7505. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7506. }),
  7507. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7508. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7509. : origAsyncDirective.templateUrl,
  7510. templateNamespace = origAsyncDirective.templateNamespace;
  7511. $compileNode.empty();
  7512. $templateRequest(templateUrl)
  7513. .then(function(content) {
  7514. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7515. content = denormalizeTemplate(content);
  7516. if (origAsyncDirective.replace) {
  7517. if (jqLiteIsTextNode(content)) {
  7518. $template = [];
  7519. } else {
  7520. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7521. }
  7522. compileNode = $template[0];
  7523. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7524. throw $compileMinErr('tplrt',
  7525. "Template for directive '{0}' must have exactly one root element. {1}",
  7526. origAsyncDirective.name, templateUrl);
  7527. }
  7528. tempTemplateAttrs = {$attr: {}};
  7529. replaceWith($rootElement, $compileNode, compileNode);
  7530. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7531. if (isObject(origAsyncDirective.scope)) {
  7532. markDirectivesAsIsolate(templateDirectives);
  7533. }
  7534. directives = templateDirectives.concat(directives);
  7535. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7536. } else {
  7537. compileNode = beforeTemplateCompileNode;
  7538. $compileNode.html(content);
  7539. }
  7540. directives.unshift(derivedSyncDirective);
  7541. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7542. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7543. previousCompileContext);
  7544. forEach($rootElement, function(node, i) {
  7545. if (node == compileNode) {
  7546. $rootElement[i] = $compileNode[0];
  7547. }
  7548. });
  7549. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7550. while (linkQueue.length) {
  7551. var scope = linkQueue.shift(),
  7552. beforeTemplateLinkNode = linkQueue.shift(),
  7553. linkRootElement = linkQueue.shift(),
  7554. boundTranscludeFn = linkQueue.shift(),
  7555. linkNode = $compileNode[0];
  7556. if (scope.$$destroyed) continue;
  7557. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7558. var oldClasses = beforeTemplateLinkNode.className;
  7559. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7560. origAsyncDirective.replace)) {
  7561. // it was cloned therefore we have to clone as well.
  7562. linkNode = jqLiteClone(compileNode);
  7563. }
  7564. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7565. // Copy in CSS classes from original node
  7566. safeAddClass(jqLite(linkNode), oldClasses);
  7567. }
  7568. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7569. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7570. } else {
  7571. childBoundTranscludeFn = boundTranscludeFn;
  7572. }
  7573. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7574. childBoundTranscludeFn, afterTemplateNodeLinkFn);
  7575. }
  7576. linkQueue = null;
  7577. });
  7578. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7579. var childBoundTranscludeFn = boundTranscludeFn;
  7580. if (scope.$$destroyed) return;
  7581. if (linkQueue) {
  7582. linkQueue.push(scope,
  7583. node,
  7584. rootElement,
  7585. childBoundTranscludeFn);
  7586. } else {
  7587. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7588. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7589. }
  7590. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,
  7591. afterTemplateNodeLinkFn);
  7592. }
  7593. };
  7594. }
  7595. /**
  7596. * Sorting function for bound directives.
  7597. */
  7598. function byPriority(a, b) {
  7599. var diff = b.priority - a.priority;
  7600. if (diff !== 0) return diff;
  7601. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7602. return a.index - b.index;
  7603. }
  7604. function assertNoDuplicate(what, previousDirective, directive, element) {
  7605. function wrapModuleNameIfDefined(moduleName) {
  7606. return moduleName ?
  7607. (' (module: ' + moduleName + ')') :
  7608. '';
  7609. }
  7610. if (previousDirective) {
  7611. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  7612. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  7613. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  7614. }
  7615. }
  7616. function addTextInterpolateDirective(directives, text) {
  7617. var interpolateFn = $interpolate(text, true);
  7618. if (interpolateFn) {
  7619. directives.push({
  7620. priority: 0,
  7621. compile: function textInterpolateCompileFn(templateNode) {
  7622. var templateNodeParent = templateNode.parent(),
  7623. hasCompileParent = !!templateNodeParent.length;
  7624. // When transcluding a template that has bindings in the root
  7625. // we don't have a parent and thus need to add the class during linking fn.
  7626. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7627. return function textInterpolateLinkFn(scope, node) {
  7628. var parent = node.parent();
  7629. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7630. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7631. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7632. node[0].nodeValue = value;
  7633. });
  7634. };
  7635. }
  7636. });
  7637. }
  7638. }
  7639. function wrapTemplate(type, template) {
  7640. type = lowercase(type || 'html');
  7641. switch (type) {
  7642. case 'svg':
  7643. case 'math':
  7644. var wrapper = document.createElement('div');
  7645. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7646. return wrapper.childNodes[0].childNodes;
  7647. default:
  7648. return template;
  7649. }
  7650. }
  7651. function getTrustedContext(node, attrNormalizedName) {
  7652. if (attrNormalizedName == "srcdoc") {
  7653. return $sce.HTML;
  7654. }
  7655. var tag = nodeName_(node);
  7656. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7657. if (attrNormalizedName == "xlinkHref" ||
  7658. (tag == "form" && attrNormalizedName == "action") ||
  7659. (tag != "img" && (attrNormalizedName == "src" ||
  7660. attrNormalizedName == "ngSrc"))) {
  7661. return $sce.RESOURCE_URL;
  7662. }
  7663. }
  7664. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7665. var trustedContext = getTrustedContext(node, name);
  7666. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7667. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7668. // no interpolation found -> ignore
  7669. if (!interpolateFn) return;
  7670. if (name === "multiple" && nodeName_(node) === "select") {
  7671. throw $compileMinErr("selmulti",
  7672. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7673. startingTag(node));
  7674. }
  7675. directives.push({
  7676. priority: 100,
  7677. compile: function() {
  7678. return {
  7679. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7680. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7681. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7682. throw $compileMinErr('nodomevents',
  7683. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7684. "ng- versions (such as ng-click instead of onclick) instead.");
  7685. }
  7686. // If the attribute has changed since last $interpolate()ed
  7687. var newValue = attr[name];
  7688. if (newValue !== value) {
  7689. // we need to interpolate again since the attribute value has been updated
  7690. // (e.g. by another directive's compile function)
  7691. // ensure unset/empty values make interpolateFn falsy
  7692. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7693. value = newValue;
  7694. }
  7695. // if attribute was updated so that there is no interpolation going on we don't want to
  7696. // register any observers
  7697. if (!interpolateFn) return;
  7698. // initialize attr object so that it's ready in case we need the value for isolate
  7699. // scope initialization, otherwise the value would not be available from isolate
  7700. // directive's linking fn during linking phase
  7701. attr[name] = interpolateFn(scope);
  7702. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7703. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7704. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7705. //special case for class attribute addition + removal
  7706. //so that class changes can tap into the animation
  7707. //hooks provided by the $animate service. Be sure to
  7708. //skip animations when the first digest occurs (when
  7709. //both the new and the old values are the same) since
  7710. //the CSS classes are the non-interpolated values
  7711. if (name === 'class' && newValue != oldValue) {
  7712. attr.$updateClass(newValue, oldValue);
  7713. } else {
  7714. attr.$set(name, newValue);
  7715. }
  7716. });
  7717. }
  7718. };
  7719. }
  7720. });
  7721. }
  7722. /**
  7723. * This is a special jqLite.replaceWith, which can replace items which
  7724. * have no parents, provided that the containing jqLite collection is provided.
  7725. *
  7726. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7727. * in the root of the tree.
  7728. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7729. * the shell, but replace its DOM node reference.
  7730. * @param {Node} newNode The new DOM node.
  7731. */
  7732. function replaceWith($rootElement, elementsToRemove, newNode) {
  7733. var firstElementToRemove = elementsToRemove[0],
  7734. removeCount = elementsToRemove.length,
  7735. parent = firstElementToRemove.parentNode,
  7736. i, ii;
  7737. if ($rootElement) {
  7738. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7739. if ($rootElement[i] == firstElementToRemove) {
  7740. $rootElement[i++] = newNode;
  7741. for (var j = i, j2 = j + removeCount - 1,
  7742. jj = $rootElement.length;
  7743. j < jj; j++, j2++) {
  7744. if (j2 < jj) {
  7745. $rootElement[j] = $rootElement[j2];
  7746. } else {
  7747. delete $rootElement[j];
  7748. }
  7749. }
  7750. $rootElement.length -= removeCount - 1;
  7751. // If the replaced element is also the jQuery .context then replace it
  7752. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7753. // http://api.jquery.com/context/
  7754. if ($rootElement.context === firstElementToRemove) {
  7755. $rootElement.context = newNode;
  7756. }
  7757. break;
  7758. }
  7759. }
  7760. }
  7761. if (parent) {
  7762. parent.replaceChild(newNode, firstElementToRemove);
  7763. }
  7764. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7765. var fragment = document.createDocumentFragment();
  7766. fragment.appendChild(firstElementToRemove);
  7767. if (jqLite.hasData(firstElementToRemove)) {
  7768. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7769. // data here because there's no public interface in jQuery to do that and copying over
  7770. // event listeners (which is the main use of private data) wouldn't work anyway.
  7771. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7772. // Remove data of the replaced element. We cannot just call .remove()
  7773. // on the element it since that would deallocate scope that is needed
  7774. // for the new node. Instead, remove the data "manually".
  7775. if (!jQuery) {
  7776. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7777. } else {
  7778. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7779. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7780. // the scope to be trashed and we do need the very same scope to work with the new
  7781. // element. However, we cannot just cache the non-patched version and use it here as
  7782. // that would break if another library patches the method after Angular does (one
  7783. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7784. // skipped this one time.
  7785. skipDestroyOnNextJQueryCleanData = true;
  7786. jQuery.cleanData([firstElementToRemove]);
  7787. }
  7788. }
  7789. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7790. var element = elementsToRemove[k];
  7791. jqLite(element).remove(); // must do this way to clean up expando
  7792. fragment.appendChild(element);
  7793. delete elementsToRemove[k];
  7794. }
  7795. elementsToRemove[0] = newNode;
  7796. elementsToRemove.length = 1;
  7797. }
  7798. function cloneAndAnnotateFn(fn, annotation) {
  7799. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7800. }
  7801. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7802. try {
  7803. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7804. } catch (e) {
  7805. $exceptionHandler(e, startingTag($element));
  7806. }
  7807. }
  7808. // Set up $watches for isolate scope and controller bindings. This process
  7809. // only occurs for isolate scopes and new scopes with controllerAs.
  7810. function initializeDirectiveBindings(scope, attrs, destination, bindings,
  7811. directive, newScope) {
  7812. var onNewScopeDestroyed;
  7813. forEach(bindings, function(definition, scopeName) {
  7814. var attrName = definition.attrName,
  7815. optional = definition.optional,
  7816. mode = definition.mode, // @, =, or &
  7817. lastValue,
  7818. parentGet, parentSet, compare;
  7819. if (!hasOwnProperty.call(attrs, attrName)) {
  7820. // In the case of user defined a binding with the same name as a method in Object.prototype but didn't set
  7821. // the corresponding attribute. We need to make sure subsequent code won't access to the prototype function
  7822. attrs[attrName] = undefined;
  7823. }
  7824. switch (mode) {
  7825. case '@':
  7826. if (!attrs[attrName] && !optional) {
  7827. destination[scopeName] = undefined;
  7828. }
  7829. attrs.$observe(attrName, function(value) {
  7830. destination[scopeName] = value;
  7831. });
  7832. attrs.$$observers[attrName].$$scope = scope;
  7833. if (attrs[attrName]) {
  7834. // If the attribute has been provided then we trigger an interpolation to ensure
  7835. // the value is there for use in the link fn
  7836. destination[scopeName] = $interpolate(attrs[attrName])(scope);
  7837. }
  7838. break;
  7839. case '=':
  7840. if (optional && !attrs[attrName]) {
  7841. return;
  7842. }
  7843. parentGet = $parse(attrs[attrName]);
  7844. if (parentGet.literal) {
  7845. compare = equals;
  7846. } else {
  7847. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  7848. }
  7849. parentSet = parentGet.assign || function() {
  7850. // reset the change, or we will throw this exception on every $digest
  7851. lastValue = destination[scopeName] = parentGet(scope);
  7852. throw $compileMinErr('nonassign',
  7853. "Expression '{0}' used with directive '{1}' is non-assignable!",
  7854. attrs[attrName], directive.name);
  7855. };
  7856. lastValue = destination[scopeName] = parentGet(scope);
  7857. var parentValueWatch = function parentValueWatch(parentValue) {
  7858. if (!compare(parentValue, destination[scopeName])) {
  7859. // we are out of sync and need to copy
  7860. if (!compare(parentValue, lastValue)) {
  7861. // parent changed and it has precedence
  7862. destination[scopeName] = parentValue;
  7863. } else {
  7864. // if the parent can be assigned then do so
  7865. parentSet(scope, parentValue = destination[scopeName]);
  7866. }
  7867. }
  7868. return lastValue = parentValue;
  7869. };
  7870. parentValueWatch.$stateful = true;
  7871. var unwatch;
  7872. if (definition.collection) {
  7873. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  7874. } else {
  7875. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  7876. }
  7877. onNewScopeDestroyed = (onNewScopeDestroyed || []);
  7878. onNewScopeDestroyed.push(unwatch);
  7879. break;
  7880. case '&':
  7881. parentGet = $parse(attrs[attrName]);
  7882. // Don't assign noop to destination if expression is not valid
  7883. if (parentGet === noop && optional) break;
  7884. destination[scopeName] = function(locals) {
  7885. return parentGet(scope, locals);
  7886. };
  7887. break;
  7888. }
  7889. });
  7890. var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {
  7891. for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {
  7892. onNewScopeDestroyed[i]();
  7893. }
  7894. } : noop;
  7895. if (newScope && destroyBindings !== noop) {
  7896. newScope.$on('$destroy', destroyBindings);
  7897. return noop;
  7898. }
  7899. return destroyBindings;
  7900. }
  7901. }];
  7902. }
  7903. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7904. /**
  7905. * Converts all accepted directives format into proper directive name.
  7906. * @param name Name to normalize
  7907. */
  7908. function directiveNormalize(name) {
  7909. return camelCase(name.replace(PREFIX_REGEXP, ''));
  7910. }
  7911. /**
  7912. * @ngdoc type
  7913. * @name $compile.directive.Attributes
  7914. *
  7915. * @description
  7916. * A shared object between directive compile / linking functions which contains normalized DOM
  7917. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  7918. * needed since all of these are treated as equivalent in Angular:
  7919. *
  7920. * ```
  7921. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  7922. * ```
  7923. */
  7924. /**
  7925. * @ngdoc property
  7926. * @name $compile.directive.Attributes#$attr
  7927. *
  7928. * @description
  7929. * A map of DOM element attribute names to the normalized name. This is
  7930. * needed to do reverse lookup from normalized name back to actual name.
  7931. */
  7932. /**
  7933. * @ngdoc method
  7934. * @name $compile.directive.Attributes#$set
  7935. * @kind function
  7936. *
  7937. * @description
  7938. * Set DOM element attribute value.
  7939. *
  7940. *
  7941. * @param {string} name Normalized element attribute name of the property to modify. The name is
  7942. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  7943. * property to the original name.
  7944. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  7945. */
  7946. /**
  7947. * Closure compiler type information
  7948. */
  7949. function nodesetLinkingFn(
  7950. /* angular.Scope */ scope,
  7951. /* NodeList */ nodeList,
  7952. /* Element */ rootElement,
  7953. /* function(Function) */ boundTranscludeFn
  7954. ) {}
  7955. function directiveLinkingFn(
  7956. /* nodesetLinkingFn */ nodesetLinkingFn,
  7957. /* angular.Scope */ scope,
  7958. /* Node */ node,
  7959. /* Element */ rootElement,
  7960. /* function(Function) */ boundTranscludeFn
  7961. ) {}
  7962. function tokenDifference(str1, str2) {
  7963. var values = '',
  7964. tokens1 = str1.split(/\s+/),
  7965. tokens2 = str2.split(/\s+/);
  7966. outer:
  7967. for (var i = 0; i < tokens1.length; i++) {
  7968. var token = tokens1[i];
  7969. for (var j = 0; j < tokens2.length; j++) {
  7970. if (token == tokens2[j]) continue outer;
  7971. }
  7972. values += (values.length > 0 ? ' ' : '') + token;
  7973. }
  7974. return values;
  7975. }
  7976. function removeComments(jqNodes) {
  7977. jqNodes = jqLite(jqNodes);
  7978. var i = jqNodes.length;
  7979. if (i <= 1) {
  7980. return jqNodes;
  7981. }
  7982. while (i--) {
  7983. var node = jqNodes[i];
  7984. if (node.nodeType === NODE_TYPE_COMMENT) {
  7985. splice.call(jqNodes, i, 1);
  7986. }
  7987. }
  7988. return jqNodes;
  7989. }
  7990. var $controllerMinErr = minErr('$controller');
  7991. var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  7992. function identifierForController(controller, ident) {
  7993. if (ident && isString(ident)) return ident;
  7994. if (isString(controller)) {
  7995. var match = CNTRL_REG.exec(controller);
  7996. if (match) return match[3];
  7997. }
  7998. }
  7999. /**
  8000. * @ngdoc provider
  8001. * @name $controllerProvider
  8002. * @description
  8003. * The {@link ng.$controller $controller service} is used by Angular to create new
  8004. * controllers.
  8005. *
  8006. * This provider allows controller registration via the
  8007. * {@link ng.$controllerProvider#register register} method.
  8008. */
  8009. function $ControllerProvider() {
  8010. var controllers = {},
  8011. globals = false;
  8012. /**
  8013. * @ngdoc method
  8014. * @name $controllerProvider#register
  8015. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  8016. * the names and the values are the constructors.
  8017. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  8018. * annotations in the array notation).
  8019. */
  8020. this.register = function(name, constructor) {
  8021. assertNotHasOwnProperty(name, 'controller');
  8022. if (isObject(name)) {
  8023. extend(controllers, name);
  8024. } else {
  8025. controllers[name] = constructor;
  8026. }
  8027. };
  8028. /**
  8029. * @ngdoc method
  8030. * @name $controllerProvider#allowGlobals
  8031. * @description If called, allows `$controller` to find controller constructors on `window`
  8032. */
  8033. this.allowGlobals = function() {
  8034. globals = true;
  8035. };
  8036. this.$get = ['$injector', '$window', function($injector, $window) {
  8037. /**
  8038. * @ngdoc service
  8039. * @name $controller
  8040. * @requires $injector
  8041. *
  8042. * @param {Function|string} constructor If called with a function then it's considered to be the
  8043. * controller constructor function. Otherwise it's considered to be a string which is used
  8044. * to retrieve the controller constructor using the following steps:
  8045. *
  8046. * * check if a controller with given name is registered via `$controllerProvider`
  8047. * * check if evaluating the string on the current scope returns a constructor
  8048. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  8049. * `window` object (not recommended)
  8050. *
  8051. * The string can use the `controller as property` syntax, where the controller instance is published
  8052. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  8053. * to work correctly.
  8054. *
  8055. * @param {Object} locals Injection locals for Controller.
  8056. * @return {Object} Instance of given controller.
  8057. *
  8058. * @description
  8059. * `$controller` service is responsible for instantiating controllers.
  8060. *
  8061. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  8062. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  8063. */
  8064. return function(expression, locals, later, ident) {
  8065. // PRIVATE API:
  8066. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  8067. // If true, $controller will allocate the object with the correct
  8068. // prototype chain, but will not invoke the controller until a returned
  8069. // callback is invoked.
  8070. // param `ident` --- An optional label which overrides the label parsed from the controller
  8071. // expression, if any.
  8072. var instance, match, constructor, identifier;
  8073. later = later === true;
  8074. if (ident && isString(ident)) {
  8075. identifier = ident;
  8076. }
  8077. if (isString(expression)) {
  8078. match = expression.match(CNTRL_REG);
  8079. if (!match) {
  8080. throw $controllerMinErr('ctrlfmt',
  8081. "Badly formed controller string '{0}'. " +
  8082. "Must match `__name__ as __id__` or `__name__`.", expression);
  8083. }
  8084. constructor = match[1],
  8085. identifier = identifier || match[3];
  8086. expression = controllers.hasOwnProperty(constructor)
  8087. ? controllers[constructor]
  8088. : getter(locals.$scope, constructor, true) ||
  8089. (globals ? getter($window, constructor, true) : undefined);
  8090. assertArgFn(expression, constructor, true);
  8091. }
  8092. if (later) {
  8093. // Instantiate controller later:
  8094. // This machinery is used to create an instance of the object before calling the
  8095. // controller's constructor itself.
  8096. //
  8097. // This allows properties to be added to the controller before the constructor is
  8098. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  8099. //
  8100. // This feature is not intended for use by applications, and is thus not documented
  8101. // publicly.
  8102. // Object creation: http://jsperf.com/create-constructor/2
  8103. var controllerPrototype = (isArray(expression) ?
  8104. expression[expression.length - 1] : expression).prototype;
  8105. instance = Object.create(controllerPrototype || null);
  8106. if (identifier) {
  8107. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8108. }
  8109. var instantiate;
  8110. return instantiate = extend(function() {
  8111. var result = $injector.invoke(expression, instance, locals, constructor);
  8112. if (result !== instance && (isObject(result) || isFunction(result))) {
  8113. instance = result;
  8114. if (identifier) {
  8115. // If result changed, re-assign controllerAs value to scope.
  8116. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8117. }
  8118. }
  8119. return instance;
  8120. }, {
  8121. instance: instance,
  8122. identifier: identifier
  8123. });
  8124. }
  8125. instance = $injector.instantiate(expression, locals, constructor);
  8126. if (identifier) {
  8127. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8128. }
  8129. return instance;
  8130. };
  8131. function addIdentifier(locals, identifier, instance, name) {
  8132. if (!(locals && isObject(locals.$scope))) {
  8133. throw minErr('$controller')('noscp',
  8134. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  8135. name, identifier);
  8136. }
  8137. locals.$scope[identifier] = instance;
  8138. }
  8139. }];
  8140. }
  8141. /**
  8142. * @ngdoc service
  8143. * @name $document
  8144. * @requires $window
  8145. *
  8146. * @description
  8147. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  8148. *
  8149. * @example
  8150. <example module="documentExample">
  8151. <file name="index.html">
  8152. <div ng-controller="ExampleController">
  8153. <p>$document title: <b ng-bind="title"></b></p>
  8154. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  8155. </div>
  8156. </file>
  8157. <file name="script.js">
  8158. angular.module('documentExample', [])
  8159. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  8160. $scope.title = $document[0].title;
  8161. $scope.windowTitle = angular.element(window.document)[0].title;
  8162. }]);
  8163. </file>
  8164. </example>
  8165. */
  8166. function $DocumentProvider() {
  8167. this.$get = ['$window', function(window) {
  8168. return jqLite(window.document);
  8169. }];
  8170. }
  8171. /**
  8172. * @ngdoc service
  8173. * @name $exceptionHandler
  8174. * @requires ng.$log
  8175. *
  8176. * @description
  8177. * Any uncaught exception in angular expressions is delegated to this service.
  8178. * The default implementation simply delegates to `$log.error` which logs it into
  8179. * the browser console.
  8180. *
  8181. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  8182. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  8183. *
  8184. * ## Example:
  8185. *
  8186. * ```js
  8187. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  8188. * return function(exception, cause) {
  8189. * exception.message += ' (caused by "' + cause + '")';
  8190. * throw exception;
  8191. * };
  8192. * });
  8193. * ```
  8194. *
  8195. * This example will override the normal action of `$exceptionHandler`, to make angular
  8196. * exceptions fail hard when they happen, instead of just logging to the console.
  8197. *
  8198. * <hr />
  8199. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  8200. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  8201. * (unless executed during a digest).
  8202. *
  8203. * If you wish, you can manually delegate exceptions, e.g.
  8204. * `try { ... } catch(e) { $exceptionHandler(e); }`
  8205. *
  8206. * @param {Error} exception Exception associated with the error.
  8207. * @param {string=} cause optional information about the context in which
  8208. * the error was thrown.
  8209. *
  8210. */
  8211. function $ExceptionHandlerProvider() {
  8212. this.$get = ['$log', function($log) {
  8213. return function(exception, cause) {
  8214. $log.error.apply($log, arguments);
  8215. };
  8216. }];
  8217. }
  8218. var APPLICATION_JSON = 'application/json';
  8219. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  8220. var JSON_START = /^\[|^\{(?!\{)/;
  8221. var JSON_ENDS = {
  8222. '[': /]$/,
  8223. '{': /}$/
  8224. };
  8225. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  8226. function serializeValue(v) {
  8227. if (isObject(v)) {
  8228. return isDate(v) ? v.toISOString() : toJson(v);
  8229. }
  8230. return v;
  8231. }
  8232. function $HttpParamSerializerProvider() {
  8233. /**
  8234. * @ngdoc service
  8235. * @name $httpParamSerializer
  8236. * @description
  8237. *
  8238. * Default {@link $http `$http`} params serializer that converts objects to strings
  8239. * according to the following rules:
  8240. *
  8241. * * `{'foo': 'bar'}` results in `foo=bar`
  8242. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  8243. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  8244. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  8245. *
  8246. * Note that serializer will sort the request parameters alphabetically.
  8247. * */
  8248. this.$get = function() {
  8249. return function ngParamSerializer(params) {
  8250. if (!params) return '';
  8251. var parts = [];
  8252. forEachSorted(params, function(value, key) {
  8253. if (value === null || isUndefined(value)) return;
  8254. if (isArray(value)) {
  8255. forEach(value, function(v, k) {
  8256. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  8257. });
  8258. } else {
  8259. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  8260. }
  8261. });
  8262. return parts.join('&');
  8263. };
  8264. };
  8265. }
  8266. function $HttpParamSerializerJQLikeProvider() {
  8267. /**
  8268. * @ngdoc service
  8269. * @name $httpParamSerializerJQLike
  8270. * @description
  8271. *
  8272. * Alternative {@link $http `$http`} params serializer that follows
  8273. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  8274. * The serializer will also sort the params alphabetically.
  8275. *
  8276. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  8277. *
  8278. * ```js
  8279. * $http({
  8280. * url: myUrl,
  8281. * method: 'GET',
  8282. * params: myParams,
  8283. * paramSerializer: '$httpParamSerializerJQLike'
  8284. * });
  8285. * ```
  8286. *
  8287. * It is also possible to set it as the default `paramSerializer` in the
  8288. * {@link $httpProvider#defaults `$httpProvider`}.
  8289. *
  8290. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  8291. * form data for submission:
  8292. *
  8293. * ```js
  8294. * .controller(function($http, $httpParamSerializerJQLike) {
  8295. * //...
  8296. *
  8297. * $http({
  8298. * url: myUrl,
  8299. * method: 'POST',
  8300. * data: $httpParamSerializerJQLike(myData),
  8301. * headers: {
  8302. * 'Content-Type': 'application/x-www-form-urlencoded'
  8303. * }
  8304. * });
  8305. *
  8306. * });
  8307. * ```
  8308. *
  8309. * */
  8310. this.$get = function() {
  8311. return function jQueryLikeParamSerializer(params) {
  8312. if (!params) return '';
  8313. var parts = [];
  8314. serialize(params, '', true);
  8315. return parts.join('&');
  8316. function serialize(toSerialize, prefix, topLevel) {
  8317. if (toSerialize === null || isUndefined(toSerialize)) return;
  8318. if (isArray(toSerialize)) {
  8319. forEach(toSerialize, function(value) {
  8320. serialize(value, prefix + '[]');
  8321. });
  8322. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  8323. forEachSorted(toSerialize, function(value, key) {
  8324. serialize(value, prefix +
  8325. (topLevel ? '' : '[') +
  8326. key +
  8327. (topLevel ? '' : ']'));
  8328. });
  8329. } else {
  8330. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  8331. }
  8332. }
  8333. };
  8334. };
  8335. }
  8336. function defaultHttpResponseTransform(data, headers) {
  8337. if (isString(data)) {
  8338. // Strip json vulnerability protection prefix and trim whitespace
  8339. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  8340. if (tempData) {
  8341. var contentType = headers('Content-Type');
  8342. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  8343. data = fromJson(tempData);
  8344. }
  8345. }
  8346. }
  8347. return data;
  8348. }
  8349. function isJsonLike(str) {
  8350. var jsonStart = str.match(JSON_START);
  8351. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  8352. }
  8353. /**
  8354. * Parse headers into key value object
  8355. *
  8356. * @param {string} headers Raw headers as a string
  8357. * @returns {Object} Parsed headers as key value object
  8358. */
  8359. function parseHeaders(headers) {
  8360. var parsed = createMap(), i;
  8361. function fillInParsed(key, val) {
  8362. if (key) {
  8363. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  8364. }
  8365. }
  8366. if (isString(headers)) {
  8367. forEach(headers.split('\n'), function(line) {
  8368. i = line.indexOf(':');
  8369. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  8370. });
  8371. } else if (isObject(headers)) {
  8372. forEach(headers, function(headerVal, headerKey) {
  8373. fillInParsed(lowercase(headerKey), trim(headerVal));
  8374. });
  8375. }
  8376. return parsed;
  8377. }
  8378. /**
  8379. * Returns a function that provides access to parsed headers.
  8380. *
  8381. * Headers are lazy parsed when first requested.
  8382. * @see parseHeaders
  8383. *
  8384. * @param {(string|Object)} headers Headers to provide access to.
  8385. * @returns {function(string=)} Returns a getter function which if called with:
  8386. *
  8387. * - if called with single an argument returns a single header value or null
  8388. * - if called with no arguments returns an object containing all headers.
  8389. */
  8390. function headersGetter(headers) {
  8391. var headersObj;
  8392. return function(name) {
  8393. if (!headersObj) headersObj = parseHeaders(headers);
  8394. if (name) {
  8395. var value = headersObj[lowercase(name)];
  8396. if (value === void 0) {
  8397. value = null;
  8398. }
  8399. return value;
  8400. }
  8401. return headersObj;
  8402. };
  8403. }
  8404. /**
  8405. * Chain all given functions
  8406. *
  8407. * This function is used for both request and response transforming
  8408. *
  8409. * @param {*} data Data to transform.
  8410. * @param {function(string=)} headers HTTP headers getter fn.
  8411. * @param {number} status HTTP status code of the response.
  8412. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  8413. * @returns {*} Transformed data.
  8414. */
  8415. function transformData(data, headers, status, fns) {
  8416. if (isFunction(fns)) {
  8417. return fns(data, headers, status);
  8418. }
  8419. forEach(fns, function(fn) {
  8420. data = fn(data, headers, status);
  8421. });
  8422. return data;
  8423. }
  8424. function isSuccess(status) {
  8425. return 200 <= status && status < 300;
  8426. }
  8427. /**
  8428. * @ngdoc provider
  8429. * @name $httpProvider
  8430. * @description
  8431. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  8432. * */
  8433. function $HttpProvider() {
  8434. /**
  8435. * @ngdoc property
  8436. * @name $httpProvider#defaults
  8437. * @description
  8438. *
  8439. * Object containing default values for all {@link ng.$http $http} requests.
  8440. *
  8441. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  8442. * that will provide the cache for all requests who set their `cache` property to `true`.
  8443. * If you set the `defaults.cache = false` then only requests that specify their own custom
  8444. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  8445. *
  8446. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  8447. * Defaults value is `'XSRF-TOKEN'`.
  8448. *
  8449. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  8450. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  8451. *
  8452. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  8453. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  8454. * setting default headers.
  8455. * - **`defaults.headers.common`**
  8456. * - **`defaults.headers.post`**
  8457. * - **`defaults.headers.put`**
  8458. * - **`defaults.headers.patch`**
  8459. *
  8460. *
  8461. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  8462. * used to the prepare string representation of request parameters (specified as an object).
  8463. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  8464. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  8465. *
  8466. **/
  8467. var defaults = this.defaults = {
  8468. // transform incoming response data
  8469. transformResponse: [defaultHttpResponseTransform],
  8470. // transform outgoing request data
  8471. transformRequest: [function(d) {
  8472. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  8473. }],
  8474. // default headers
  8475. headers: {
  8476. common: {
  8477. 'Accept': 'application/json, text/plain, */*'
  8478. },
  8479. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8480. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8481. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  8482. },
  8483. xsrfCookieName: 'XSRF-TOKEN',
  8484. xsrfHeaderName: 'X-XSRF-TOKEN',
  8485. paramSerializer: '$httpParamSerializer'
  8486. };
  8487. var useApplyAsync = false;
  8488. /**
  8489. * @ngdoc method
  8490. * @name $httpProvider#useApplyAsync
  8491. * @description
  8492. *
  8493. * Configure $http service to combine processing of multiple http responses received at around
  8494. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  8495. * significant performance improvement for bigger applications that make many HTTP requests
  8496. * concurrently (common during application bootstrap).
  8497. *
  8498. * Defaults to false. If no value is specified, returns the current configured value.
  8499. *
  8500. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  8501. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  8502. * to load and share the same digest cycle.
  8503. *
  8504. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8505. * otherwise, returns the current configured value.
  8506. **/
  8507. this.useApplyAsync = function(value) {
  8508. if (isDefined(value)) {
  8509. useApplyAsync = !!value;
  8510. return this;
  8511. }
  8512. return useApplyAsync;
  8513. };
  8514. /**
  8515. * @ngdoc property
  8516. * @name $httpProvider#interceptors
  8517. * @description
  8518. *
  8519. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  8520. * pre-processing of request or postprocessing of responses.
  8521. *
  8522. * These service factories are ordered by request, i.e. they are applied in the same order as the
  8523. * array, on request, but reverse order, on response.
  8524. *
  8525. * {@link ng.$http#interceptors Interceptors detailed info}
  8526. **/
  8527. var interceptorFactories = this.interceptors = [];
  8528. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  8529. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  8530. var defaultCache = $cacheFactory('$http');
  8531. /**
  8532. * Make sure that default param serializer is exposed as a function
  8533. */
  8534. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  8535. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  8536. /**
  8537. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  8538. * The reversal is needed so that we can build up the interception chain around the
  8539. * server request.
  8540. */
  8541. var reversedInterceptors = [];
  8542. forEach(interceptorFactories, function(interceptorFactory) {
  8543. reversedInterceptors.unshift(isString(interceptorFactory)
  8544. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  8545. });
  8546. /**
  8547. * @ngdoc service
  8548. * @kind function
  8549. * @name $http
  8550. * @requires ng.$httpBackend
  8551. * @requires $cacheFactory
  8552. * @requires $rootScope
  8553. * @requires $q
  8554. * @requires $injector
  8555. *
  8556. * @description
  8557. * The `$http` service is a core Angular service that facilitates communication with the remote
  8558. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  8559. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  8560. *
  8561. * For unit testing applications that use `$http` service, see
  8562. * {@link ngMock.$httpBackend $httpBackend mock}.
  8563. *
  8564. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  8565. * $resource} service.
  8566. *
  8567. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  8568. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  8569. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  8570. *
  8571. *
  8572. * ## General usage
  8573. * The `$http` service is a function which takes a single argument — a configuration object —
  8574. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  8575. * with two $http specific methods: `success` and `error`.
  8576. *
  8577. * ```js
  8578. * // Simple GET request example :
  8579. * $http.get('/someUrl').
  8580. * success(function(data, status, headers, config) {
  8581. * // this callback will be called asynchronously
  8582. * // when the response is available
  8583. * }).
  8584. * error(function(data, status, headers, config) {
  8585. * // called asynchronously if an error occurs
  8586. * // or server returns response with an error status.
  8587. * });
  8588. * ```
  8589. *
  8590. * ```js
  8591. * // Simple POST request example (passing data) :
  8592. * $http.post('/someUrl', {msg:'hello word!'}).
  8593. * success(function(data, status, headers, config) {
  8594. * // this callback will be called asynchronously
  8595. * // when the response is available
  8596. * }).
  8597. * error(function(data, status, headers, config) {
  8598. * // called asynchronously if an error occurs
  8599. * // or server returns response with an error status.
  8600. * });
  8601. * ```
  8602. *
  8603. *
  8604. * Since the returned value of calling the $http function is a `promise`, you can also use
  8605. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  8606. * an object representing the response. See the API signature and type info below for more
  8607. * details.
  8608. *
  8609. * A response status code between 200 and 299 is considered a success status and
  8610. * will result in the success callback being called. Note that if the response is a redirect,
  8611. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  8612. * called for such responses.
  8613. *
  8614. * ## Writing Unit Tests that use $http
  8615. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  8616. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  8617. * request using trained responses.
  8618. *
  8619. * ```
  8620. * $httpBackend.expectGET(...);
  8621. * $http.get(...);
  8622. * $httpBackend.flush();
  8623. * ```
  8624. *
  8625. * ## Shortcut methods
  8626. *
  8627. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  8628. * request data must be passed in for POST/PUT requests.
  8629. *
  8630. * ```js
  8631. * $http.get('/someUrl').success(successCallback);
  8632. * $http.post('/someUrl', data).success(successCallback);
  8633. * ```
  8634. *
  8635. * Complete list of shortcut methods:
  8636. *
  8637. * - {@link ng.$http#get $http.get}
  8638. * - {@link ng.$http#head $http.head}
  8639. * - {@link ng.$http#post $http.post}
  8640. * - {@link ng.$http#put $http.put}
  8641. * - {@link ng.$http#delete $http.delete}
  8642. * - {@link ng.$http#jsonp $http.jsonp}
  8643. * - {@link ng.$http#patch $http.patch}
  8644. *
  8645. *
  8646. * ## Setting HTTP Headers
  8647. *
  8648. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8649. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8650. * object, which currently contains this default configuration:
  8651. *
  8652. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8653. * - `Accept: application/json, text/plain, * / *`
  8654. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8655. * - `Content-Type: application/json`
  8656. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8657. * - `Content-Type: application/json`
  8658. *
  8659. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8660. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8661. * with the lowercased HTTP method name as the key, e.g.
  8662. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  8663. *
  8664. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8665. * fashion. For example:
  8666. *
  8667. * ```
  8668. * module.run(function($http) {
  8669. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8670. * });
  8671. * ```
  8672. *
  8673. * In addition, you can supply a `headers` property in the config object passed when
  8674. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8675. *
  8676. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8677. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8678. *
  8679. * ```js
  8680. * var req = {
  8681. * method: 'POST',
  8682. * url: 'http://example.com',
  8683. * headers: {
  8684. * 'Content-Type': undefined
  8685. * },
  8686. * data: { test: 'test' }
  8687. * }
  8688. *
  8689. * $http(req).success(function(){...}).error(function(){...});
  8690. * ```
  8691. *
  8692. * ## Transforming Requests and Responses
  8693. *
  8694. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8695. * and `transformResponse`. These properties can be a single function that returns
  8696. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  8697. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8698. *
  8699. * ### Default Transformations
  8700. *
  8701. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8702. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8703. * then these will be applied.
  8704. *
  8705. * You can augment or replace the default transformations by modifying these properties by adding to or
  8706. * replacing the array.
  8707. *
  8708. * Angular provides the following default transformations:
  8709. *
  8710. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8711. *
  8712. * - If the `data` property of the request configuration object contains an object, serialize it
  8713. * into JSON format.
  8714. *
  8715. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8716. *
  8717. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8718. * - If JSON response is detected, deserialize it using a JSON parser.
  8719. *
  8720. *
  8721. * ### Overriding the Default Transformations Per Request
  8722. *
  8723. * If you wish override the request/response transformations only for a single request then provide
  8724. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8725. * into `$http`.
  8726. *
  8727. * Note that if you provide these properties on the config object the default transformations will be
  8728. * overwritten. If you wish to augment the default transformations then you must include them in your
  8729. * local transformation array.
  8730. *
  8731. * The following code demonstrates adding a new response transformation to be run after the default response
  8732. * transformations have been run.
  8733. *
  8734. * ```js
  8735. * function appendTransform(defaults, transform) {
  8736. *
  8737. * // We can't guarantee that the default transformation is an array
  8738. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8739. *
  8740. * // Append the new transformation to the defaults
  8741. * return defaults.concat(transform);
  8742. * }
  8743. *
  8744. * $http({
  8745. * url: '...',
  8746. * method: 'GET',
  8747. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8748. * return doTransform(value);
  8749. * })
  8750. * });
  8751. * ```
  8752. *
  8753. *
  8754. * ## Caching
  8755. *
  8756. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8757. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8758. * When the cache is enabled, `$http` stores the response from the server in the specified
  8759. * cache. The next time the same request is made, the response is served from the cache without
  8760. * sending a request to the server.
  8761. *
  8762. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8763. * the same way that real requests are.
  8764. *
  8765. * If there are multiple GET requests for the same URL that should be cached using the same
  8766. * cache, but the cache is not populated yet, only one request to the server will be made and
  8767. * the remaining requests will be fulfilled using the response from the first request.
  8768. *
  8769. * You can change the default cache to a new object (built with
  8770. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8771. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8772. * their `cache` property to `true` will now use this cache object.
  8773. *
  8774. * If you set the default cache to `false` then only requests that specify their own custom
  8775. * cache object will be cached.
  8776. *
  8777. * ## Interceptors
  8778. *
  8779. * Before you start creating interceptors, be sure to understand the
  8780. * {@link ng.$q $q and deferred/promise APIs}.
  8781. *
  8782. * For purposes of global error handling, authentication, or any kind of synchronous or
  8783. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8784. * able to intercept requests before they are handed to the server and
  8785. * responses before they are handed over to the application code that
  8786. * initiated these requests. The interceptors leverage the {@link ng.$q
  8787. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8788. *
  8789. * The interceptors are service factories that are registered with the `$httpProvider` by
  8790. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8791. * injected with dependencies (if specified) and returns the interceptor.
  8792. *
  8793. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8794. *
  8795. * * `request`: interceptors get called with a http `config` object. The function is free to
  8796. * modify the `config` object or create a new one. The function needs to return the `config`
  8797. * object directly, or a promise containing the `config` or a new `config` object.
  8798. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8799. * resolved with a rejection.
  8800. * * `response`: interceptors get called with http `response` object. The function is free to
  8801. * modify the `response` object or create a new one. The function needs to return the `response`
  8802. * object directly, or as a promise containing the `response` or a new `response` object.
  8803. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8804. * resolved with a rejection.
  8805. *
  8806. *
  8807. * ```js
  8808. * // register the interceptor as a service
  8809. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8810. * return {
  8811. * // optional method
  8812. * 'request': function(config) {
  8813. * // do something on success
  8814. * return config;
  8815. * },
  8816. *
  8817. * // optional method
  8818. * 'requestError': function(rejection) {
  8819. * // do something on error
  8820. * if (canRecover(rejection)) {
  8821. * return responseOrNewPromise
  8822. * }
  8823. * return $q.reject(rejection);
  8824. * },
  8825. *
  8826. *
  8827. *
  8828. * // optional method
  8829. * 'response': function(response) {
  8830. * // do something on success
  8831. * return response;
  8832. * },
  8833. *
  8834. * // optional method
  8835. * 'responseError': function(rejection) {
  8836. * // do something on error
  8837. * if (canRecover(rejection)) {
  8838. * return responseOrNewPromise
  8839. * }
  8840. * return $q.reject(rejection);
  8841. * }
  8842. * };
  8843. * });
  8844. *
  8845. * $httpProvider.interceptors.push('myHttpInterceptor');
  8846. *
  8847. *
  8848. * // alternatively, register the interceptor via an anonymous factory
  8849. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8850. * return {
  8851. * 'request': function(config) {
  8852. * // same as above
  8853. * },
  8854. *
  8855. * 'response': function(response) {
  8856. * // same as above
  8857. * }
  8858. * };
  8859. * });
  8860. * ```
  8861. *
  8862. * ## Security Considerations
  8863. *
  8864. * When designing web applications, consider security threats from:
  8865. *
  8866. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8867. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  8868. *
  8869. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  8870. * pre-configured with strategies that address these issues, but for this to work backend server
  8871. * cooperation is required.
  8872. *
  8873. * ### JSON Vulnerability Protection
  8874. *
  8875. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8876. * allows third party website to turn your JSON resource URL into
  8877. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  8878. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  8879. * Angular will automatically strip the prefix before processing it as JSON.
  8880. *
  8881. * For example if your server needs to return:
  8882. * ```js
  8883. * ['one','two']
  8884. * ```
  8885. *
  8886. * which is vulnerable to attack, your server can return:
  8887. * ```js
  8888. * )]}',
  8889. * ['one','two']
  8890. * ```
  8891. *
  8892. * Angular will strip the prefix, before processing the JSON.
  8893. *
  8894. *
  8895. * ### Cross Site Request Forgery (XSRF) Protection
  8896. *
  8897. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  8898. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  8899. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  8900. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  8901. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  8902. * the XHR came from JavaScript running on your domain. The header will not be set for
  8903. * cross-domain requests.
  8904. *
  8905. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  8906. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  8907. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  8908. * that only JavaScript running on your domain could have sent the request. The token must be
  8909. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  8910. * making up its own tokens). We recommend that the token is a digest of your site's
  8911. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  8912. * for added security.
  8913. *
  8914. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  8915. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  8916. * or the per-request config object.
  8917. *
  8918. * In order to prevent collisions in environments where multiple Angular apps share the
  8919. * same domain or subdomain, we recommend that each application uses unique cookie name.
  8920. *
  8921. *
  8922. * @param {object} config Object describing the request to be made and how it should be
  8923. * processed. The object has following properties:
  8924. *
  8925. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  8926. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  8927. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  8928. * with the `paramSerializer` and appended as GET parameters.
  8929. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  8930. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  8931. * HTTP headers to send to the server. If the return value of a function is null, the
  8932. * header will not be sent. Functions accept a config object as an argument.
  8933. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  8934. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  8935. * - **transformRequest** –
  8936. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8937. * transform function or an array of such functions. The transform function takes the http
  8938. * request body and headers and returns its transformed (typically serialized) version.
  8939. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8940. * Overriding the Default Transformations}
  8941. * - **transformResponse** –
  8942. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  8943. * transform function or an array of such functions. The transform function takes the http
  8944. * response body, headers and status and returns its transformed (typically deserialized) version.
  8945. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8946. * Overriding the Default TransformationjqLiks}
  8947. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  8948. * prepare the string representation of request parameters (specified as an object).
  8949. * If specified as string, it is interpreted as function registered with the
  8950. * {@link $injector $injector}, which means you can create your own serializer
  8951. * by registering it as a {@link auto.$provide#service service}.
  8952. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  8953. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  8954. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  8955. * GET request, otherwise if a cache instance built with
  8956. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  8957. * caching.
  8958. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  8959. * that should abort the request when resolved.
  8960. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  8961. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  8962. * for more information.
  8963. * - **responseType** - `{string}` - see
  8964. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  8965. *
  8966. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  8967. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  8968. * method takes two arguments a success and an error callback which will be called with a
  8969. * response object. The `success` and `error` methods take a single argument - a function that
  8970. * will be called when the request succeeds or fails respectively. The arguments passed into
  8971. * these functions are destructured representation of the response object passed into the
  8972. * `then` method. The response object has these properties:
  8973. *
  8974. * - **data** – `{string|Object}` – The response body transformed with the transform
  8975. * functions.
  8976. * - **status** – `{number}` – HTTP status code of the response.
  8977. * - **headers** – `{function([headerName])}` – Header getter function.
  8978. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8979. * - **statusText** – `{string}` – HTTP status text of the response.
  8980. *
  8981. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  8982. * requests. This is primarily meant to be used for debugging purposes.
  8983. *
  8984. *
  8985. * @example
  8986. <example module="httpExample">
  8987. <file name="index.html">
  8988. <div ng-controller="FetchController">
  8989. <select ng-model="method" aria-label="Request method">
  8990. <option>GET</option>
  8991. <option>JSONP</option>
  8992. </select>
  8993. <input type="text" ng-model="url" size="80" aria-label="URL" />
  8994. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  8995. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  8996. <button id="samplejsonpbtn"
  8997. ng-click="updateModel('JSONP',
  8998. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  8999. Sample JSONP
  9000. </button>
  9001. <button id="invalidjsonpbtn"
  9002. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  9003. Invalid JSONP
  9004. </button>
  9005. <pre>http status code: {{status}}</pre>
  9006. <pre>http response data: {{data}}</pre>
  9007. </div>
  9008. </file>
  9009. <file name="script.js">
  9010. angular.module('httpExample', [])
  9011. .controller('FetchController', ['$scope', '$http', '$templateCache',
  9012. function($scope, $http, $templateCache) {
  9013. $scope.method = 'GET';
  9014. $scope.url = 'http-hello.html';
  9015. $scope.fetch = function() {
  9016. $scope.code = null;
  9017. $scope.response = null;
  9018. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  9019. success(function(data, status) {
  9020. $scope.status = status;
  9021. $scope.data = data;
  9022. }).
  9023. error(function(data, status) {
  9024. $scope.data = data || "Request failed";
  9025. $scope.status = status;
  9026. });
  9027. };
  9028. $scope.updateModel = function(method, url) {
  9029. $scope.method = method;
  9030. $scope.url = url;
  9031. };
  9032. }]);
  9033. </file>
  9034. <file name="http-hello.html">
  9035. Hello, $http!
  9036. </file>
  9037. <file name="protractor.js" type="protractor">
  9038. var status = element(by.binding('status'));
  9039. var data = element(by.binding('data'));
  9040. var fetchBtn = element(by.id('fetchbtn'));
  9041. var sampleGetBtn = element(by.id('samplegetbtn'));
  9042. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  9043. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  9044. it('should make an xhr GET request', function() {
  9045. sampleGetBtn.click();
  9046. fetchBtn.click();
  9047. expect(status.getText()).toMatch('200');
  9048. expect(data.getText()).toMatch(/Hello, \$http!/);
  9049. });
  9050. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  9051. // it('should make a JSONP request to angularjs.org', function() {
  9052. // sampleJsonpBtn.click();
  9053. // fetchBtn.click();
  9054. // expect(status.getText()).toMatch('200');
  9055. // expect(data.getText()).toMatch(/Super Hero!/);
  9056. // });
  9057. it('should make JSONP request to invalid URL and invoke the error handler',
  9058. function() {
  9059. invalidJsonpBtn.click();
  9060. fetchBtn.click();
  9061. expect(status.getText()).toMatch('0');
  9062. expect(data.getText()).toMatch('Request failed');
  9063. });
  9064. </file>
  9065. </example>
  9066. */
  9067. function $http(requestConfig) {
  9068. if (!angular.isObject(requestConfig)) {
  9069. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  9070. }
  9071. var config = extend({
  9072. method: 'get',
  9073. transformRequest: defaults.transformRequest,
  9074. transformResponse: defaults.transformResponse,
  9075. paramSerializer: defaults.paramSerializer
  9076. }, requestConfig);
  9077. config.headers = mergeHeaders(requestConfig);
  9078. config.method = uppercase(config.method);
  9079. config.paramSerializer = isString(config.paramSerializer) ?
  9080. $injector.get(config.paramSerializer) : config.paramSerializer;
  9081. var serverRequest = function(config) {
  9082. var headers = config.headers;
  9083. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  9084. // strip content-type if data is undefined
  9085. if (isUndefined(reqData)) {
  9086. forEach(headers, function(value, header) {
  9087. if (lowercase(header) === 'content-type') {
  9088. delete headers[header];
  9089. }
  9090. });
  9091. }
  9092. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  9093. config.withCredentials = defaults.withCredentials;
  9094. }
  9095. // send request
  9096. return sendReq(config, reqData).then(transformResponse, transformResponse);
  9097. };
  9098. var chain = [serverRequest, undefined];
  9099. var promise = $q.when(config);
  9100. // apply interceptors
  9101. forEach(reversedInterceptors, function(interceptor) {
  9102. if (interceptor.request || interceptor.requestError) {
  9103. chain.unshift(interceptor.request, interceptor.requestError);
  9104. }
  9105. if (interceptor.response || interceptor.responseError) {
  9106. chain.push(interceptor.response, interceptor.responseError);
  9107. }
  9108. });
  9109. while (chain.length) {
  9110. var thenFn = chain.shift();
  9111. var rejectFn = chain.shift();
  9112. promise = promise.then(thenFn, rejectFn);
  9113. }
  9114. promise.success = function(fn) {
  9115. assertArgFn(fn, 'fn');
  9116. promise.then(function(response) {
  9117. fn(response.data, response.status, response.headers, config);
  9118. });
  9119. return promise;
  9120. };
  9121. promise.error = function(fn) {
  9122. assertArgFn(fn, 'fn');
  9123. promise.then(null, function(response) {
  9124. fn(response.data, response.status, response.headers, config);
  9125. });
  9126. return promise;
  9127. };
  9128. return promise;
  9129. function transformResponse(response) {
  9130. // make a copy since the response must be cacheable
  9131. var resp = extend({}, response);
  9132. if (!response.data) {
  9133. resp.data = response.data;
  9134. } else {
  9135. resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
  9136. }
  9137. return (isSuccess(response.status))
  9138. ? resp
  9139. : $q.reject(resp);
  9140. }
  9141. function executeHeaderFns(headers, config) {
  9142. var headerContent, processedHeaders = {};
  9143. forEach(headers, function(headerFn, header) {
  9144. if (isFunction(headerFn)) {
  9145. headerContent = headerFn(config);
  9146. if (headerContent != null) {
  9147. processedHeaders[header] = headerContent;
  9148. }
  9149. } else {
  9150. processedHeaders[header] = headerFn;
  9151. }
  9152. });
  9153. return processedHeaders;
  9154. }
  9155. function mergeHeaders(config) {
  9156. var defHeaders = defaults.headers,
  9157. reqHeaders = extend({}, config.headers),
  9158. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  9159. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  9160. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  9161. defaultHeadersIteration:
  9162. for (defHeaderName in defHeaders) {
  9163. lowercaseDefHeaderName = lowercase(defHeaderName);
  9164. for (reqHeaderName in reqHeaders) {
  9165. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  9166. continue defaultHeadersIteration;
  9167. }
  9168. }
  9169. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  9170. }
  9171. // execute if header value is a function for merged headers
  9172. return executeHeaderFns(reqHeaders, shallowCopy(config));
  9173. }
  9174. }
  9175. $http.pendingRequests = [];
  9176. /**
  9177. * @ngdoc method
  9178. * @name $http#get
  9179. *
  9180. * @description
  9181. * Shortcut method to perform `GET` request.
  9182. *
  9183. * @param {string} url Relative or absolute URL specifying the destination of the request
  9184. * @param {Object=} config Optional configuration object
  9185. * @returns {HttpPromise} Future object
  9186. */
  9187. /**
  9188. * @ngdoc method
  9189. * @name $http#delete
  9190. *
  9191. * @description
  9192. * Shortcut method to perform `DELETE` request.
  9193. *
  9194. * @param {string} url Relative or absolute URL specifying the destination of the request
  9195. * @param {Object=} config Optional configuration object
  9196. * @returns {HttpPromise} Future object
  9197. */
  9198. /**
  9199. * @ngdoc method
  9200. * @name $http#head
  9201. *
  9202. * @description
  9203. * Shortcut method to perform `HEAD` request.
  9204. *
  9205. * @param {string} url Relative or absolute URL specifying the destination of the request
  9206. * @param {Object=} config Optional configuration object
  9207. * @returns {HttpPromise} Future object
  9208. */
  9209. /**
  9210. * @ngdoc method
  9211. * @name $http#jsonp
  9212. *
  9213. * @description
  9214. * Shortcut method to perform `JSONP` request.
  9215. *
  9216. * @param {string} url Relative or absolute URL specifying the destination of the request.
  9217. * The name of the callback should be the string `JSON_CALLBACK`.
  9218. * @param {Object=} config Optional configuration object
  9219. * @returns {HttpPromise} Future object
  9220. */
  9221. createShortMethods('get', 'delete', 'head', 'jsonp');
  9222. /**
  9223. * @ngdoc method
  9224. * @name $http#post
  9225. *
  9226. * @description
  9227. * Shortcut method to perform `POST` request.
  9228. *
  9229. * @param {string} url Relative or absolute URL specifying the destination of the request
  9230. * @param {*} data Request content
  9231. * @param {Object=} config Optional configuration object
  9232. * @returns {HttpPromise} Future object
  9233. */
  9234. /**
  9235. * @ngdoc method
  9236. * @name $http#put
  9237. *
  9238. * @description
  9239. * Shortcut method to perform `PUT` request.
  9240. *
  9241. * @param {string} url Relative or absolute URL specifying the destination of the request
  9242. * @param {*} data Request content
  9243. * @param {Object=} config Optional configuration object
  9244. * @returns {HttpPromise} Future object
  9245. */
  9246. /**
  9247. * @ngdoc method
  9248. * @name $http#patch
  9249. *
  9250. * @description
  9251. * Shortcut method to perform `PATCH` request.
  9252. *
  9253. * @param {string} url Relative or absolute URL specifying the destination of the request
  9254. * @param {*} data Request content
  9255. * @param {Object=} config Optional configuration object
  9256. * @returns {HttpPromise} Future object
  9257. */
  9258. createShortMethodsWithData('post', 'put', 'patch');
  9259. /**
  9260. * @ngdoc property
  9261. * @name $http#defaults
  9262. *
  9263. * @description
  9264. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  9265. * default headers, withCredentials as well as request and response transformations.
  9266. *
  9267. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  9268. */
  9269. $http.defaults = defaults;
  9270. return $http;
  9271. function createShortMethods(names) {
  9272. forEach(arguments, function(name) {
  9273. $http[name] = function(url, config) {
  9274. return $http(extend({}, config || {}, {
  9275. method: name,
  9276. url: url
  9277. }));
  9278. };
  9279. });
  9280. }
  9281. function createShortMethodsWithData(name) {
  9282. forEach(arguments, function(name) {
  9283. $http[name] = function(url, data, config) {
  9284. return $http(extend({}, config || {}, {
  9285. method: name,
  9286. url: url,
  9287. data: data
  9288. }));
  9289. };
  9290. });
  9291. }
  9292. /**
  9293. * Makes the request.
  9294. *
  9295. * !!! ACCESSES CLOSURE VARS:
  9296. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  9297. */
  9298. function sendReq(config, reqData) {
  9299. var deferred = $q.defer(),
  9300. promise = deferred.promise,
  9301. cache,
  9302. cachedResp,
  9303. reqHeaders = config.headers,
  9304. url = buildUrl(config.url, config.paramSerializer(config.params));
  9305. $http.pendingRequests.push(config);
  9306. promise.then(removePendingReq, removePendingReq);
  9307. if ((config.cache || defaults.cache) && config.cache !== false &&
  9308. (config.method === 'GET' || config.method === 'JSONP')) {
  9309. cache = isObject(config.cache) ? config.cache
  9310. : isObject(defaults.cache) ? defaults.cache
  9311. : defaultCache;
  9312. }
  9313. if (cache) {
  9314. cachedResp = cache.get(url);
  9315. if (isDefined(cachedResp)) {
  9316. if (isPromiseLike(cachedResp)) {
  9317. // cached request has already been sent, but there is no response yet
  9318. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  9319. } else {
  9320. // serving from cache
  9321. if (isArray(cachedResp)) {
  9322. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  9323. } else {
  9324. resolvePromise(cachedResp, 200, {}, 'OK');
  9325. }
  9326. }
  9327. } else {
  9328. // put the promise for the non-transformed response into cache as a placeholder
  9329. cache.put(url, promise);
  9330. }
  9331. }
  9332. // if we won't have the response in cache, set the xsrf headers and
  9333. // send the request to the backend
  9334. if (isUndefined(cachedResp)) {
  9335. var xsrfValue = urlIsSameOrigin(config.url)
  9336. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  9337. : undefined;
  9338. if (xsrfValue) {
  9339. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  9340. }
  9341. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  9342. config.withCredentials, config.responseType);
  9343. }
  9344. return promise;
  9345. /**
  9346. * Callback registered to $httpBackend():
  9347. * - caches the response if desired
  9348. * - resolves the raw $http promise
  9349. * - calls $apply
  9350. */
  9351. function done(status, response, headersString, statusText) {
  9352. if (cache) {
  9353. if (isSuccess(status)) {
  9354. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  9355. } else {
  9356. // remove promise from the cache
  9357. cache.remove(url);
  9358. }
  9359. }
  9360. function resolveHttpPromise() {
  9361. resolvePromise(response, status, headersString, statusText);
  9362. }
  9363. if (useApplyAsync) {
  9364. $rootScope.$applyAsync(resolveHttpPromise);
  9365. } else {
  9366. resolveHttpPromise();
  9367. if (!$rootScope.$$phase) $rootScope.$apply();
  9368. }
  9369. }
  9370. /**
  9371. * Resolves the raw $http promise.
  9372. */
  9373. function resolvePromise(response, status, headers, statusText) {
  9374. // normalize internal statuses to 0
  9375. status = Math.max(status, 0);
  9376. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  9377. data: response,
  9378. status: status,
  9379. headers: headersGetter(headers),
  9380. config: config,
  9381. statusText: statusText
  9382. });
  9383. }
  9384. function resolvePromiseWithResult(result) {
  9385. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  9386. }
  9387. function removePendingReq() {
  9388. var idx = $http.pendingRequests.indexOf(config);
  9389. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  9390. }
  9391. }
  9392. function buildUrl(url, serializedParams) {
  9393. if (serializedParams.length > 0) {
  9394. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  9395. }
  9396. return url;
  9397. }
  9398. }];
  9399. }
  9400. function createXhr() {
  9401. return new window.XMLHttpRequest();
  9402. }
  9403. /**
  9404. * @ngdoc service
  9405. * @name $httpBackend
  9406. * @requires $window
  9407. * @requires $document
  9408. *
  9409. * @description
  9410. * HTTP backend used by the {@link ng.$http service} that delegates to
  9411. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  9412. *
  9413. * You should never need to use this service directly, instead use the higher-level abstractions:
  9414. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  9415. *
  9416. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  9417. * $httpBackend} which can be trained with responses.
  9418. */
  9419. function $HttpBackendProvider() {
  9420. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  9421. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  9422. }];
  9423. }
  9424. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  9425. // TODO(vojta): fix the signature
  9426. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  9427. $browser.$$incOutstandingRequestCount();
  9428. url = url || $browser.url();
  9429. if (lowercase(method) == 'jsonp') {
  9430. var callbackId = '_' + (callbacks.counter++).toString(36);
  9431. callbacks[callbackId] = function(data) {
  9432. callbacks[callbackId].data = data;
  9433. callbacks[callbackId].called = true;
  9434. };
  9435. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  9436. callbackId, function(status, text) {
  9437. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  9438. callbacks[callbackId] = noop;
  9439. });
  9440. } else {
  9441. var xhr = createXhr();
  9442. xhr.open(method, url, true);
  9443. forEach(headers, function(value, key) {
  9444. if (isDefined(value)) {
  9445. xhr.setRequestHeader(key, value);
  9446. }
  9447. });
  9448. xhr.onload = function requestLoaded() {
  9449. var statusText = xhr.statusText || '';
  9450. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  9451. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  9452. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  9453. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  9454. var status = xhr.status === 1223 ? 204 : xhr.status;
  9455. // fix status code when it is 0 (0 status is undocumented).
  9456. // Occurs when accessing file resources or on Android 4.1 stock browser
  9457. // while retrieving files from application cache.
  9458. if (status === 0) {
  9459. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  9460. }
  9461. completeRequest(callback,
  9462. status,
  9463. response,
  9464. xhr.getAllResponseHeaders(),
  9465. statusText);
  9466. };
  9467. var requestError = function() {
  9468. // The response is always empty
  9469. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  9470. completeRequest(callback, -1, null, null, '');
  9471. };
  9472. xhr.onerror = requestError;
  9473. xhr.onabort = requestError;
  9474. if (withCredentials) {
  9475. xhr.withCredentials = true;
  9476. }
  9477. if (responseType) {
  9478. try {
  9479. xhr.responseType = responseType;
  9480. } catch (e) {
  9481. // WebKit added support for the json responseType value on 09/03/2013
  9482. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  9483. // known to throw when setting the value "json" as the response type. Other older
  9484. // browsers implementing the responseType
  9485. //
  9486. // The json response type can be ignored if not supported, because JSON payloads are
  9487. // parsed on the client-side regardless.
  9488. if (responseType !== 'json') {
  9489. throw e;
  9490. }
  9491. }
  9492. }
  9493. xhr.send(post);
  9494. }
  9495. if (timeout > 0) {
  9496. var timeoutId = $browserDefer(timeoutRequest, timeout);
  9497. } else if (isPromiseLike(timeout)) {
  9498. timeout.then(timeoutRequest);
  9499. }
  9500. function timeoutRequest() {
  9501. jsonpDone && jsonpDone();
  9502. xhr && xhr.abort();
  9503. }
  9504. function completeRequest(callback, status, response, headersString, statusText) {
  9505. // cancel timeout and subsequent timeout promise resolution
  9506. if (timeoutId !== undefined) {
  9507. $browserDefer.cancel(timeoutId);
  9508. }
  9509. jsonpDone = xhr = null;
  9510. callback(status, response, headersString, statusText);
  9511. $browser.$$completeOutstandingRequest(noop);
  9512. }
  9513. };
  9514. function jsonpReq(url, callbackId, done) {
  9515. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  9516. // - fetches local scripts via XHR and evals them
  9517. // - adds and immediately removes script elements from the document
  9518. var script = rawDocument.createElement('script'), callback = null;
  9519. script.type = "text/javascript";
  9520. script.src = url;
  9521. script.async = true;
  9522. callback = function(event) {
  9523. removeEventListenerFn(script, "load", callback);
  9524. removeEventListenerFn(script, "error", callback);
  9525. rawDocument.body.removeChild(script);
  9526. script = null;
  9527. var status = -1;
  9528. var text = "unknown";
  9529. if (event) {
  9530. if (event.type === "load" && !callbacks[callbackId].called) {
  9531. event = { type: "error" };
  9532. }
  9533. text = event.type;
  9534. status = event.type === "error" ? 404 : 200;
  9535. }
  9536. if (done) {
  9537. done(status, text);
  9538. }
  9539. };
  9540. addEventListenerFn(script, "load", callback);
  9541. addEventListenerFn(script, "error", callback);
  9542. rawDocument.body.appendChild(script);
  9543. return callback;
  9544. }
  9545. }
  9546. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  9547. $interpolateMinErr.throwNoconcat = function(text) {
  9548. throw $interpolateMinErr('noconcat',
  9549. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9550. "interpolations that concatenate multiple expressions when a trusted value is " +
  9551. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9552. };
  9553. $interpolateMinErr.interr = function(text, err) {
  9554. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  9555. };
  9556. /**
  9557. * @ngdoc provider
  9558. * @name $interpolateProvider
  9559. *
  9560. * @description
  9561. *
  9562. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  9563. *
  9564. * @example
  9565. <example module="customInterpolationApp">
  9566. <file name="index.html">
  9567. <script>
  9568. var customInterpolationApp = angular.module('customInterpolationApp', []);
  9569. customInterpolationApp.config(function($interpolateProvider) {
  9570. $interpolateProvider.startSymbol('//');
  9571. $interpolateProvider.endSymbol('//');
  9572. });
  9573. customInterpolationApp.controller('DemoController', function() {
  9574. this.label = "This binding is brought you by // interpolation symbols.";
  9575. });
  9576. </script>
  9577. <div ng-app="App" ng-controller="DemoController as demo">
  9578. //demo.label//
  9579. </div>
  9580. </file>
  9581. <file name="protractor.js" type="protractor">
  9582. it('should interpolate binding with custom symbols', function() {
  9583. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  9584. });
  9585. </file>
  9586. </example>
  9587. */
  9588. function $InterpolateProvider() {
  9589. var startSymbol = '{{';
  9590. var endSymbol = '}}';
  9591. /**
  9592. * @ngdoc method
  9593. * @name $interpolateProvider#startSymbol
  9594. * @description
  9595. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  9596. *
  9597. * @param {string=} value new value to set the starting symbol to.
  9598. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9599. */
  9600. this.startSymbol = function(value) {
  9601. if (value) {
  9602. startSymbol = value;
  9603. return this;
  9604. } else {
  9605. return startSymbol;
  9606. }
  9607. };
  9608. /**
  9609. * @ngdoc method
  9610. * @name $interpolateProvider#endSymbol
  9611. * @description
  9612. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9613. *
  9614. * @param {string=} value new value to set the ending symbol to.
  9615. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9616. */
  9617. this.endSymbol = function(value) {
  9618. if (value) {
  9619. endSymbol = value;
  9620. return this;
  9621. } else {
  9622. return endSymbol;
  9623. }
  9624. };
  9625. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  9626. var startSymbolLength = startSymbol.length,
  9627. endSymbolLength = endSymbol.length,
  9628. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  9629. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  9630. function escape(ch) {
  9631. return '\\\\\\' + ch;
  9632. }
  9633. function unescapeText(text) {
  9634. return text.replace(escapedStartRegexp, startSymbol).
  9635. replace(escapedEndRegexp, endSymbol);
  9636. }
  9637. function stringify(value) {
  9638. if (value == null) { // null || undefined
  9639. return '';
  9640. }
  9641. switch (typeof value) {
  9642. case 'string':
  9643. break;
  9644. case 'number':
  9645. value = '' + value;
  9646. break;
  9647. default:
  9648. value = toJson(value);
  9649. }
  9650. return value;
  9651. }
  9652. /**
  9653. * @ngdoc service
  9654. * @name $interpolate
  9655. * @kind function
  9656. *
  9657. * @requires $parse
  9658. * @requires $sce
  9659. *
  9660. * @description
  9661. *
  9662. * Compiles a string with markup into an interpolation function. This service is used by the
  9663. * HTML {@link ng.$compile $compile} service for data binding. See
  9664. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  9665. * interpolation markup.
  9666. *
  9667. *
  9668. * ```js
  9669. * var $interpolate = ...; // injected
  9670. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9671. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  9672. * ```
  9673. *
  9674. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9675. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9676. * evaluate to a value other than `undefined`.
  9677. *
  9678. * ```js
  9679. * var $interpolate = ...; // injected
  9680. * var context = {greeting: 'Hello', name: undefined };
  9681. *
  9682. * // default "forgiving" mode
  9683. * var exp = $interpolate('{{greeting}} {{name}}!');
  9684. * expect(exp(context)).toEqual('Hello !');
  9685. *
  9686. * // "allOrNothing" mode
  9687. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9688. * expect(exp(context)).toBeUndefined();
  9689. * context.name = 'Angular';
  9690. * expect(exp(context)).toEqual('Hello Angular!');
  9691. * ```
  9692. *
  9693. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9694. *
  9695. * ####Escaped Interpolation
  9696. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9697. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9698. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9699. * or binding.
  9700. *
  9701. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9702. * degree, while also enabling code examples to work without relying on the
  9703. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9704. *
  9705. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9706. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9707. * interpolation start/end markers with their escaped counterparts.**
  9708. *
  9709. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9710. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9711. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9712. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9713. * this is typically useful only when user-data is used in rendering a template from the server, or
  9714. * when otherwise untrusted data is used by a directive.
  9715. *
  9716. * <example>
  9717. * <file name="index.html">
  9718. * <div ng-init="username='A user'">
  9719. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9720. * </p>
  9721. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9722. * application, but fails to accomplish their task, because the server has correctly
  9723. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9724. * characters.</p>
  9725. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9726. * from the database by an administrator.</p>
  9727. * </div>
  9728. * </file>
  9729. * </example>
  9730. *
  9731. * @param {string} text The text with markup to interpolate.
  9732. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9733. * embedded expression in order to return an interpolation function. Strings with no
  9734. * embedded expression will return null for the interpolation function.
  9735. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9736. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9737. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9738. * provides Strict Contextual Escaping for details.
  9739. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9740. * unless all embedded expressions evaluate to a value other than `undefined`.
  9741. * @returns {function(context)} an interpolation function which is used to compute the
  9742. * interpolated string. The function has these parameters:
  9743. *
  9744. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9745. */
  9746. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9747. allOrNothing = !!allOrNothing;
  9748. var startIndex,
  9749. endIndex,
  9750. index = 0,
  9751. expressions = [],
  9752. parseFns = [],
  9753. textLength = text.length,
  9754. exp,
  9755. concat = [],
  9756. expressionPositions = [];
  9757. while (index < textLength) {
  9758. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9759. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9760. if (index !== startIndex) {
  9761. concat.push(unescapeText(text.substring(index, startIndex)));
  9762. }
  9763. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9764. expressions.push(exp);
  9765. parseFns.push($parse(exp, parseStringifyInterceptor));
  9766. index = endIndex + endSymbolLength;
  9767. expressionPositions.push(concat.length);
  9768. concat.push('');
  9769. } else {
  9770. // we did not find an interpolation, so we have to add the remainder to the separators array
  9771. if (index !== textLength) {
  9772. concat.push(unescapeText(text.substring(index)));
  9773. }
  9774. break;
  9775. }
  9776. }
  9777. // Concatenating expressions makes it hard to reason about whether some combination of
  9778. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9779. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9780. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9781. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9782. // the load when auditing for XSS issues.
  9783. if (trustedContext && concat.length > 1) {
  9784. $interpolateMinErr.throwNoconcat(text);
  9785. }
  9786. if (!mustHaveExpression || expressions.length) {
  9787. var compute = function(values) {
  9788. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9789. if (allOrNothing && isUndefined(values[i])) return;
  9790. concat[expressionPositions[i]] = values[i];
  9791. }
  9792. return concat.join('');
  9793. };
  9794. var getValue = function(value) {
  9795. return trustedContext ?
  9796. $sce.getTrusted(trustedContext, value) :
  9797. $sce.valueOf(value);
  9798. };
  9799. return extend(function interpolationFn(context) {
  9800. var i = 0;
  9801. var ii = expressions.length;
  9802. var values = new Array(ii);
  9803. try {
  9804. for (; i < ii; i++) {
  9805. values[i] = parseFns[i](context);
  9806. }
  9807. return compute(values);
  9808. } catch (err) {
  9809. $exceptionHandler($interpolateMinErr.interr(text, err));
  9810. }
  9811. }, {
  9812. // all of these properties are undocumented for now
  9813. exp: text, //just for compatibility with regular watchers created via $watch
  9814. expressions: expressions,
  9815. $$watchDelegate: function(scope, listener) {
  9816. var lastValue;
  9817. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9818. var currValue = compute(values);
  9819. if (isFunction(listener)) {
  9820. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9821. }
  9822. lastValue = currValue;
  9823. });
  9824. }
  9825. });
  9826. }
  9827. function parseStringifyInterceptor(value) {
  9828. try {
  9829. value = getValue(value);
  9830. return allOrNothing && !isDefined(value) ? value : stringify(value);
  9831. } catch (err) {
  9832. $exceptionHandler($interpolateMinErr.interr(text, err));
  9833. }
  9834. }
  9835. }
  9836. /**
  9837. * @ngdoc method
  9838. * @name $interpolate#startSymbol
  9839. * @description
  9840. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9841. *
  9842. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9843. * the symbol.
  9844. *
  9845. * @returns {string} start symbol.
  9846. */
  9847. $interpolate.startSymbol = function() {
  9848. return startSymbol;
  9849. };
  9850. /**
  9851. * @ngdoc method
  9852. * @name $interpolate#endSymbol
  9853. * @description
  9854. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9855. *
  9856. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9857. * the symbol.
  9858. *
  9859. * @returns {string} end symbol.
  9860. */
  9861. $interpolate.endSymbol = function() {
  9862. return endSymbol;
  9863. };
  9864. return $interpolate;
  9865. }];
  9866. }
  9867. function $IntervalProvider() {
  9868. this.$get = ['$rootScope', '$window', '$q', '$$q',
  9869. function($rootScope, $window, $q, $$q) {
  9870. var intervals = {};
  9871. /**
  9872. * @ngdoc service
  9873. * @name $interval
  9874. *
  9875. * @description
  9876. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  9877. * milliseconds.
  9878. *
  9879. * The return value of registering an interval function is a promise. This promise will be
  9880. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  9881. * run indefinitely if `count` is not defined. The value of the notification will be the
  9882. * number of iterations that have run.
  9883. * To cancel an interval, call `$interval.cancel(promise)`.
  9884. *
  9885. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  9886. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  9887. * time.
  9888. *
  9889. * <div class="alert alert-warning">
  9890. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  9891. * with them. In particular they are not automatically destroyed when a controller's scope or a
  9892. * directive's element are destroyed.
  9893. * You should take this into consideration and make sure to always cancel the interval at the
  9894. * appropriate moment. See the example below for more details on how and when to do this.
  9895. * </div>
  9896. *
  9897. * @param {function()} fn A function that should be called repeatedly.
  9898. * @param {number} delay Number of milliseconds between each function call.
  9899. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  9900. * indefinitely.
  9901. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  9902. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  9903. * @param {...*=} Pass additional parameters to the executed function.
  9904. * @returns {promise} A promise which will be notified on each iteration.
  9905. *
  9906. * @example
  9907. * <example module="intervalExample">
  9908. * <file name="index.html">
  9909. * <script>
  9910. * angular.module('intervalExample', [])
  9911. * .controller('ExampleController', ['$scope', '$interval',
  9912. * function($scope, $interval) {
  9913. * $scope.format = 'M/d/yy h:mm:ss a';
  9914. * $scope.blood_1 = 100;
  9915. * $scope.blood_2 = 120;
  9916. *
  9917. * var stop;
  9918. * $scope.fight = function() {
  9919. * // Don't start a new fight if we are already fighting
  9920. * if ( angular.isDefined(stop) ) return;
  9921. *
  9922. * stop = $interval(function() {
  9923. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  9924. * $scope.blood_1 = $scope.blood_1 - 3;
  9925. * $scope.blood_2 = $scope.blood_2 - 4;
  9926. * } else {
  9927. * $scope.stopFight();
  9928. * }
  9929. * }, 100);
  9930. * };
  9931. *
  9932. * $scope.stopFight = function() {
  9933. * if (angular.isDefined(stop)) {
  9934. * $interval.cancel(stop);
  9935. * stop = undefined;
  9936. * }
  9937. * };
  9938. *
  9939. * $scope.resetFight = function() {
  9940. * $scope.blood_1 = 100;
  9941. * $scope.blood_2 = 120;
  9942. * };
  9943. *
  9944. * $scope.$on('$destroy', function() {
  9945. * // Make sure that the interval is destroyed too
  9946. * $scope.stopFight();
  9947. * });
  9948. * }])
  9949. * // Register the 'myCurrentTime' directive factory method.
  9950. * // We inject $interval and dateFilter service since the factory method is DI.
  9951. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  9952. * function($interval, dateFilter) {
  9953. * // return the directive link function. (compile function not needed)
  9954. * return function(scope, element, attrs) {
  9955. * var format, // date format
  9956. * stopTime; // so that we can cancel the time updates
  9957. *
  9958. * // used to update the UI
  9959. * function updateTime() {
  9960. * element.text(dateFilter(new Date(), format));
  9961. * }
  9962. *
  9963. * // watch the expression, and update the UI on change.
  9964. * scope.$watch(attrs.myCurrentTime, function(value) {
  9965. * format = value;
  9966. * updateTime();
  9967. * });
  9968. *
  9969. * stopTime = $interval(updateTime, 1000);
  9970. *
  9971. * // listen on DOM destroy (removal) event, and cancel the next UI update
  9972. * // to prevent updating time after the DOM element was removed.
  9973. * element.on('$destroy', function() {
  9974. * $interval.cancel(stopTime);
  9975. * });
  9976. * }
  9977. * }]);
  9978. * </script>
  9979. *
  9980. * <div>
  9981. * <div ng-controller="ExampleController">
  9982. * <label>Date format: <input ng-model="format"></label> <hr/>
  9983. * Current time is: <span my-current-time="format"></span>
  9984. * <hr/>
  9985. * Blood 1 : <font color='red'>{{blood_1}}</font>
  9986. * Blood 2 : <font color='red'>{{blood_2}}</font>
  9987. * <button type="button" data-ng-click="fight()">Fight</button>
  9988. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  9989. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  9990. * </div>
  9991. * </div>
  9992. *
  9993. * </file>
  9994. * </example>
  9995. */
  9996. function interval(fn, delay, count, invokeApply) {
  9997. var hasParams = arguments.length > 4,
  9998. args = hasParams ? sliceArgs(arguments, 4) : [],
  9999. setInterval = $window.setInterval,
  10000. clearInterval = $window.clearInterval,
  10001. iteration = 0,
  10002. skipApply = (isDefined(invokeApply) && !invokeApply),
  10003. deferred = (skipApply ? $$q : $q).defer(),
  10004. promise = deferred.promise;
  10005. count = isDefined(count) ? count : 0;
  10006. promise.then(null, null, (!hasParams) ? fn : function() {
  10007. fn.apply(null, args);
  10008. });
  10009. promise.$$intervalId = setInterval(function tick() {
  10010. deferred.notify(iteration++);
  10011. if (count > 0 && iteration >= count) {
  10012. deferred.resolve(iteration);
  10013. clearInterval(promise.$$intervalId);
  10014. delete intervals[promise.$$intervalId];
  10015. }
  10016. if (!skipApply) $rootScope.$apply();
  10017. }, delay);
  10018. intervals[promise.$$intervalId] = deferred;
  10019. return promise;
  10020. }
  10021. /**
  10022. * @ngdoc method
  10023. * @name $interval#cancel
  10024. *
  10025. * @description
  10026. * Cancels a task associated with the `promise`.
  10027. *
  10028. * @param {promise} promise returned by the `$interval` function.
  10029. * @returns {boolean} Returns `true` if the task was successfully canceled.
  10030. */
  10031. interval.cancel = function(promise) {
  10032. if (promise && promise.$$intervalId in intervals) {
  10033. intervals[promise.$$intervalId].reject('canceled');
  10034. $window.clearInterval(promise.$$intervalId);
  10035. delete intervals[promise.$$intervalId];
  10036. return true;
  10037. }
  10038. return false;
  10039. };
  10040. return interval;
  10041. }];
  10042. }
  10043. /**
  10044. * @ngdoc service
  10045. * @name $locale
  10046. *
  10047. * @description
  10048. * $locale service provides localization rules for various Angular components. As of right now the
  10049. * only public api is:
  10050. *
  10051. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  10052. */
  10053. function $LocaleProvider() {
  10054. this.$get = function() {
  10055. return {
  10056. id: 'en-us',
  10057. NUMBER_FORMATS: {
  10058. DECIMAL_SEP: '.',
  10059. GROUP_SEP: ',',
  10060. PATTERNS: [
  10061. { // Decimal Pattern
  10062. minInt: 1,
  10063. minFrac: 0,
  10064. maxFrac: 3,
  10065. posPre: '',
  10066. posSuf: '',
  10067. negPre: '-',
  10068. negSuf: '',
  10069. gSize: 3,
  10070. lgSize: 3
  10071. },{ //Currency Pattern
  10072. minInt: 1,
  10073. minFrac: 2,
  10074. maxFrac: 2,
  10075. posPre: '\u00A4',
  10076. posSuf: '',
  10077. negPre: '(\u00A4',
  10078. negSuf: ')',
  10079. gSize: 3,
  10080. lgSize: 3
  10081. }
  10082. ],
  10083. CURRENCY_SYM: '$'
  10084. },
  10085. DATETIME_FORMATS: {
  10086. MONTH:
  10087. 'January,February,March,April,May,June,July,August,September,October,November,December'
  10088. .split(','),
  10089. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  10090. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  10091. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  10092. AMPMS: ['AM','PM'],
  10093. medium: 'MMM d, y h:mm:ss a',
  10094. 'short': 'M/d/yy h:mm a',
  10095. fullDate: 'EEEE, MMMM d, y',
  10096. longDate: 'MMMM d, y',
  10097. mediumDate: 'MMM d, y',
  10098. shortDate: 'M/d/yy',
  10099. mediumTime: 'h:mm:ss a',
  10100. shortTime: 'h:mm a',
  10101. ERANAMES: [
  10102. "Before Christ",
  10103. "Anno Domini"
  10104. ],
  10105. ERAS: [
  10106. "BC",
  10107. "AD"
  10108. ]
  10109. },
  10110. pluralCat: function(num) {
  10111. if (num === 1) {
  10112. return 'one';
  10113. }
  10114. return 'other';
  10115. }
  10116. };
  10117. };
  10118. }
  10119. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  10120. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  10121. var $locationMinErr = minErr('$location');
  10122. /**
  10123. * Encode path using encodeUriSegment, ignoring forward slashes
  10124. *
  10125. * @param {string} path Path to encode
  10126. * @returns {string}
  10127. */
  10128. function encodePath(path) {
  10129. var segments = path.split('/'),
  10130. i = segments.length;
  10131. while (i--) {
  10132. segments[i] = encodeUriSegment(segments[i]);
  10133. }
  10134. return segments.join('/');
  10135. }
  10136. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  10137. var parsedUrl = urlResolve(absoluteUrl);
  10138. locationObj.$$protocol = parsedUrl.protocol;
  10139. locationObj.$$host = parsedUrl.hostname;
  10140. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  10141. }
  10142. function parseAppUrl(relativeUrl, locationObj) {
  10143. var prefixed = (relativeUrl.charAt(0) !== '/');
  10144. if (prefixed) {
  10145. relativeUrl = '/' + relativeUrl;
  10146. }
  10147. var match = urlResolve(relativeUrl);
  10148. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  10149. match.pathname.substring(1) : match.pathname);
  10150. locationObj.$$search = parseKeyValue(match.search);
  10151. locationObj.$$hash = decodeURIComponent(match.hash);
  10152. // make sure path starts with '/';
  10153. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  10154. locationObj.$$path = '/' + locationObj.$$path;
  10155. }
  10156. }
  10157. /**
  10158. *
  10159. * @param {string} begin
  10160. * @param {string} whole
  10161. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  10162. * expected string.
  10163. */
  10164. function beginsWith(begin, whole) {
  10165. if (whole.indexOf(begin) === 0) {
  10166. return whole.substr(begin.length);
  10167. }
  10168. }
  10169. function stripHash(url) {
  10170. var index = url.indexOf('#');
  10171. return index == -1 ? url : url.substr(0, index);
  10172. }
  10173. function trimEmptyHash(url) {
  10174. return url.replace(/(#.+)|#$/, '$1');
  10175. }
  10176. function stripFile(url) {
  10177. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  10178. }
  10179. /* return the server only (scheme://host:port) */
  10180. function serverBase(url) {
  10181. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  10182. }
  10183. /**
  10184. * LocationHtml5Url represents an url
  10185. * This object is exposed as $location service when HTML5 mode is enabled and supported
  10186. *
  10187. * @constructor
  10188. * @param {string} appBase application base URL
  10189. * @param {string} basePrefix url path prefix
  10190. */
  10191. function LocationHtml5Url(appBase, basePrefix) {
  10192. this.$$html5 = true;
  10193. basePrefix = basePrefix || '';
  10194. var appBaseNoFile = stripFile(appBase);
  10195. parseAbsoluteUrl(appBase, this);
  10196. /**
  10197. * Parse given html5 (regular) url string into properties
  10198. * @param {string} url HTML5 url
  10199. * @private
  10200. */
  10201. this.$$parse = function(url) {
  10202. var pathUrl = beginsWith(appBaseNoFile, url);
  10203. if (!isString(pathUrl)) {
  10204. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  10205. appBaseNoFile);
  10206. }
  10207. parseAppUrl(pathUrl, this);
  10208. if (!this.$$path) {
  10209. this.$$path = '/';
  10210. }
  10211. this.$$compose();
  10212. };
  10213. /**
  10214. * Compose url and update `absUrl` property
  10215. * @private
  10216. */
  10217. this.$$compose = function() {
  10218. var search = toKeyValue(this.$$search),
  10219. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10220. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10221. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  10222. };
  10223. this.$$parseLinkUrl = function(url, relHref) {
  10224. if (relHref && relHref[0] === '#') {
  10225. // special case for links to hash fragments:
  10226. // keep the old url and only replace the hash fragment
  10227. this.hash(relHref.slice(1));
  10228. return true;
  10229. }
  10230. var appUrl, prevAppUrl;
  10231. var rewrittenUrl;
  10232. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  10233. prevAppUrl = appUrl;
  10234. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  10235. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  10236. } else {
  10237. rewrittenUrl = appBase + prevAppUrl;
  10238. }
  10239. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  10240. rewrittenUrl = appBaseNoFile + appUrl;
  10241. } else if (appBaseNoFile == url + '/') {
  10242. rewrittenUrl = appBaseNoFile;
  10243. }
  10244. if (rewrittenUrl) {
  10245. this.$$parse(rewrittenUrl);
  10246. }
  10247. return !!rewrittenUrl;
  10248. };
  10249. }
  10250. /**
  10251. * LocationHashbangUrl represents url
  10252. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  10253. * It also serves as the base class for html5 mode fallback on legacy browsers.
  10254. *
  10255. * @constructor
  10256. * @param {string} appBase application base URL
  10257. * @param {string} hashPrefix hashbang prefix
  10258. */
  10259. function LocationHashbangUrl(appBase, hashPrefix) {
  10260. var appBaseNoFile = stripFile(appBase);
  10261. parseAbsoluteUrl(appBase, this);
  10262. /**
  10263. * Parse given hashbang url into properties
  10264. * @param {string} url Hashbang url
  10265. * @private
  10266. */
  10267. this.$$parse = function(url) {
  10268. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  10269. var withoutHashUrl;
  10270. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  10271. // The rest of the url starts with a hash so we have
  10272. // got either a hashbang path or a plain hash fragment
  10273. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  10274. if (isUndefined(withoutHashUrl)) {
  10275. // There was no hashbang prefix so we just have a hash fragment
  10276. withoutHashUrl = withoutBaseUrl;
  10277. }
  10278. } else {
  10279. // There was no hashbang path nor hash fragment:
  10280. // If we are in HTML5 mode we use what is left as the path;
  10281. // Otherwise we ignore what is left
  10282. if (this.$$html5) {
  10283. withoutHashUrl = withoutBaseUrl;
  10284. } else {
  10285. withoutHashUrl = '';
  10286. if (isUndefined(withoutBaseUrl)) {
  10287. appBase = url;
  10288. this.replace();
  10289. }
  10290. }
  10291. }
  10292. parseAppUrl(withoutHashUrl, this);
  10293. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  10294. this.$$compose();
  10295. /*
  10296. * In Windows, on an anchor node on documents loaded from
  10297. * the filesystem, the browser will return a pathname
  10298. * prefixed with the drive name ('/C:/path') when a
  10299. * pathname without a drive is set:
  10300. * * a.setAttribute('href', '/foo')
  10301. * * a.pathname === '/C:/foo' //true
  10302. *
  10303. * Inside of Angular, we're always using pathnames that
  10304. * do not include drive names for routing.
  10305. */
  10306. function removeWindowsDriveName(path, url, base) {
  10307. /*
  10308. Matches paths for file protocol on windows,
  10309. such as /C:/foo/bar, and captures only /foo/bar.
  10310. */
  10311. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  10312. var firstPathSegmentMatch;
  10313. //Get the relative path from the input URL.
  10314. if (url.indexOf(base) === 0) {
  10315. url = url.replace(base, '');
  10316. }
  10317. // The input URL intentionally contains a first path segment that ends with a colon.
  10318. if (windowsFilePathExp.exec(url)) {
  10319. return path;
  10320. }
  10321. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  10322. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  10323. }
  10324. };
  10325. /**
  10326. * Compose hashbang url and update `absUrl` property
  10327. * @private
  10328. */
  10329. this.$$compose = function() {
  10330. var search = toKeyValue(this.$$search),
  10331. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10332. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10333. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  10334. };
  10335. this.$$parseLinkUrl = function(url, relHref) {
  10336. if (stripHash(appBase) == stripHash(url)) {
  10337. this.$$parse(url);
  10338. return true;
  10339. }
  10340. return false;
  10341. };
  10342. }
  10343. /**
  10344. * LocationHashbangUrl represents url
  10345. * This object is exposed as $location service when html5 history api is enabled but the browser
  10346. * does not support it.
  10347. *
  10348. * @constructor
  10349. * @param {string} appBase application base URL
  10350. * @param {string} hashPrefix hashbang prefix
  10351. */
  10352. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  10353. this.$$html5 = true;
  10354. LocationHashbangUrl.apply(this, arguments);
  10355. var appBaseNoFile = stripFile(appBase);
  10356. this.$$parseLinkUrl = function(url, relHref) {
  10357. if (relHref && relHref[0] === '#') {
  10358. // special case for links to hash fragments:
  10359. // keep the old url and only replace the hash fragment
  10360. this.hash(relHref.slice(1));
  10361. return true;
  10362. }
  10363. var rewrittenUrl;
  10364. var appUrl;
  10365. if (appBase == stripHash(url)) {
  10366. rewrittenUrl = url;
  10367. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  10368. rewrittenUrl = appBase + hashPrefix + appUrl;
  10369. } else if (appBaseNoFile === url + '/') {
  10370. rewrittenUrl = appBaseNoFile;
  10371. }
  10372. if (rewrittenUrl) {
  10373. this.$$parse(rewrittenUrl);
  10374. }
  10375. return !!rewrittenUrl;
  10376. };
  10377. this.$$compose = function() {
  10378. var search = toKeyValue(this.$$search),
  10379. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10380. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10381. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  10382. this.$$absUrl = appBase + hashPrefix + this.$$url;
  10383. };
  10384. }
  10385. var locationPrototype = {
  10386. /**
  10387. * Are we in html5 mode?
  10388. * @private
  10389. */
  10390. $$html5: false,
  10391. /**
  10392. * Has any change been replacing?
  10393. * @private
  10394. */
  10395. $$replace: false,
  10396. /**
  10397. * @ngdoc method
  10398. * @name $location#absUrl
  10399. *
  10400. * @description
  10401. * This method is getter only.
  10402. *
  10403. * Return full url representation with all segments encoded according to rules specified in
  10404. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  10405. *
  10406. *
  10407. * ```js
  10408. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10409. * var absUrl = $location.absUrl();
  10410. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  10411. * ```
  10412. *
  10413. * @return {string} full url
  10414. */
  10415. absUrl: locationGetter('$$absUrl'),
  10416. /**
  10417. * @ngdoc method
  10418. * @name $location#url
  10419. *
  10420. * @description
  10421. * This method is getter / setter.
  10422. *
  10423. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  10424. *
  10425. * Change path, search and hash, when called with parameter and return `$location`.
  10426. *
  10427. *
  10428. * ```js
  10429. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10430. * var url = $location.url();
  10431. * // => "/some/path?foo=bar&baz=xoxo"
  10432. * ```
  10433. *
  10434. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  10435. * @return {string} url
  10436. */
  10437. url: function(url) {
  10438. if (isUndefined(url)) {
  10439. return this.$$url;
  10440. }
  10441. var match = PATH_MATCH.exec(url);
  10442. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  10443. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  10444. this.hash(match[5] || '');
  10445. return this;
  10446. },
  10447. /**
  10448. * @ngdoc method
  10449. * @name $location#protocol
  10450. *
  10451. * @description
  10452. * This method is getter only.
  10453. *
  10454. * Return protocol of current url.
  10455. *
  10456. *
  10457. * ```js
  10458. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10459. * var protocol = $location.protocol();
  10460. * // => "http"
  10461. * ```
  10462. *
  10463. * @return {string} protocol of current url
  10464. */
  10465. protocol: locationGetter('$$protocol'),
  10466. /**
  10467. * @ngdoc method
  10468. * @name $location#host
  10469. *
  10470. * @description
  10471. * This method is getter only.
  10472. *
  10473. * Return host of current url.
  10474. *
  10475. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  10476. *
  10477. *
  10478. * ```js
  10479. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10480. * var host = $location.host();
  10481. * // => "example.com"
  10482. *
  10483. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  10484. * host = $location.host();
  10485. * // => "example.com"
  10486. * host = location.host;
  10487. * // => "example.com:8080"
  10488. * ```
  10489. *
  10490. * @return {string} host of current url.
  10491. */
  10492. host: locationGetter('$$host'),
  10493. /**
  10494. * @ngdoc method
  10495. * @name $location#port
  10496. *
  10497. * @description
  10498. * This method is getter only.
  10499. *
  10500. * Return port of current url.
  10501. *
  10502. *
  10503. * ```js
  10504. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10505. * var port = $location.port();
  10506. * // => 80
  10507. * ```
  10508. *
  10509. * @return {Number} port
  10510. */
  10511. port: locationGetter('$$port'),
  10512. /**
  10513. * @ngdoc method
  10514. * @name $location#path
  10515. *
  10516. * @description
  10517. * This method is getter / setter.
  10518. *
  10519. * Return path of current url when called without any parameter.
  10520. *
  10521. * Change path when called with parameter and return `$location`.
  10522. *
  10523. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  10524. * if it is missing.
  10525. *
  10526. *
  10527. * ```js
  10528. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10529. * var path = $location.path();
  10530. * // => "/some/path"
  10531. * ```
  10532. *
  10533. * @param {(string|number)=} path New path
  10534. * @return {string} path
  10535. */
  10536. path: locationGetterSetter('$$path', function(path) {
  10537. path = path !== null ? path.toString() : '';
  10538. return path.charAt(0) == '/' ? path : '/' + path;
  10539. }),
  10540. /**
  10541. * @ngdoc method
  10542. * @name $location#search
  10543. *
  10544. * @description
  10545. * This method is getter / setter.
  10546. *
  10547. * Return search part (as object) of current url when called without any parameter.
  10548. *
  10549. * Change search part when called with parameter and return `$location`.
  10550. *
  10551. *
  10552. * ```js
  10553. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10554. * var searchObject = $location.search();
  10555. * // => {foo: 'bar', baz: 'xoxo'}
  10556. *
  10557. * // set foo to 'yipee'
  10558. * $location.search('foo', 'yipee');
  10559. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  10560. * ```
  10561. *
  10562. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  10563. * hash object.
  10564. *
  10565. * When called with a single argument the method acts as a setter, setting the `search` component
  10566. * of `$location` to the specified value.
  10567. *
  10568. * If the argument is a hash object containing an array of values, these values will be encoded
  10569. * as duplicate search parameters in the url.
  10570. *
  10571. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  10572. * will override only a single search property.
  10573. *
  10574. * If `paramValue` is an array, it will override the property of the `search` component of
  10575. * `$location` specified via the first argument.
  10576. *
  10577. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  10578. *
  10579. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  10580. * value nor trailing equal sign.
  10581. *
  10582. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  10583. * one or more arguments returns `$location` object itself.
  10584. */
  10585. search: function(search, paramValue) {
  10586. switch (arguments.length) {
  10587. case 0:
  10588. return this.$$search;
  10589. case 1:
  10590. if (isString(search) || isNumber(search)) {
  10591. search = search.toString();
  10592. this.$$search = parseKeyValue(search);
  10593. } else if (isObject(search)) {
  10594. search = copy(search, {});
  10595. // remove object undefined or null properties
  10596. forEach(search, function(value, key) {
  10597. if (value == null) delete search[key];
  10598. });
  10599. this.$$search = search;
  10600. } else {
  10601. throw $locationMinErr('isrcharg',
  10602. 'The first argument of the `$location#search()` call must be a string or an object.');
  10603. }
  10604. break;
  10605. default:
  10606. if (isUndefined(paramValue) || paramValue === null) {
  10607. delete this.$$search[search];
  10608. } else {
  10609. this.$$search[search] = paramValue;
  10610. }
  10611. }
  10612. this.$$compose();
  10613. return this;
  10614. },
  10615. /**
  10616. * @ngdoc method
  10617. * @name $location#hash
  10618. *
  10619. * @description
  10620. * This method is getter / setter.
  10621. *
  10622. * Return hash fragment when called without any parameter.
  10623. *
  10624. * Change hash fragment when called with parameter and return `$location`.
  10625. *
  10626. *
  10627. * ```js
  10628. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  10629. * var hash = $location.hash();
  10630. * // => "hashValue"
  10631. * ```
  10632. *
  10633. * @param {(string|number)=} hash New hash fragment
  10634. * @return {string} hash
  10635. */
  10636. hash: locationGetterSetter('$$hash', function(hash) {
  10637. return hash !== null ? hash.toString() : '';
  10638. }),
  10639. /**
  10640. * @ngdoc method
  10641. * @name $location#replace
  10642. *
  10643. * @description
  10644. * If called, all changes to $location during current `$digest` will be replacing current history
  10645. * record, instead of adding new one.
  10646. */
  10647. replace: function() {
  10648. this.$$replace = true;
  10649. return this;
  10650. }
  10651. };
  10652. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  10653. Location.prototype = Object.create(locationPrototype);
  10654. /**
  10655. * @ngdoc method
  10656. * @name $location#state
  10657. *
  10658. * @description
  10659. * This method is getter / setter.
  10660. *
  10661. * Return the history state object when called without any parameter.
  10662. *
  10663. * Change the history state object when called with one parameter and return `$location`.
  10664. * The state object is later passed to `pushState` or `replaceState`.
  10665. *
  10666. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  10667. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  10668. * older browsers (like IE9 or Android < 4.0), don't use this method.
  10669. *
  10670. * @param {object=} state State object for pushState or replaceState
  10671. * @return {object} state
  10672. */
  10673. Location.prototype.state = function(state) {
  10674. if (!arguments.length) {
  10675. return this.$$state;
  10676. }
  10677. if (Location !== LocationHtml5Url || !this.$$html5) {
  10678. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10679. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10680. }
  10681. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10682. // but we're changing the $$state reference to $browser.state() during the $digest
  10683. // so the modification window is narrow.
  10684. this.$$state = isUndefined(state) ? null : state;
  10685. return this;
  10686. };
  10687. });
  10688. function locationGetter(property) {
  10689. return function() {
  10690. return this[property];
  10691. };
  10692. }
  10693. function locationGetterSetter(property, preprocess) {
  10694. return function(value) {
  10695. if (isUndefined(value)) {
  10696. return this[property];
  10697. }
  10698. this[property] = preprocess(value);
  10699. this.$$compose();
  10700. return this;
  10701. };
  10702. }
  10703. /**
  10704. * @ngdoc service
  10705. * @name $location
  10706. *
  10707. * @requires $rootElement
  10708. *
  10709. * @description
  10710. * The $location service parses the URL in the browser address bar (based on the
  10711. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10712. * available to your application. Changes to the URL in the address bar are reflected into
  10713. * $location service and changes to $location are reflected into the browser address bar.
  10714. *
  10715. * **The $location service:**
  10716. *
  10717. * - Exposes the current URL in the browser address bar, so you can
  10718. * - Watch and observe the URL.
  10719. * - Change the URL.
  10720. * - Synchronizes the URL with the browser when the user
  10721. * - Changes the address bar.
  10722. * - Clicks the back or forward button (or clicks a History link).
  10723. * - Clicks on a link.
  10724. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10725. *
  10726. * For more information see {@link guide/$location Developer Guide: Using $location}
  10727. */
  10728. /**
  10729. * @ngdoc provider
  10730. * @name $locationProvider
  10731. * @description
  10732. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10733. */
  10734. function $LocationProvider() {
  10735. var hashPrefix = '',
  10736. html5Mode = {
  10737. enabled: false,
  10738. requireBase: true,
  10739. rewriteLinks: true
  10740. };
  10741. /**
  10742. * @ngdoc method
  10743. * @name $locationProvider#hashPrefix
  10744. * @description
  10745. * @param {string=} prefix Prefix for hash part (containing path and search)
  10746. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10747. */
  10748. this.hashPrefix = function(prefix) {
  10749. if (isDefined(prefix)) {
  10750. hashPrefix = prefix;
  10751. return this;
  10752. } else {
  10753. return hashPrefix;
  10754. }
  10755. };
  10756. /**
  10757. * @ngdoc method
  10758. * @name $locationProvider#html5Mode
  10759. * @description
  10760. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10761. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10762. * properties:
  10763. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10764. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10765. * support `pushState`.
  10766. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10767. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10768. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10769. * See the {@link guide/$location $location guide for more information}
  10770. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10771. * enables/disables url rewriting for relative links.
  10772. *
  10773. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10774. */
  10775. this.html5Mode = function(mode) {
  10776. if (isBoolean(mode)) {
  10777. html5Mode.enabled = mode;
  10778. return this;
  10779. } else if (isObject(mode)) {
  10780. if (isBoolean(mode.enabled)) {
  10781. html5Mode.enabled = mode.enabled;
  10782. }
  10783. if (isBoolean(mode.requireBase)) {
  10784. html5Mode.requireBase = mode.requireBase;
  10785. }
  10786. if (isBoolean(mode.rewriteLinks)) {
  10787. html5Mode.rewriteLinks = mode.rewriteLinks;
  10788. }
  10789. return this;
  10790. } else {
  10791. return html5Mode;
  10792. }
  10793. };
  10794. /**
  10795. * @ngdoc event
  10796. * @name $location#$locationChangeStart
  10797. * @eventType broadcast on root scope
  10798. * @description
  10799. * Broadcasted before a URL will change.
  10800. *
  10801. * This change can be prevented by calling
  10802. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10803. * details about event object. Upon successful change
  10804. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10805. *
  10806. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10807. * the browser supports the HTML5 History API.
  10808. *
  10809. * @param {Object} angularEvent Synthetic event object.
  10810. * @param {string} newUrl New URL
  10811. * @param {string=} oldUrl URL that was before it was changed.
  10812. * @param {string=} newState New history state object
  10813. * @param {string=} oldState History state object that was before it was changed.
  10814. */
  10815. /**
  10816. * @ngdoc event
  10817. * @name $location#$locationChangeSuccess
  10818. * @eventType broadcast on root scope
  10819. * @description
  10820. * Broadcasted after a URL was changed.
  10821. *
  10822. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10823. * the browser supports the HTML5 History API.
  10824. *
  10825. * @param {Object} angularEvent Synthetic event object.
  10826. * @param {string} newUrl New URL
  10827. * @param {string=} oldUrl URL that was before it was changed.
  10828. * @param {string=} newState New history state object
  10829. * @param {string=} oldState History state object that was before it was changed.
  10830. */
  10831. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10832. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10833. var $location,
  10834. LocationMode,
  10835. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10836. initialUrl = $browser.url(),
  10837. appBase;
  10838. if (html5Mode.enabled) {
  10839. if (!baseHref && html5Mode.requireBase) {
  10840. throw $locationMinErr('nobase',
  10841. "$location in HTML5 mode requires a <base> tag to be present!");
  10842. }
  10843. appBase = serverBase(initialUrl) + (baseHref || '/');
  10844. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10845. } else {
  10846. appBase = stripHash(initialUrl);
  10847. LocationMode = LocationHashbangUrl;
  10848. }
  10849. $location = new LocationMode(appBase, '#' + hashPrefix);
  10850. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10851. $location.$$state = $browser.state();
  10852. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10853. function setBrowserUrlWithFallback(url, replace, state) {
  10854. var oldUrl = $location.url();
  10855. var oldState = $location.$$state;
  10856. try {
  10857. $browser.url(url, replace, state);
  10858. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10859. // state object; this makes possible quick checking if the state changed in the digest
  10860. // loop. Checking deep equality would be too expensive.
  10861. $location.$$state = $browser.state();
  10862. } catch (e) {
  10863. // Restore old values if pushState fails
  10864. $location.url(oldUrl);
  10865. $location.$$state = oldState;
  10866. throw e;
  10867. }
  10868. }
  10869. $rootElement.on('click', function(event) {
  10870. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10871. // currently we open nice url link and redirect then
  10872. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  10873. var elm = jqLite(event.target);
  10874. // traverse the DOM up to find first A tag
  10875. while (nodeName_(elm[0]) !== 'a') {
  10876. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10877. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10878. }
  10879. var absHref = elm.prop('href');
  10880. // get the actual href attribute - see
  10881. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10882. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10883. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10884. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10885. // an animation.
  10886. absHref = urlResolve(absHref.animVal).href;
  10887. }
  10888. // Ignore when url is started with javascript: or mailto:
  10889. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10890. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10891. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10892. // We do a preventDefault for all urls that are part of the angular application,
  10893. // in html5mode and also without, so that we are able to abort navigation without
  10894. // getting double entries in the location history.
  10895. event.preventDefault();
  10896. // update location manually
  10897. if ($location.absUrl() != $browser.url()) {
  10898. $rootScope.$apply();
  10899. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10900. $window.angular['ff-684208-preventDefault'] = true;
  10901. }
  10902. }
  10903. }
  10904. });
  10905. // rewrite hashbang url <> html5 url
  10906. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  10907. $browser.url($location.absUrl(), true);
  10908. }
  10909. var initializing = true;
  10910. // update $location when $browser url changes
  10911. $browser.onUrlChange(function(newUrl, newState) {
  10912. $rootScope.$evalAsync(function() {
  10913. var oldUrl = $location.absUrl();
  10914. var oldState = $location.$$state;
  10915. var defaultPrevented;
  10916. $location.$$parse(newUrl);
  10917. $location.$$state = newState;
  10918. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10919. newState, oldState).defaultPrevented;
  10920. // if the location was changed by a `$locationChangeStart` handler then stop
  10921. // processing this location change
  10922. if ($location.absUrl() !== newUrl) return;
  10923. if (defaultPrevented) {
  10924. $location.$$parse(oldUrl);
  10925. $location.$$state = oldState;
  10926. setBrowserUrlWithFallback(oldUrl, false, oldState);
  10927. } else {
  10928. initializing = false;
  10929. afterLocationChange(oldUrl, oldState);
  10930. }
  10931. });
  10932. if (!$rootScope.$$phase) $rootScope.$digest();
  10933. });
  10934. // update browser
  10935. $rootScope.$watch(function $locationWatch() {
  10936. var oldUrl = trimEmptyHash($browser.url());
  10937. var newUrl = trimEmptyHash($location.absUrl());
  10938. var oldState = $browser.state();
  10939. var currentReplace = $location.$$replace;
  10940. var urlOrStateChanged = oldUrl !== newUrl ||
  10941. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  10942. if (initializing || urlOrStateChanged) {
  10943. initializing = false;
  10944. $rootScope.$evalAsync(function() {
  10945. var newUrl = $location.absUrl();
  10946. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10947. $location.$$state, oldState).defaultPrevented;
  10948. // if the location was changed by a `$locationChangeStart` handler then stop
  10949. // processing this location change
  10950. if ($location.absUrl() !== newUrl) return;
  10951. if (defaultPrevented) {
  10952. $location.$$parse(oldUrl);
  10953. $location.$$state = oldState;
  10954. } else {
  10955. if (urlOrStateChanged) {
  10956. setBrowserUrlWithFallback(newUrl, currentReplace,
  10957. oldState === $location.$$state ? null : $location.$$state);
  10958. }
  10959. afterLocationChange(oldUrl, oldState);
  10960. }
  10961. });
  10962. }
  10963. $location.$$replace = false;
  10964. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  10965. // there is a change
  10966. });
  10967. return $location;
  10968. function afterLocationChange(oldUrl, oldState) {
  10969. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  10970. $location.$$state, oldState);
  10971. }
  10972. }];
  10973. }
  10974. /**
  10975. * @ngdoc service
  10976. * @name $log
  10977. * @requires $window
  10978. *
  10979. * @description
  10980. * Simple service for logging. Default implementation safely writes the message
  10981. * into the browser's console (if present).
  10982. *
  10983. * The main purpose of this service is to simplify debugging and troubleshooting.
  10984. *
  10985. * The default is to log `debug` messages. You can use
  10986. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  10987. *
  10988. * @example
  10989. <example module="logExample">
  10990. <file name="script.js">
  10991. angular.module('logExample', [])
  10992. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  10993. $scope.$log = $log;
  10994. $scope.message = 'Hello World!';
  10995. }]);
  10996. </file>
  10997. <file name="index.html">
  10998. <div ng-controller="LogController">
  10999. <p>Reload this page with open console, enter text and hit the log button...</p>
  11000. <label>Message:
  11001. <input type="text" ng-model="message" /></label>
  11002. <button ng-click="$log.log(message)">log</button>
  11003. <button ng-click="$log.warn(message)">warn</button>
  11004. <button ng-click="$log.info(message)">info</button>
  11005. <button ng-click="$log.error(message)">error</button>
  11006. <button ng-click="$log.debug(message)">debug</button>
  11007. </div>
  11008. </file>
  11009. </example>
  11010. */
  11011. /**
  11012. * @ngdoc provider
  11013. * @name $logProvider
  11014. * @description
  11015. * Use the `$logProvider` to configure how the application logs messages
  11016. */
  11017. function $LogProvider() {
  11018. var debug = true,
  11019. self = this;
  11020. /**
  11021. * @ngdoc method
  11022. * @name $logProvider#debugEnabled
  11023. * @description
  11024. * @param {boolean=} flag enable or disable debug level messages
  11025. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11026. */
  11027. this.debugEnabled = function(flag) {
  11028. if (isDefined(flag)) {
  11029. debug = flag;
  11030. return this;
  11031. } else {
  11032. return debug;
  11033. }
  11034. };
  11035. this.$get = ['$window', function($window) {
  11036. return {
  11037. /**
  11038. * @ngdoc method
  11039. * @name $log#log
  11040. *
  11041. * @description
  11042. * Write a log message
  11043. */
  11044. log: consoleLog('log'),
  11045. /**
  11046. * @ngdoc method
  11047. * @name $log#info
  11048. *
  11049. * @description
  11050. * Write an information message
  11051. */
  11052. info: consoleLog('info'),
  11053. /**
  11054. * @ngdoc method
  11055. * @name $log#warn
  11056. *
  11057. * @description
  11058. * Write a warning message
  11059. */
  11060. warn: consoleLog('warn'),
  11061. /**
  11062. * @ngdoc method
  11063. * @name $log#error
  11064. *
  11065. * @description
  11066. * Write an error message
  11067. */
  11068. error: consoleLog('error'),
  11069. /**
  11070. * @ngdoc method
  11071. * @name $log#debug
  11072. *
  11073. * @description
  11074. * Write a debug message
  11075. */
  11076. debug: (function() {
  11077. var fn = consoleLog('debug');
  11078. return function() {
  11079. if (debug) {
  11080. fn.apply(self, arguments);
  11081. }
  11082. };
  11083. }())
  11084. };
  11085. function formatError(arg) {
  11086. if (arg instanceof Error) {
  11087. if (arg.stack) {
  11088. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  11089. ? 'Error: ' + arg.message + '\n' + arg.stack
  11090. : arg.stack;
  11091. } else if (arg.sourceURL) {
  11092. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  11093. }
  11094. }
  11095. return arg;
  11096. }
  11097. function consoleLog(type) {
  11098. var console = $window.console || {},
  11099. logFn = console[type] || console.log || noop,
  11100. hasApply = false;
  11101. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  11102. // The reason behind this is that console.log has type "object" in IE8...
  11103. try {
  11104. hasApply = !!logFn.apply;
  11105. } catch (e) {}
  11106. if (hasApply) {
  11107. return function() {
  11108. var args = [];
  11109. forEach(arguments, function(arg) {
  11110. args.push(formatError(arg));
  11111. });
  11112. return logFn.apply(console, args);
  11113. };
  11114. }
  11115. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  11116. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  11117. return function(arg1, arg2) {
  11118. logFn(arg1, arg2 == null ? '' : arg2);
  11119. };
  11120. }
  11121. }];
  11122. }
  11123. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  11124. * Any commits to this file should be reviewed with security in mind. *
  11125. * Changes to this file can potentially create security vulnerabilities. *
  11126. * An approval from 2 Core members with history of modifying *
  11127. * this file is required. *
  11128. * *
  11129. * Does the change somehow allow for arbitrary javascript to be executed? *
  11130. * Or allows for someone to change the prototype of built-in objects? *
  11131. * Or gives undesired access to variables likes document or window? *
  11132. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  11133. var $parseMinErr = minErr('$parse');
  11134. // Sandboxing Angular Expressions
  11135. // ------------------------------
  11136. // Angular expressions are generally considered safe because these expressions only have direct
  11137. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  11138. // obtaining a reference to native JS functions such as the Function constructor.
  11139. //
  11140. // As an example, consider the following Angular expression:
  11141. //
  11142. // {}.toString.constructor('alert("evil JS code")')
  11143. //
  11144. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  11145. // against the expression language, but not to prevent exploits that were enabled by exposing
  11146. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  11147. // practice and therefore we are not even trying to protect against interaction with an object
  11148. // explicitly exposed in this way.
  11149. //
  11150. // In general, it is not possible to access a Window object from an angular expression unless a
  11151. // window or some DOM object that has a reference to window is published onto a Scope.
  11152. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  11153. // native objects.
  11154. //
  11155. // See https://docs.angularjs.org/guide/security
  11156. function ensureSafeMemberName(name, fullExpression) {
  11157. if (name === "__defineGetter__" || name === "__defineSetter__"
  11158. || name === "__lookupGetter__" || name === "__lookupSetter__"
  11159. || name === "__proto__") {
  11160. throw $parseMinErr('isecfld',
  11161. 'Attempting to access a disallowed field in Angular expressions! '
  11162. + 'Expression: {0}', fullExpression);
  11163. }
  11164. return name;
  11165. }
  11166. function ensureSafeObject(obj, fullExpression) {
  11167. // nifty check if obj is Function that is fast and works across iframes and other contexts
  11168. if (obj) {
  11169. if (obj.constructor === obj) {
  11170. throw $parseMinErr('isecfn',
  11171. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11172. fullExpression);
  11173. } else if (// isWindow(obj)
  11174. obj.window === obj) {
  11175. throw $parseMinErr('isecwindow',
  11176. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  11177. fullExpression);
  11178. } else if (// isElement(obj)
  11179. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  11180. throw $parseMinErr('isecdom',
  11181. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  11182. fullExpression);
  11183. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  11184. obj === Object) {
  11185. throw $parseMinErr('isecobj',
  11186. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  11187. fullExpression);
  11188. }
  11189. }
  11190. return obj;
  11191. }
  11192. var CALL = Function.prototype.call;
  11193. var APPLY = Function.prototype.apply;
  11194. var BIND = Function.prototype.bind;
  11195. function ensureSafeFunction(obj, fullExpression) {
  11196. if (obj) {
  11197. if (obj.constructor === obj) {
  11198. throw $parseMinErr('isecfn',
  11199. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11200. fullExpression);
  11201. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  11202. throw $parseMinErr('isecff',
  11203. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  11204. fullExpression);
  11205. }
  11206. }
  11207. }
  11208. var OPERATORS = createMap();
  11209. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  11210. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  11211. /////////////////////////////////////////
  11212. /**
  11213. * @constructor
  11214. */
  11215. var Lexer = function(options) {
  11216. this.options = options;
  11217. };
  11218. Lexer.prototype = {
  11219. constructor: Lexer,
  11220. lex: function(text) {
  11221. this.text = text;
  11222. this.index = 0;
  11223. this.tokens = [];
  11224. while (this.index < this.text.length) {
  11225. var ch = this.text.charAt(this.index);
  11226. if (ch === '"' || ch === "'") {
  11227. this.readString(ch);
  11228. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  11229. this.readNumber();
  11230. } else if (this.isIdent(ch)) {
  11231. this.readIdent();
  11232. } else if (this.is(ch, '(){}[].,;:?')) {
  11233. this.tokens.push({index: this.index, text: ch});
  11234. this.index++;
  11235. } else if (this.isWhitespace(ch)) {
  11236. this.index++;
  11237. } else {
  11238. var ch2 = ch + this.peek();
  11239. var ch3 = ch2 + this.peek(2);
  11240. var op1 = OPERATORS[ch];
  11241. var op2 = OPERATORS[ch2];
  11242. var op3 = OPERATORS[ch3];
  11243. if (op1 || op2 || op3) {
  11244. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  11245. this.tokens.push({index: this.index, text: token, operator: true});
  11246. this.index += token.length;
  11247. } else {
  11248. this.throwError('Unexpected next character ', this.index, this.index + 1);
  11249. }
  11250. }
  11251. }
  11252. return this.tokens;
  11253. },
  11254. is: function(ch, chars) {
  11255. return chars.indexOf(ch) !== -1;
  11256. },
  11257. peek: function(i) {
  11258. var num = i || 1;
  11259. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  11260. },
  11261. isNumber: function(ch) {
  11262. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  11263. },
  11264. isWhitespace: function(ch) {
  11265. // IE treats non-breaking space as \u00A0
  11266. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  11267. ch === '\n' || ch === '\v' || ch === '\u00A0');
  11268. },
  11269. isIdent: function(ch) {
  11270. return ('a' <= ch && ch <= 'z' ||
  11271. 'A' <= ch && ch <= 'Z' ||
  11272. '_' === ch || ch === '$');
  11273. },
  11274. isExpOperator: function(ch) {
  11275. return (ch === '-' || ch === '+' || this.isNumber(ch));
  11276. },
  11277. throwError: function(error, start, end) {
  11278. end = end || this.index;
  11279. var colStr = (isDefined(start)
  11280. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  11281. : ' ' + end);
  11282. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  11283. error, colStr, this.text);
  11284. },
  11285. readNumber: function() {
  11286. var number = '';
  11287. var start = this.index;
  11288. while (this.index < this.text.length) {
  11289. var ch = lowercase(this.text.charAt(this.index));
  11290. if (ch == '.' || this.isNumber(ch)) {
  11291. number += ch;
  11292. } else {
  11293. var peekCh = this.peek();
  11294. if (ch == 'e' && this.isExpOperator(peekCh)) {
  11295. number += ch;
  11296. } else if (this.isExpOperator(ch) &&
  11297. peekCh && this.isNumber(peekCh) &&
  11298. number.charAt(number.length - 1) == 'e') {
  11299. number += ch;
  11300. } else if (this.isExpOperator(ch) &&
  11301. (!peekCh || !this.isNumber(peekCh)) &&
  11302. number.charAt(number.length - 1) == 'e') {
  11303. this.throwError('Invalid exponent');
  11304. } else {
  11305. break;
  11306. }
  11307. }
  11308. this.index++;
  11309. }
  11310. this.tokens.push({
  11311. index: start,
  11312. text: number,
  11313. constant: true,
  11314. value: Number(number)
  11315. });
  11316. },
  11317. readIdent: function() {
  11318. var start = this.index;
  11319. while (this.index < this.text.length) {
  11320. var ch = this.text.charAt(this.index);
  11321. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  11322. break;
  11323. }
  11324. this.index++;
  11325. }
  11326. this.tokens.push({
  11327. index: start,
  11328. text: this.text.slice(start, this.index),
  11329. identifier: true
  11330. });
  11331. },
  11332. readString: function(quote) {
  11333. var start = this.index;
  11334. this.index++;
  11335. var string = '';
  11336. var rawString = quote;
  11337. var escape = false;
  11338. while (this.index < this.text.length) {
  11339. var ch = this.text.charAt(this.index);
  11340. rawString += ch;
  11341. if (escape) {
  11342. if (ch === 'u') {
  11343. var hex = this.text.substring(this.index + 1, this.index + 5);
  11344. if (!hex.match(/[\da-f]{4}/i)) {
  11345. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  11346. }
  11347. this.index += 4;
  11348. string += String.fromCharCode(parseInt(hex, 16));
  11349. } else {
  11350. var rep = ESCAPE[ch];
  11351. string = string + (rep || ch);
  11352. }
  11353. escape = false;
  11354. } else if (ch === '\\') {
  11355. escape = true;
  11356. } else if (ch === quote) {
  11357. this.index++;
  11358. this.tokens.push({
  11359. index: start,
  11360. text: rawString,
  11361. constant: true,
  11362. value: string
  11363. });
  11364. return;
  11365. } else {
  11366. string += ch;
  11367. }
  11368. this.index++;
  11369. }
  11370. this.throwError('Unterminated quote', start);
  11371. }
  11372. };
  11373. var AST = function(lexer, options) {
  11374. this.lexer = lexer;
  11375. this.options = options;
  11376. };
  11377. AST.Program = 'Program';
  11378. AST.ExpressionStatement = 'ExpressionStatement';
  11379. AST.AssignmentExpression = 'AssignmentExpression';
  11380. AST.ConditionalExpression = 'ConditionalExpression';
  11381. AST.LogicalExpression = 'LogicalExpression';
  11382. AST.BinaryExpression = 'BinaryExpression';
  11383. AST.UnaryExpression = 'UnaryExpression';
  11384. AST.CallExpression = 'CallExpression';
  11385. AST.MemberExpression = 'MemberExpression';
  11386. AST.Identifier = 'Identifier';
  11387. AST.Literal = 'Literal';
  11388. AST.ArrayExpression = 'ArrayExpression';
  11389. AST.Property = 'Property';
  11390. AST.ObjectExpression = 'ObjectExpression';
  11391. AST.ThisExpression = 'ThisExpression';
  11392. // Internal use only
  11393. AST.NGValueParameter = 'NGValueParameter';
  11394. AST.prototype = {
  11395. ast: function(text) {
  11396. this.text = text;
  11397. this.tokens = this.lexer.lex(text);
  11398. var value = this.program();
  11399. if (this.tokens.length !== 0) {
  11400. this.throwError('is an unexpected token', this.tokens[0]);
  11401. }
  11402. return value;
  11403. },
  11404. program: function() {
  11405. var body = [];
  11406. while (true) {
  11407. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  11408. body.push(this.expressionStatement());
  11409. if (!this.expect(';')) {
  11410. return { type: AST.Program, body: body};
  11411. }
  11412. }
  11413. },
  11414. expressionStatement: function() {
  11415. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  11416. },
  11417. filterChain: function() {
  11418. var left = this.expression();
  11419. var token;
  11420. while ((token = this.expect('|'))) {
  11421. left = this.filter(left);
  11422. }
  11423. return left;
  11424. },
  11425. expression: function() {
  11426. return this.assignment();
  11427. },
  11428. assignment: function() {
  11429. var result = this.ternary();
  11430. if (this.expect('=')) {
  11431. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  11432. }
  11433. return result;
  11434. },
  11435. ternary: function() {
  11436. var test = this.logicalOR();
  11437. var alternate;
  11438. var consequent;
  11439. if (this.expect('?')) {
  11440. alternate = this.expression();
  11441. if (this.consume(':')) {
  11442. consequent = this.expression();
  11443. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  11444. }
  11445. }
  11446. return test;
  11447. },
  11448. logicalOR: function() {
  11449. var left = this.logicalAND();
  11450. while (this.expect('||')) {
  11451. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  11452. }
  11453. return left;
  11454. },
  11455. logicalAND: function() {
  11456. var left = this.equality();
  11457. while (this.expect('&&')) {
  11458. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  11459. }
  11460. return left;
  11461. },
  11462. equality: function() {
  11463. var left = this.relational();
  11464. var token;
  11465. while ((token = this.expect('==','!=','===','!=='))) {
  11466. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  11467. }
  11468. return left;
  11469. },
  11470. relational: function() {
  11471. var left = this.additive();
  11472. var token;
  11473. while ((token = this.expect('<', '>', '<=', '>='))) {
  11474. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  11475. }
  11476. return left;
  11477. },
  11478. additive: function() {
  11479. var left = this.multiplicative();
  11480. var token;
  11481. while ((token = this.expect('+','-'))) {
  11482. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  11483. }
  11484. return left;
  11485. },
  11486. multiplicative: function() {
  11487. var left = this.unary();
  11488. var token;
  11489. while ((token = this.expect('*','/','%'))) {
  11490. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  11491. }
  11492. return left;
  11493. },
  11494. unary: function() {
  11495. var token;
  11496. if ((token = this.expect('+', '-', '!'))) {
  11497. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  11498. } else {
  11499. return this.primary();
  11500. }
  11501. },
  11502. primary: function() {
  11503. var primary;
  11504. if (this.expect('(')) {
  11505. primary = this.filterChain();
  11506. this.consume(')');
  11507. } else if (this.expect('[')) {
  11508. primary = this.arrayDeclaration();
  11509. } else if (this.expect('{')) {
  11510. primary = this.object();
  11511. } else if (this.constants.hasOwnProperty(this.peek().text)) {
  11512. primary = copy(this.constants[this.consume().text]);
  11513. } else if (this.peek().identifier) {
  11514. primary = this.identifier();
  11515. } else if (this.peek().constant) {
  11516. primary = this.constant();
  11517. } else {
  11518. this.throwError('not a primary expression', this.peek());
  11519. }
  11520. var next;
  11521. while ((next = this.expect('(', '[', '.'))) {
  11522. if (next.text === '(') {
  11523. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  11524. this.consume(')');
  11525. } else if (next.text === '[') {
  11526. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  11527. this.consume(']');
  11528. } else if (next.text === '.') {
  11529. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  11530. } else {
  11531. this.throwError('IMPOSSIBLE');
  11532. }
  11533. }
  11534. return primary;
  11535. },
  11536. filter: function(baseExpression) {
  11537. var args = [baseExpression];
  11538. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  11539. while (this.expect(':')) {
  11540. args.push(this.expression());
  11541. }
  11542. return result;
  11543. },
  11544. parseArguments: function() {
  11545. var args = [];
  11546. if (this.peekToken().text !== ')') {
  11547. do {
  11548. args.push(this.expression());
  11549. } while (this.expect(','));
  11550. }
  11551. return args;
  11552. },
  11553. identifier: function() {
  11554. var token = this.consume();
  11555. if (!token.identifier) {
  11556. this.throwError('is not a valid identifier', token);
  11557. }
  11558. return { type: AST.Identifier, name: token.text };
  11559. },
  11560. constant: function() {
  11561. // TODO check that it is a constant
  11562. return { type: AST.Literal, value: this.consume().value };
  11563. },
  11564. arrayDeclaration: function() {
  11565. var elements = [];
  11566. if (this.peekToken().text !== ']') {
  11567. do {
  11568. if (this.peek(']')) {
  11569. // Support trailing commas per ES5.1.
  11570. break;
  11571. }
  11572. elements.push(this.expression());
  11573. } while (this.expect(','));
  11574. }
  11575. this.consume(']');
  11576. return { type: AST.ArrayExpression, elements: elements };
  11577. },
  11578. object: function() {
  11579. var properties = [], property;
  11580. if (this.peekToken().text !== '}') {
  11581. do {
  11582. if (this.peek('}')) {
  11583. // Support trailing commas per ES5.1.
  11584. break;
  11585. }
  11586. property = {type: AST.Property, kind: 'init'};
  11587. if (this.peek().constant) {
  11588. property.key = this.constant();
  11589. } else if (this.peek().identifier) {
  11590. property.key = this.identifier();
  11591. } else {
  11592. this.throwError("invalid key", this.peek());
  11593. }
  11594. this.consume(':');
  11595. property.value = this.expression();
  11596. properties.push(property);
  11597. } while (this.expect(','));
  11598. }
  11599. this.consume('}');
  11600. return {type: AST.ObjectExpression, properties: properties };
  11601. },
  11602. throwError: function(msg, token) {
  11603. throw $parseMinErr('syntax',
  11604. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  11605. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  11606. },
  11607. consume: function(e1) {
  11608. if (this.tokens.length === 0) {
  11609. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11610. }
  11611. var token = this.expect(e1);
  11612. if (!token) {
  11613. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  11614. }
  11615. return token;
  11616. },
  11617. peekToken: function() {
  11618. if (this.tokens.length === 0) {
  11619. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11620. }
  11621. return this.tokens[0];
  11622. },
  11623. peek: function(e1, e2, e3, e4) {
  11624. return this.peekAhead(0, e1, e2, e3, e4);
  11625. },
  11626. peekAhead: function(i, e1, e2, e3, e4) {
  11627. if (this.tokens.length > i) {
  11628. var token = this.tokens[i];
  11629. var t = token.text;
  11630. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  11631. (!e1 && !e2 && !e3 && !e4)) {
  11632. return token;
  11633. }
  11634. }
  11635. return false;
  11636. },
  11637. expect: function(e1, e2, e3, e4) {
  11638. var token = this.peek(e1, e2, e3, e4);
  11639. if (token) {
  11640. this.tokens.shift();
  11641. return token;
  11642. }
  11643. return false;
  11644. },
  11645. /* `undefined` is not a constant, it is an identifier,
  11646. * but using it as an identifier is not supported
  11647. */
  11648. constants: {
  11649. 'true': { type: AST.Literal, value: true },
  11650. 'false': { type: AST.Literal, value: false },
  11651. 'null': { type: AST.Literal, value: null },
  11652. 'undefined': {type: AST.Literal, value: undefined },
  11653. 'this': {type: AST.ThisExpression }
  11654. }
  11655. };
  11656. function ifDefined(v, d) {
  11657. return typeof v !== 'undefined' ? v : d;
  11658. }
  11659. function plusFn(l, r) {
  11660. if (typeof l === 'undefined') return r;
  11661. if (typeof r === 'undefined') return l;
  11662. return l + r;
  11663. }
  11664. function isStateless($filter, filterName) {
  11665. var fn = $filter(filterName);
  11666. return !fn.$stateful;
  11667. }
  11668. function findConstantAndWatchExpressions(ast, $filter) {
  11669. var allConstants;
  11670. var argsToWatch;
  11671. switch (ast.type) {
  11672. case AST.Program:
  11673. allConstants = true;
  11674. forEach(ast.body, function(expr) {
  11675. findConstantAndWatchExpressions(expr.expression, $filter);
  11676. allConstants = allConstants && expr.expression.constant;
  11677. });
  11678. ast.constant = allConstants;
  11679. break;
  11680. case AST.Literal:
  11681. ast.constant = true;
  11682. ast.toWatch = [];
  11683. break;
  11684. case AST.UnaryExpression:
  11685. findConstantAndWatchExpressions(ast.argument, $filter);
  11686. ast.constant = ast.argument.constant;
  11687. ast.toWatch = ast.argument.toWatch;
  11688. break;
  11689. case AST.BinaryExpression:
  11690. findConstantAndWatchExpressions(ast.left, $filter);
  11691. findConstantAndWatchExpressions(ast.right, $filter);
  11692. ast.constant = ast.left.constant && ast.right.constant;
  11693. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  11694. break;
  11695. case AST.LogicalExpression:
  11696. findConstantAndWatchExpressions(ast.left, $filter);
  11697. findConstantAndWatchExpressions(ast.right, $filter);
  11698. ast.constant = ast.left.constant && ast.right.constant;
  11699. ast.toWatch = ast.constant ? [] : [ast];
  11700. break;
  11701. case AST.ConditionalExpression:
  11702. findConstantAndWatchExpressions(ast.test, $filter);
  11703. findConstantAndWatchExpressions(ast.alternate, $filter);
  11704. findConstantAndWatchExpressions(ast.consequent, $filter);
  11705. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  11706. ast.toWatch = ast.constant ? [] : [ast];
  11707. break;
  11708. case AST.Identifier:
  11709. ast.constant = false;
  11710. ast.toWatch = [ast];
  11711. break;
  11712. case AST.MemberExpression:
  11713. findConstantAndWatchExpressions(ast.object, $filter);
  11714. if (ast.computed) {
  11715. findConstantAndWatchExpressions(ast.property, $filter);
  11716. }
  11717. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  11718. ast.toWatch = [ast];
  11719. break;
  11720. case AST.CallExpression:
  11721. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  11722. argsToWatch = [];
  11723. forEach(ast.arguments, function(expr) {
  11724. findConstantAndWatchExpressions(expr, $filter);
  11725. allConstants = allConstants && expr.constant;
  11726. if (!expr.constant) {
  11727. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11728. }
  11729. });
  11730. ast.constant = allConstants;
  11731. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  11732. break;
  11733. case AST.AssignmentExpression:
  11734. findConstantAndWatchExpressions(ast.left, $filter);
  11735. findConstantAndWatchExpressions(ast.right, $filter);
  11736. ast.constant = ast.left.constant && ast.right.constant;
  11737. ast.toWatch = [ast];
  11738. break;
  11739. case AST.ArrayExpression:
  11740. allConstants = true;
  11741. argsToWatch = [];
  11742. forEach(ast.elements, function(expr) {
  11743. findConstantAndWatchExpressions(expr, $filter);
  11744. allConstants = allConstants && expr.constant;
  11745. if (!expr.constant) {
  11746. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11747. }
  11748. });
  11749. ast.constant = allConstants;
  11750. ast.toWatch = argsToWatch;
  11751. break;
  11752. case AST.ObjectExpression:
  11753. allConstants = true;
  11754. argsToWatch = [];
  11755. forEach(ast.properties, function(property) {
  11756. findConstantAndWatchExpressions(property.value, $filter);
  11757. allConstants = allConstants && property.value.constant;
  11758. if (!property.value.constant) {
  11759. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  11760. }
  11761. });
  11762. ast.constant = allConstants;
  11763. ast.toWatch = argsToWatch;
  11764. break;
  11765. case AST.ThisExpression:
  11766. ast.constant = false;
  11767. ast.toWatch = [];
  11768. break;
  11769. }
  11770. }
  11771. function getInputs(body) {
  11772. if (body.length != 1) return;
  11773. var lastExpression = body[0].expression;
  11774. var candidate = lastExpression.toWatch;
  11775. if (candidate.length !== 1) return candidate;
  11776. return candidate[0] !== lastExpression ? candidate : undefined;
  11777. }
  11778. function isAssignable(ast) {
  11779. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  11780. }
  11781. function assignableAST(ast) {
  11782. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  11783. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  11784. }
  11785. }
  11786. function isLiteral(ast) {
  11787. return ast.body.length === 0 ||
  11788. ast.body.length === 1 && (
  11789. ast.body[0].expression.type === AST.Literal ||
  11790. ast.body[0].expression.type === AST.ArrayExpression ||
  11791. ast.body[0].expression.type === AST.ObjectExpression);
  11792. }
  11793. function isConstant(ast) {
  11794. return ast.constant;
  11795. }
  11796. function ASTCompiler(astBuilder, $filter) {
  11797. this.astBuilder = astBuilder;
  11798. this.$filter = $filter;
  11799. }
  11800. ASTCompiler.prototype = {
  11801. compile: function(expression, expensiveChecks) {
  11802. var self = this;
  11803. var ast = this.astBuilder.ast(expression);
  11804. this.state = {
  11805. nextId: 0,
  11806. filters: {},
  11807. expensiveChecks: expensiveChecks,
  11808. fn: {vars: [], body: [], own: {}},
  11809. assign: {vars: [], body: [], own: {}},
  11810. inputs: []
  11811. };
  11812. findConstantAndWatchExpressions(ast, self.$filter);
  11813. var extra = '';
  11814. var assignable;
  11815. this.stage = 'assign';
  11816. if ((assignable = assignableAST(ast))) {
  11817. this.state.computing = 'assign';
  11818. var result = this.nextId();
  11819. this.recurse(assignable, result);
  11820. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  11821. }
  11822. var toWatch = getInputs(ast.body);
  11823. self.stage = 'inputs';
  11824. forEach(toWatch, function(watch, key) {
  11825. var fnKey = 'fn' + key;
  11826. self.state[fnKey] = {vars: [], body: [], own: {}};
  11827. self.state.computing = fnKey;
  11828. var intoId = self.nextId();
  11829. self.recurse(watch, intoId);
  11830. self.return_(intoId);
  11831. self.state.inputs.push(fnKey);
  11832. watch.watchId = key;
  11833. });
  11834. this.state.computing = 'fn';
  11835. this.stage = 'main';
  11836. this.recurse(ast);
  11837. var fnString =
  11838. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  11839. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  11840. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  11841. this.filterPrefix() +
  11842. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  11843. extra +
  11844. this.watchFns() +
  11845. 'return fn;';
  11846. /* jshint -W054 */
  11847. var fn = (new Function('$filter',
  11848. 'ensureSafeMemberName',
  11849. 'ensureSafeObject',
  11850. 'ensureSafeFunction',
  11851. 'ifDefined',
  11852. 'plus',
  11853. 'text',
  11854. fnString))(
  11855. this.$filter,
  11856. ensureSafeMemberName,
  11857. ensureSafeObject,
  11858. ensureSafeFunction,
  11859. ifDefined,
  11860. plusFn,
  11861. expression);
  11862. /* jshint +W054 */
  11863. this.state = this.stage = undefined;
  11864. fn.literal = isLiteral(ast);
  11865. fn.constant = isConstant(ast);
  11866. return fn;
  11867. },
  11868. USE: 'use',
  11869. STRICT: 'strict',
  11870. watchFns: function() {
  11871. var result = [];
  11872. var fns = this.state.inputs;
  11873. var self = this;
  11874. forEach(fns, function(name) {
  11875. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  11876. });
  11877. if (fns.length) {
  11878. result.push('fn.inputs=[' + fns.join(',') + '];');
  11879. }
  11880. return result.join('');
  11881. },
  11882. generateFunction: function(name, params) {
  11883. return 'function(' + params + '){' +
  11884. this.varsPrefix(name) +
  11885. this.body(name) +
  11886. '};';
  11887. },
  11888. filterPrefix: function() {
  11889. var parts = [];
  11890. var self = this;
  11891. forEach(this.state.filters, function(id, filter) {
  11892. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  11893. });
  11894. if (parts.length) return 'var ' + parts.join(',') + ';';
  11895. return '';
  11896. },
  11897. varsPrefix: function(section) {
  11898. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  11899. },
  11900. body: function(section) {
  11901. return this.state[section].body.join('');
  11902. },
  11903. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  11904. var left, right, self = this, args, expression;
  11905. recursionFn = recursionFn || noop;
  11906. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  11907. intoId = intoId || this.nextId();
  11908. this.if_('i',
  11909. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  11910. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  11911. );
  11912. return;
  11913. }
  11914. switch (ast.type) {
  11915. case AST.Program:
  11916. forEach(ast.body, function(expression, pos) {
  11917. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  11918. if (pos !== ast.body.length - 1) {
  11919. self.current().body.push(right, ';');
  11920. } else {
  11921. self.return_(right);
  11922. }
  11923. });
  11924. break;
  11925. case AST.Literal:
  11926. expression = this.escape(ast.value);
  11927. this.assign(intoId, expression);
  11928. recursionFn(expression);
  11929. break;
  11930. case AST.UnaryExpression:
  11931. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  11932. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  11933. this.assign(intoId, expression);
  11934. recursionFn(expression);
  11935. break;
  11936. case AST.BinaryExpression:
  11937. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  11938. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  11939. if (ast.operator === '+') {
  11940. expression = this.plus(left, right);
  11941. } else if (ast.operator === '-') {
  11942. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  11943. } else {
  11944. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  11945. }
  11946. this.assign(intoId, expression);
  11947. recursionFn(expression);
  11948. break;
  11949. case AST.LogicalExpression:
  11950. intoId = intoId || this.nextId();
  11951. self.recurse(ast.left, intoId);
  11952. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  11953. recursionFn(intoId);
  11954. break;
  11955. case AST.ConditionalExpression:
  11956. intoId = intoId || this.nextId();
  11957. self.recurse(ast.test, intoId);
  11958. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  11959. recursionFn(intoId);
  11960. break;
  11961. case AST.Identifier:
  11962. intoId = intoId || this.nextId();
  11963. if (nameId) {
  11964. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  11965. nameId.computed = false;
  11966. nameId.name = ast.name;
  11967. }
  11968. ensureSafeMemberName(ast.name);
  11969. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  11970. function() {
  11971. self.if_(self.stage === 'inputs' || 's', function() {
  11972. if (create && create !== 1) {
  11973. self.if_(
  11974. self.not(self.nonComputedMember('s', ast.name)),
  11975. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  11976. }
  11977. self.assign(intoId, self.nonComputedMember('s', ast.name));
  11978. });
  11979. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  11980. );
  11981. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  11982. self.addEnsureSafeObject(intoId);
  11983. }
  11984. recursionFn(intoId);
  11985. break;
  11986. case AST.MemberExpression:
  11987. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  11988. intoId = intoId || this.nextId();
  11989. self.recurse(ast.object, left, undefined, function() {
  11990. self.if_(self.notNull(left), function() {
  11991. if (ast.computed) {
  11992. right = self.nextId();
  11993. self.recurse(ast.property, right);
  11994. self.addEnsureSafeMemberName(right);
  11995. if (create && create !== 1) {
  11996. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  11997. }
  11998. expression = self.ensureSafeObject(self.computedMember(left, right));
  11999. self.assign(intoId, expression);
  12000. if (nameId) {
  12001. nameId.computed = true;
  12002. nameId.name = right;
  12003. }
  12004. } else {
  12005. ensureSafeMemberName(ast.property.name);
  12006. if (create && create !== 1) {
  12007. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  12008. }
  12009. expression = self.nonComputedMember(left, ast.property.name);
  12010. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  12011. expression = self.ensureSafeObject(expression);
  12012. }
  12013. self.assign(intoId, expression);
  12014. if (nameId) {
  12015. nameId.computed = false;
  12016. nameId.name = ast.property.name;
  12017. }
  12018. }
  12019. }, function() {
  12020. self.assign(intoId, 'undefined');
  12021. });
  12022. recursionFn(intoId);
  12023. }, !!create);
  12024. break;
  12025. case AST.CallExpression:
  12026. intoId = intoId || this.nextId();
  12027. if (ast.filter) {
  12028. right = self.filter(ast.callee.name);
  12029. args = [];
  12030. forEach(ast.arguments, function(expr) {
  12031. var argument = self.nextId();
  12032. self.recurse(expr, argument);
  12033. args.push(argument);
  12034. });
  12035. expression = right + '(' + args.join(',') + ')';
  12036. self.assign(intoId, expression);
  12037. recursionFn(intoId);
  12038. } else {
  12039. right = self.nextId();
  12040. left = {};
  12041. args = [];
  12042. self.recurse(ast.callee, right, left, function() {
  12043. self.if_(self.notNull(right), function() {
  12044. self.addEnsureSafeFunction(right);
  12045. forEach(ast.arguments, function(expr) {
  12046. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12047. args.push(self.ensureSafeObject(argument));
  12048. });
  12049. });
  12050. if (left.name) {
  12051. if (!self.state.expensiveChecks) {
  12052. self.addEnsureSafeObject(left.context);
  12053. }
  12054. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  12055. } else {
  12056. expression = right + '(' + args.join(',') + ')';
  12057. }
  12058. expression = self.ensureSafeObject(expression);
  12059. self.assign(intoId, expression);
  12060. }, function() {
  12061. self.assign(intoId, 'undefined');
  12062. });
  12063. recursionFn(intoId);
  12064. });
  12065. }
  12066. break;
  12067. case AST.AssignmentExpression:
  12068. right = this.nextId();
  12069. left = {};
  12070. if (!isAssignable(ast.left)) {
  12071. throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
  12072. }
  12073. this.recurse(ast.left, undefined, left, function() {
  12074. self.if_(self.notNull(left.context), function() {
  12075. self.recurse(ast.right, right);
  12076. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  12077. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  12078. self.assign(intoId, expression);
  12079. recursionFn(intoId || expression);
  12080. });
  12081. }, 1);
  12082. break;
  12083. case AST.ArrayExpression:
  12084. args = [];
  12085. forEach(ast.elements, function(expr) {
  12086. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12087. args.push(argument);
  12088. });
  12089. });
  12090. expression = '[' + args.join(',') + ']';
  12091. this.assign(intoId, expression);
  12092. recursionFn(expression);
  12093. break;
  12094. case AST.ObjectExpression:
  12095. args = [];
  12096. forEach(ast.properties, function(property) {
  12097. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  12098. args.push(self.escape(
  12099. property.key.type === AST.Identifier ? property.key.name :
  12100. ('' + property.key.value)) +
  12101. ':' + expr);
  12102. });
  12103. });
  12104. expression = '{' + args.join(',') + '}';
  12105. this.assign(intoId, expression);
  12106. recursionFn(expression);
  12107. break;
  12108. case AST.ThisExpression:
  12109. this.assign(intoId, 's');
  12110. recursionFn('s');
  12111. break;
  12112. case AST.NGValueParameter:
  12113. this.assign(intoId, 'v');
  12114. recursionFn('v');
  12115. break;
  12116. }
  12117. },
  12118. getHasOwnProperty: function(element, property) {
  12119. var key = element + '.' + property;
  12120. var own = this.current().own;
  12121. if (!own.hasOwnProperty(key)) {
  12122. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  12123. }
  12124. return own[key];
  12125. },
  12126. assign: function(id, value) {
  12127. if (!id) return;
  12128. this.current().body.push(id, '=', value, ';');
  12129. return id;
  12130. },
  12131. filter: function(filterName) {
  12132. if (!this.state.filters.hasOwnProperty(filterName)) {
  12133. this.state.filters[filterName] = this.nextId(true);
  12134. }
  12135. return this.state.filters[filterName];
  12136. },
  12137. ifDefined: function(id, defaultValue) {
  12138. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  12139. },
  12140. plus: function(left, right) {
  12141. return 'plus(' + left + ',' + right + ')';
  12142. },
  12143. return_: function(id) {
  12144. this.current().body.push('return ', id, ';');
  12145. },
  12146. if_: function(test, alternate, consequent) {
  12147. if (test === true) {
  12148. alternate();
  12149. } else {
  12150. var body = this.current().body;
  12151. body.push('if(', test, '){');
  12152. alternate();
  12153. body.push('}');
  12154. if (consequent) {
  12155. body.push('else{');
  12156. consequent();
  12157. body.push('}');
  12158. }
  12159. }
  12160. },
  12161. not: function(expression) {
  12162. return '!(' + expression + ')';
  12163. },
  12164. notNull: function(expression) {
  12165. return expression + '!=null';
  12166. },
  12167. nonComputedMember: function(left, right) {
  12168. return left + '.' + right;
  12169. },
  12170. computedMember: function(left, right) {
  12171. return left + '[' + right + ']';
  12172. },
  12173. member: function(left, right, computed) {
  12174. if (computed) return this.computedMember(left, right);
  12175. return this.nonComputedMember(left, right);
  12176. },
  12177. addEnsureSafeObject: function(item) {
  12178. this.current().body.push(this.ensureSafeObject(item), ';');
  12179. },
  12180. addEnsureSafeMemberName: function(item) {
  12181. this.current().body.push(this.ensureSafeMemberName(item), ';');
  12182. },
  12183. addEnsureSafeFunction: function(item) {
  12184. this.current().body.push(this.ensureSafeFunction(item), ';');
  12185. },
  12186. ensureSafeObject: function(item) {
  12187. return 'ensureSafeObject(' + item + ',text)';
  12188. },
  12189. ensureSafeMemberName: function(item) {
  12190. return 'ensureSafeMemberName(' + item + ',text)';
  12191. },
  12192. ensureSafeFunction: function(item) {
  12193. return 'ensureSafeFunction(' + item + ',text)';
  12194. },
  12195. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12196. var self = this;
  12197. return function() {
  12198. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  12199. };
  12200. },
  12201. lazyAssign: function(id, value) {
  12202. var self = this;
  12203. return function() {
  12204. self.assign(id, value);
  12205. };
  12206. },
  12207. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  12208. stringEscapeFn: function(c) {
  12209. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  12210. },
  12211. escape: function(value) {
  12212. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  12213. if (isNumber(value)) return value.toString();
  12214. if (value === true) return 'true';
  12215. if (value === false) return 'false';
  12216. if (value === null) return 'null';
  12217. if (typeof value === 'undefined') return 'undefined';
  12218. throw $parseMinErr('esc', 'IMPOSSIBLE');
  12219. },
  12220. nextId: function(skip, init) {
  12221. var id = 'v' + (this.state.nextId++);
  12222. if (!skip) {
  12223. this.current().vars.push(id + (init ? '=' + init : ''));
  12224. }
  12225. return id;
  12226. },
  12227. current: function() {
  12228. return this.state[this.state.computing];
  12229. }
  12230. };
  12231. function ASTInterpreter(astBuilder, $filter) {
  12232. this.astBuilder = astBuilder;
  12233. this.$filter = $filter;
  12234. }
  12235. ASTInterpreter.prototype = {
  12236. compile: function(expression, expensiveChecks) {
  12237. var self = this;
  12238. var ast = this.astBuilder.ast(expression);
  12239. this.expression = expression;
  12240. this.expensiveChecks = expensiveChecks;
  12241. findConstantAndWatchExpressions(ast, self.$filter);
  12242. var assignable;
  12243. var assign;
  12244. if ((assignable = assignableAST(ast))) {
  12245. assign = this.recurse(assignable);
  12246. }
  12247. var toWatch = getInputs(ast.body);
  12248. var inputs;
  12249. if (toWatch) {
  12250. inputs = [];
  12251. forEach(toWatch, function(watch, key) {
  12252. var input = self.recurse(watch);
  12253. watch.input = input;
  12254. inputs.push(input);
  12255. watch.watchId = key;
  12256. });
  12257. }
  12258. var expressions = [];
  12259. forEach(ast.body, function(expression) {
  12260. expressions.push(self.recurse(expression.expression));
  12261. });
  12262. var fn = ast.body.length === 0 ? function() {} :
  12263. ast.body.length === 1 ? expressions[0] :
  12264. function(scope, locals) {
  12265. var lastValue;
  12266. forEach(expressions, function(exp) {
  12267. lastValue = exp(scope, locals);
  12268. });
  12269. return lastValue;
  12270. };
  12271. if (assign) {
  12272. fn.assign = function(scope, value, locals) {
  12273. return assign(scope, locals, value);
  12274. };
  12275. }
  12276. if (inputs) {
  12277. fn.inputs = inputs;
  12278. }
  12279. fn.literal = isLiteral(ast);
  12280. fn.constant = isConstant(ast);
  12281. return fn;
  12282. },
  12283. recurse: function(ast, context, create) {
  12284. var left, right, self = this, args, expression;
  12285. if (ast.input) {
  12286. return this.inputs(ast.input, ast.watchId);
  12287. }
  12288. switch (ast.type) {
  12289. case AST.Literal:
  12290. return this.value(ast.value, context);
  12291. case AST.UnaryExpression:
  12292. right = this.recurse(ast.argument);
  12293. return this['unary' + ast.operator](right, context);
  12294. case AST.BinaryExpression:
  12295. left = this.recurse(ast.left);
  12296. right = this.recurse(ast.right);
  12297. return this['binary' + ast.operator](left, right, context);
  12298. case AST.LogicalExpression:
  12299. left = this.recurse(ast.left);
  12300. right = this.recurse(ast.right);
  12301. return this['binary' + ast.operator](left, right, context);
  12302. case AST.ConditionalExpression:
  12303. return this['ternary?:'](
  12304. this.recurse(ast.test),
  12305. this.recurse(ast.alternate),
  12306. this.recurse(ast.consequent),
  12307. context
  12308. );
  12309. case AST.Identifier:
  12310. ensureSafeMemberName(ast.name, self.expression);
  12311. return self.identifier(ast.name,
  12312. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  12313. context, create, self.expression);
  12314. case AST.MemberExpression:
  12315. left = this.recurse(ast.object, false, !!create);
  12316. if (!ast.computed) {
  12317. ensureSafeMemberName(ast.property.name, self.expression);
  12318. right = ast.property.name;
  12319. }
  12320. if (ast.computed) right = this.recurse(ast.property);
  12321. return ast.computed ?
  12322. this.computedMember(left, right, context, create, self.expression) :
  12323. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  12324. case AST.CallExpression:
  12325. args = [];
  12326. forEach(ast.arguments, function(expr) {
  12327. args.push(self.recurse(expr));
  12328. });
  12329. if (ast.filter) right = this.$filter(ast.callee.name);
  12330. if (!ast.filter) right = this.recurse(ast.callee, true);
  12331. return ast.filter ?
  12332. function(scope, locals, assign, inputs) {
  12333. var values = [];
  12334. for (var i = 0; i < args.length; ++i) {
  12335. values.push(args[i](scope, locals, assign, inputs));
  12336. }
  12337. var value = right.apply(undefined, values, inputs);
  12338. return context ? {context: undefined, name: undefined, value: value} : value;
  12339. } :
  12340. function(scope, locals, assign, inputs) {
  12341. var rhs = right(scope, locals, assign, inputs);
  12342. var value;
  12343. if (rhs.value != null) {
  12344. ensureSafeObject(rhs.context, self.expression);
  12345. ensureSafeFunction(rhs.value, self.expression);
  12346. var values = [];
  12347. for (var i = 0; i < args.length; ++i) {
  12348. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  12349. }
  12350. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  12351. }
  12352. return context ? {value: value} : value;
  12353. };
  12354. case AST.AssignmentExpression:
  12355. left = this.recurse(ast.left, true, 1);
  12356. right = this.recurse(ast.right);
  12357. return function(scope, locals, assign, inputs) {
  12358. var lhs = left(scope, locals, assign, inputs);
  12359. var rhs = right(scope, locals, assign, inputs);
  12360. ensureSafeObject(lhs.value, self.expression);
  12361. lhs.context[lhs.name] = rhs;
  12362. return context ? {value: rhs} : rhs;
  12363. };
  12364. case AST.ArrayExpression:
  12365. args = [];
  12366. forEach(ast.elements, function(expr) {
  12367. args.push(self.recurse(expr));
  12368. });
  12369. return function(scope, locals, assign, inputs) {
  12370. var value = [];
  12371. for (var i = 0; i < args.length; ++i) {
  12372. value.push(args[i](scope, locals, assign, inputs));
  12373. }
  12374. return context ? {value: value} : value;
  12375. };
  12376. case AST.ObjectExpression:
  12377. args = [];
  12378. forEach(ast.properties, function(property) {
  12379. args.push({key: property.key.type === AST.Identifier ?
  12380. property.key.name :
  12381. ('' + property.key.value),
  12382. value: self.recurse(property.value)
  12383. });
  12384. });
  12385. return function(scope, locals, assign, inputs) {
  12386. var value = {};
  12387. for (var i = 0; i < args.length; ++i) {
  12388. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  12389. }
  12390. return context ? {value: value} : value;
  12391. };
  12392. case AST.ThisExpression:
  12393. return function(scope) {
  12394. return context ? {value: scope} : scope;
  12395. };
  12396. case AST.NGValueParameter:
  12397. return function(scope, locals, assign, inputs) {
  12398. return context ? {value: assign} : assign;
  12399. };
  12400. }
  12401. },
  12402. 'unary+': function(argument, context) {
  12403. return function(scope, locals, assign, inputs) {
  12404. var arg = argument(scope, locals, assign, inputs);
  12405. if (isDefined(arg)) {
  12406. arg = +arg;
  12407. } else {
  12408. arg = 0;
  12409. }
  12410. return context ? {value: arg} : arg;
  12411. };
  12412. },
  12413. 'unary-': function(argument, context) {
  12414. return function(scope, locals, assign, inputs) {
  12415. var arg = argument(scope, locals, assign, inputs);
  12416. if (isDefined(arg)) {
  12417. arg = -arg;
  12418. } else {
  12419. arg = 0;
  12420. }
  12421. return context ? {value: arg} : arg;
  12422. };
  12423. },
  12424. 'unary!': function(argument, context) {
  12425. return function(scope, locals, assign, inputs) {
  12426. var arg = !argument(scope, locals, assign, inputs);
  12427. return context ? {value: arg} : arg;
  12428. };
  12429. },
  12430. 'binary+': function(left, right, context) {
  12431. return function(scope, locals, assign, inputs) {
  12432. var lhs = left(scope, locals, assign, inputs);
  12433. var rhs = right(scope, locals, assign, inputs);
  12434. var arg = plusFn(lhs, rhs);
  12435. return context ? {value: arg} : arg;
  12436. };
  12437. },
  12438. 'binary-': function(left, right, context) {
  12439. return function(scope, locals, assign, inputs) {
  12440. var lhs = left(scope, locals, assign, inputs);
  12441. var rhs = right(scope, locals, assign, inputs);
  12442. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  12443. return context ? {value: arg} : arg;
  12444. };
  12445. },
  12446. 'binary*': function(left, right, context) {
  12447. return function(scope, locals, assign, inputs) {
  12448. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  12449. return context ? {value: arg} : arg;
  12450. };
  12451. },
  12452. 'binary/': function(left, right, context) {
  12453. return function(scope, locals, assign, inputs) {
  12454. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  12455. return context ? {value: arg} : arg;
  12456. };
  12457. },
  12458. 'binary%': function(left, right, context) {
  12459. return function(scope, locals, assign, inputs) {
  12460. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  12461. return context ? {value: arg} : arg;
  12462. };
  12463. },
  12464. 'binary===': function(left, right, context) {
  12465. return function(scope, locals, assign, inputs) {
  12466. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  12467. return context ? {value: arg} : arg;
  12468. };
  12469. },
  12470. 'binary!==': function(left, right, context) {
  12471. return function(scope, locals, assign, inputs) {
  12472. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  12473. return context ? {value: arg} : arg;
  12474. };
  12475. },
  12476. 'binary==': function(left, right, context) {
  12477. return function(scope, locals, assign, inputs) {
  12478. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  12479. return context ? {value: arg} : arg;
  12480. };
  12481. },
  12482. 'binary!=': function(left, right, context) {
  12483. return function(scope, locals, assign, inputs) {
  12484. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  12485. return context ? {value: arg} : arg;
  12486. };
  12487. },
  12488. 'binary<': function(left, right, context) {
  12489. return function(scope, locals, assign, inputs) {
  12490. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  12491. return context ? {value: arg} : arg;
  12492. };
  12493. },
  12494. 'binary>': function(left, right, context) {
  12495. return function(scope, locals, assign, inputs) {
  12496. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  12497. return context ? {value: arg} : arg;
  12498. };
  12499. },
  12500. 'binary<=': function(left, right, context) {
  12501. return function(scope, locals, assign, inputs) {
  12502. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  12503. return context ? {value: arg} : arg;
  12504. };
  12505. },
  12506. 'binary>=': function(left, right, context) {
  12507. return function(scope, locals, assign, inputs) {
  12508. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  12509. return context ? {value: arg} : arg;
  12510. };
  12511. },
  12512. 'binary&&': function(left, right, context) {
  12513. return function(scope, locals, assign, inputs) {
  12514. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  12515. return context ? {value: arg} : arg;
  12516. };
  12517. },
  12518. 'binary||': function(left, right, context) {
  12519. return function(scope, locals, assign, inputs) {
  12520. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  12521. return context ? {value: arg} : arg;
  12522. };
  12523. },
  12524. 'ternary?:': function(test, alternate, consequent, context) {
  12525. return function(scope, locals, assign, inputs) {
  12526. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  12527. return context ? {value: arg} : arg;
  12528. };
  12529. },
  12530. value: function(value, context) {
  12531. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  12532. },
  12533. identifier: function(name, expensiveChecks, context, create, expression) {
  12534. return function(scope, locals, assign, inputs) {
  12535. var base = locals && (name in locals) ? locals : scope;
  12536. if (create && create !== 1 && base && !(base[name])) {
  12537. base[name] = {};
  12538. }
  12539. var value = base ? base[name] : undefined;
  12540. if (expensiveChecks) {
  12541. ensureSafeObject(value, expression);
  12542. }
  12543. if (context) {
  12544. return {context: base, name: name, value: value};
  12545. } else {
  12546. return value;
  12547. }
  12548. };
  12549. },
  12550. computedMember: function(left, right, context, create, expression) {
  12551. return function(scope, locals, assign, inputs) {
  12552. var lhs = left(scope, locals, assign, inputs);
  12553. var rhs;
  12554. var value;
  12555. if (lhs != null) {
  12556. rhs = right(scope, locals, assign, inputs);
  12557. ensureSafeMemberName(rhs, expression);
  12558. if (create && create !== 1 && lhs && !(lhs[rhs])) {
  12559. lhs[rhs] = {};
  12560. }
  12561. value = lhs[rhs];
  12562. ensureSafeObject(value, expression);
  12563. }
  12564. if (context) {
  12565. return {context: lhs, name: rhs, value: value};
  12566. } else {
  12567. return value;
  12568. }
  12569. };
  12570. },
  12571. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  12572. return function(scope, locals, assign, inputs) {
  12573. var lhs = left(scope, locals, assign, inputs);
  12574. if (create && create !== 1 && lhs && !(lhs[right])) {
  12575. lhs[right] = {};
  12576. }
  12577. var value = lhs != null ? lhs[right] : undefined;
  12578. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  12579. ensureSafeObject(value, expression);
  12580. }
  12581. if (context) {
  12582. return {context: lhs, name: right, value: value};
  12583. } else {
  12584. return value;
  12585. }
  12586. };
  12587. },
  12588. inputs: function(input, watchId) {
  12589. return function(scope, value, locals, inputs) {
  12590. if (inputs) return inputs[watchId];
  12591. return input(scope, value, locals);
  12592. };
  12593. }
  12594. };
  12595. /**
  12596. * @constructor
  12597. */
  12598. var Parser = function(lexer, $filter, options) {
  12599. this.lexer = lexer;
  12600. this.$filter = $filter;
  12601. this.options = options;
  12602. this.ast = new AST(this.lexer);
  12603. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  12604. new ASTCompiler(this.ast, $filter);
  12605. };
  12606. Parser.prototype = {
  12607. constructor: Parser,
  12608. parse: function(text) {
  12609. return this.astCompiler.compile(text, this.options.expensiveChecks);
  12610. }
  12611. };
  12612. //////////////////////////////////////////////////
  12613. // Parser helper functions
  12614. //////////////////////////////////////////////////
  12615. function setter(obj, path, setValue, fullExp) {
  12616. ensureSafeObject(obj, fullExp);
  12617. var element = path.split('.'), key;
  12618. for (var i = 0; element.length > 1; i++) {
  12619. key = ensureSafeMemberName(element.shift(), fullExp);
  12620. var propertyObj = ensureSafeObject(obj[key], fullExp);
  12621. if (!propertyObj) {
  12622. propertyObj = {};
  12623. obj[key] = propertyObj;
  12624. }
  12625. obj = propertyObj;
  12626. }
  12627. key = ensureSafeMemberName(element.shift(), fullExp);
  12628. ensureSafeObject(obj[key], fullExp);
  12629. obj[key] = setValue;
  12630. return setValue;
  12631. }
  12632. var getterFnCacheDefault = createMap();
  12633. var getterFnCacheExpensive = createMap();
  12634. function isPossiblyDangerousMemberName(name) {
  12635. return name == 'constructor';
  12636. }
  12637. var objectValueOf = Object.prototype.valueOf;
  12638. function getValueOf(value) {
  12639. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  12640. }
  12641. ///////////////////////////////////
  12642. /**
  12643. * @ngdoc service
  12644. * @name $parse
  12645. * @kind function
  12646. *
  12647. * @description
  12648. *
  12649. * Converts Angular {@link guide/expression expression} into a function.
  12650. *
  12651. * ```js
  12652. * var getter = $parse('user.name');
  12653. * var setter = getter.assign;
  12654. * var context = {user:{name:'angular'}};
  12655. * var locals = {user:{name:'local'}};
  12656. *
  12657. * expect(getter(context)).toEqual('angular');
  12658. * setter(context, 'newValue');
  12659. * expect(context.user.name).toEqual('newValue');
  12660. * expect(getter(context, locals)).toEqual('local');
  12661. * ```
  12662. *
  12663. *
  12664. * @param {string} expression String expression to compile.
  12665. * @returns {function(context, locals)} a function which represents the compiled expression:
  12666. *
  12667. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12668. * are evaluated against (typically a scope object).
  12669. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12670. * `context`.
  12671. *
  12672. * The returned function also has the following properties:
  12673. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  12674. * literal.
  12675. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  12676. * constant literals.
  12677. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  12678. * set to a function to change its value on the given context.
  12679. *
  12680. */
  12681. /**
  12682. * @ngdoc provider
  12683. * @name $parseProvider
  12684. *
  12685. * @description
  12686. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  12687. * service.
  12688. */
  12689. function $ParseProvider() {
  12690. var cacheDefault = createMap();
  12691. var cacheExpensive = createMap();
  12692. this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
  12693. var $parseOptions = {
  12694. csp: $sniffer.csp,
  12695. expensiveChecks: false
  12696. },
  12697. $parseOptionsExpensive = {
  12698. csp: $sniffer.csp,
  12699. expensiveChecks: true
  12700. };
  12701. return function $parse(exp, interceptorFn, expensiveChecks) {
  12702. var parsedExpression, oneTime, cacheKey;
  12703. switch (typeof exp) {
  12704. case 'string':
  12705. exp = exp.trim();
  12706. cacheKey = exp;
  12707. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  12708. parsedExpression = cache[cacheKey];
  12709. if (!parsedExpression) {
  12710. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  12711. oneTime = true;
  12712. exp = exp.substring(2);
  12713. }
  12714. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  12715. var lexer = new Lexer(parseOptions);
  12716. var parser = new Parser(lexer, $filter, parseOptions);
  12717. parsedExpression = parser.parse(exp);
  12718. if (parsedExpression.constant) {
  12719. parsedExpression.$$watchDelegate = constantWatchDelegate;
  12720. } else if (oneTime) {
  12721. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  12722. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  12723. } else if (parsedExpression.inputs) {
  12724. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  12725. }
  12726. cache[cacheKey] = parsedExpression;
  12727. }
  12728. return addInterceptor(parsedExpression, interceptorFn);
  12729. case 'function':
  12730. return addInterceptor(exp, interceptorFn);
  12731. default:
  12732. return noop;
  12733. }
  12734. };
  12735. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  12736. if (newValue == null || oldValueOfValue == null) { // null/undefined
  12737. return newValue === oldValueOfValue;
  12738. }
  12739. if (typeof newValue === 'object') {
  12740. // attempt to convert the value to a primitive type
  12741. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  12742. // be cheaply dirty-checked
  12743. newValue = getValueOf(newValue);
  12744. if (typeof newValue === 'object') {
  12745. // objects/arrays are not supported - deep-watching them would be too expensive
  12746. return false;
  12747. }
  12748. // fall-through to the primitive equality check
  12749. }
  12750. //Primitive or NaN
  12751. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  12752. }
  12753. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  12754. var inputExpressions = parsedExpression.inputs;
  12755. var lastResult;
  12756. if (inputExpressions.length === 1) {
  12757. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12758. inputExpressions = inputExpressions[0];
  12759. return scope.$watch(function expressionInputWatch(scope) {
  12760. var newInputValue = inputExpressions(scope);
  12761. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  12762. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  12763. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  12764. }
  12765. return lastResult;
  12766. }, listener, objectEquality, prettyPrintExpression);
  12767. }
  12768. var oldInputValueOfValues = [];
  12769. var oldInputValues = [];
  12770. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12771. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12772. oldInputValues[i] = null;
  12773. }
  12774. return scope.$watch(function expressionInputsWatch(scope) {
  12775. var changed = false;
  12776. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12777. var newInputValue = inputExpressions[i](scope);
  12778. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  12779. oldInputValues[i] = newInputValue;
  12780. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  12781. }
  12782. }
  12783. if (changed) {
  12784. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  12785. }
  12786. return lastResult;
  12787. }, listener, objectEquality, prettyPrintExpression);
  12788. }
  12789. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12790. var unwatch, lastValue;
  12791. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12792. return parsedExpression(scope);
  12793. }, function oneTimeListener(value, old, scope) {
  12794. lastValue = value;
  12795. if (isFunction(listener)) {
  12796. listener.apply(this, arguments);
  12797. }
  12798. if (isDefined(value)) {
  12799. scope.$$postDigest(function() {
  12800. if (isDefined(lastValue)) {
  12801. unwatch();
  12802. }
  12803. });
  12804. }
  12805. }, objectEquality);
  12806. }
  12807. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12808. var unwatch, lastValue;
  12809. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12810. return parsedExpression(scope);
  12811. }, function oneTimeListener(value, old, scope) {
  12812. lastValue = value;
  12813. if (isFunction(listener)) {
  12814. listener.call(this, value, old, scope);
  12815. }
  12816. if (isAllDefined(value)) {
  12817. scope.$$postDigest(function() {
  12818. if (isAllDefined(lastValue)) unwatch();
  12819. });
  12820. }
  12821. }, objectEquality);
  12822. function isAllDefined(value) {
  12823. var allDefined = true;
  12824. forEach(value, function(val) {
  12825. if (!isDefined(val)) allDefined = false;
  12826. });
  12827. return allDefined;
  12828. }
  12829. }
  12830. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12831. var unwatch;
  12832. return unwatch = scope.$watch(function constantWatch(scope) {
  12833. return parsedExpression(scope);
  12834. }, function constantListener(value, old, scope) {
  12835. if (isFunction(listener)) {
  12836. listener.apply(this, arguments);
  12837. }
  12838. unwatch();
  12839. }, objectEquality);
  12840. }
  12841. function addInterceptor(parsedExpression, interceptorFn) {
  12842. if (!interceptorFn) return parsedExpression;
  12843. var watchDelegate = parsedExpression.$$watchDelegate;
  12844. var regularWatch =
  12845. watchDelegate !== oneTimeLiteralWatchDelegate &&
  12846. watchDelegate !== oneTimeWatchDelegate;
  12847. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  12848. var value = parsedExpression(scope, locals, assign, inputs);
  12849. return interceptorFn(value, scope, locals);
  12850. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  12851. var value = parsedExpression(scope, locals, assign, inputs);
  12852. var result = interceptorFn(value, scope, locals);
  12853. // we only return the interceptor's result if the
  12854. // initial value is defined (for bind-once)
  12855. return isDefined(value) ? result : value;
  12856. };
  12857. // Propagate $$watchDelegates other then inputsWatchDelegate
  12858. if (parsedExpression.$$watchDelegate &&
  12859. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  12860. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  12861. } else if (!interceptorFn.$stateful) {
  12862. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  12863. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  12864. fn.$$watchDelegate = inputsWatchDelegate;
  12865. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  12866. }
  12867. return fn;
  12868. }
  12869. }];
  12870. }
  12871. /**
  12872. * @ngdoc service
  12873. * @name $q
  12874. * @requires $rootScope
  12875. *
  12876. * @description
  12877. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  12878. * when they are done processing.
  12879. *
  12880. * This is an implementation of promises/deferred objects inspired by
  12881. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  12882. *
  12883. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  12884. * implementations, and the other which resembles ES6 promises to some degree.
  12885. *
  12886. * # $q constructor
  12887. *
  12888. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  12889. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  12890. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  12891. *
  12892. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  12893. * available yet.
  12894. *
  12895. * It can be used like so:
  12896. *
  12897. * ```js
  12898. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  12899. * // are available in the current lexical scope (they could have been injected or passed in).
  12900. *
  12901. * function asyncGreet(name) {
  12902. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  12903. * return $q(function(resolve, reject) {
  12904. * setTimeout(function() {
  12905. * if (okToGreet(name)) {
  12906. * resolve('Hello, ' + name + '!');
  12907. * } else {
  12908. * reject('Greeting ' + name + ' is not allowed.');
  12909. * }
  12910. * }, 1000);
  12911. * });
  12912. * }
  12913. *
  12914. * var promise = asyncGreet('Robin Hood');
  12915. * promise.then(function(greeting) {
  12916. * alert('Success: ' + greeting);
  12917. * }, function(reason) {
  12918. * alert('Failed: ' + reason);
  12919. * });
  12920. * ```
  12921. *
  12922. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  12923. *
  12924. * However, the more traditional CommonJS-style usage is still available, and documented below.
  12925. *
  12926. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  12927. * interface for interacting with an object that represents the result of an action that is
  12928. * performed asynchronously, and may or may not be finished at any given point in time.
  12929. *
  12930. * From the perspective of dealing with error handling, deferred and promise APIs are to
  12931. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  12932. *
  12933. * ```js
  12934. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  12935. * // are available in the current lexical scope (they could have been injected or passed in).
  12936. *
  12937. * function asyncGreet(name) {
  12938. * var deferred = $q.defer();
  12939. *
  12940. * setTimeout(function() {
  12941. * deferred.notify('About to greet ' + name + '.');
  12942. *
  12943. * if (okToGreet(name)) {
  12944. * deferred.resolve('Hello, ' + name + '!');
  12945. * } else {
  12946. * deferred.reject('Greeting ' + name + ' is not allowed.');
  12947. * }
  12948. * }, 1000);
  12949. *
  12950. * return deferred.promise;
  12951. * }
  12952. *
  12953. * var promise = asyncGreet('Robin Hood');
  12954. * promise.then(function(greeting) {
  12955. * alert('Success: ' + greeting);
  12956. * }, function(reason) {
  12957. * alert('Failed: ' + reason);
  12958. * }, function(update) {
  12959. * alert('Got notification: ' + update);
  12960. * });
  12961. * ```
  12962. *
  12963. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  12964. * comes in the way of guarantees that promise and deferred APIs make, see
  12965. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  12966. *
  12967. * Additionally the promise api allows for composition that is very hard to do with the
  12968. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  12969. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  12970. * section on serial or parallel joining of promises.
  12971. *
  12972. * # The Deferred API
  12973. *
  12974. * A new instance of deferred is constructed by calling `$q.defer()`.
  12975. *
  12976. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  12977. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  12978. * of the task.
  12979. *
  12980. * **Methods**
  12981. *
  12982. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  12983. * constructed via `$q.reject`, the promise will be rejected instead.
  12984. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  12985. * resolving it with a rejection constructed via `$q.reject`.
  12986. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  12987. * multiple times before the promise is either resolved or rejected.
  12988. *
  12989. * **Properties**
  12990. *
  12991. * - promise – `{Promise}` – promise object associated with this deferred.
  12992. *
  12993. *
  12994. * # The Promise API
  12995. *
  12996. * A new promise instance is created when a deferred instance is created and can be retrieved by
  12997. * calling `deferred.promise`.
  12998. *
  12999. * The purpose of the promise object is to allow for interested parties to get access to the result
  13000. * of the deferred task when it completes.
  13001. *
  13002. * **Methods**
  13003. *
  13004. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  13005. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  13006. * as soon as the result is available. The callbacks are called with a single argument: the result
  13007. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  13008. * provide a progress indication, before the promise is resolved or rejected.
  13009. *
  13010. * This method *returns a new promise* which is resolved or rejected via the return value of the
  13011. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  13012. * with the value which is resolved in that promise using
  13013. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  13014. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  13015. * resolved or rejected from the notifyCallback method.
  13016. *
  13017. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  13018. *
  13019. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  13020. * but to do so without modifying the final value. This is useful to release resources or do some
  13021. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  13022. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  13023. * more information.
  13024. *
  13025. * # Chaining promises
  13026. *
  13027. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  13028. * possible to create a chain of promises:
  13029. *
  13030. * ```js
  13031. * promiseB = promiseA.then(function(result) {
  13032. * return result + 1;
  13033. * });
  13034. *
  13035. * // promiseB will be resolved immediately after promiseA is resolved and its value
  13036. * // will be the result of promiseA incremented by 1
  13037. * ```
  13038. *
  13039. * It is possible to create chains of any length and since a promise can be resolved with another
  13040. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  13041. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  13042. * $http's response interceptors.
  13043. *
  13044. *
  13045. * # Differences between Kris Kowal's Q and $q
  13046. *
  13047. * There are two main differences:
  13048. *
  13049. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  13050. * mechanism in angular, which means faster propagation of resolution or rejection into your
  13051. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  13052. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  13053. * all the important functionality needed for common async tasks.
  13054. *
  13055. * # Testing
  13056. *
  13057. * ```js
  13058. * it('should simulate promise', inject(function($q, $rootScope) {
  13059. * var deferred = $q.defer();
  13060. * var promise = deferred.promise;
  13061. * var resolvedValue;
  13062. *
  13063. * promise.then(function(value) { resolvedValue = value; });
  13064. * expect(resolvedValue).toBeUndefined();
  13065. *
  13066. * // Simulate resolving of promise
  13067. * deferred.resolve(123);
  13068. * // Note that the 'then' function does not get called synchronously.
  13069. * // This is because we want the promise API to always be async, whether or not
  13070. * // it got called synchronously or asynchronously.
  13071. * expect(resolvedValue).toBeUndefined();
  13072. *
  13073. * // Propagate promise resolution to 'then' functions using $apply().
  13074. * $rootScope.$apply();
  13075. * expect(resolvedValue).toEqual(123);
  13076. * }));
  13077. * ```
  13078. *
  13079. * @param {function(function, function)} resolver Function which is responsible for resolving or
  13080. * rejecting the newly created promise. The first parameter is a function which resolves the
  13081. * promise, the second parameter is a function which rejects the promise.
  13082. *
  13083. * @returns {Promise} The newly created promise.
  13084. */
  13085. function $QProvider() {
  13086. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  13087. return qFactory(function(callback) {
  13088. $rootScope.$evalAsync(callback);
  13089. }, $exceptionHandler);
  13090. }];
  13091. }
  13092. function $$QProvider() {
  13093. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  13094. return qFactory(function(callback) {
  13095. $browser.defer(callback);
  13096. }, $exceptionHandler);
  13097. }];
  13098. }
  13099. /**
  13100. * Constructs a promise manager.
  13101. *
  13102. * @param {function(function)} nextTick Function for executing functions in the next turn.
  13103. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  13104. * debugging purposes.
  13105. * @returns {object} Promise manager.
  13106. */
  13107. function qFactory(nextTick, exceptionHandler) {
  13108. var $qMinErr = minErr('$q', TypeError);
  13109. function callOnce(self, resolveFn, rejectFn) {
  13110. var called = false;
  13111. function wrap(fn) {
  13112. return function(value) {
  13113. if (called) return;
  13114. called = true;
  13115. fn.call(self, value);
  13116. };
  13117. }
  13118. return [wrap(resolveFn), wrap(rejectFn)];
  13119. }
  13120. /**
  13121. * @ngdoc method
  13122. * @name ng.$q#defer
  13123. * @kind function
  13124. *
  13125. * @description
  13126. * Creates a `Deferred` object which represents a task which will finish in the future.
  13127. *
  13128. * @returns {Deferred} Returns a new instance of deferred.
  13129. */
  13130. var defer = function() {
  13131. return new Deferred();
  13132. };
  13133. function Promise() {
  13134. this.$$state = { status: 0 };
  13135. }
  13136. Promise.prototype = {
  13137. then: function(onFulfilled, onRejected, progressBack) {
  13138. var result = new Deferred();
  13139. this.$$state.pending = this.$$state.pending || [];
  13140. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  13141. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  13142. return result.promise;
  13143. },
  13144. "catch": function(callback) {
  13145. return this.then(null, callback);
  13146. },
  13147. "finally": function(callback, progressBack) {
  13148. return this.then(function(value) {
  13149. return handleCallback(value, true, callback);
  13150. }, function(error) {
  13151. return handleCallback(error, false, callback);
  13152. }, progressBack);
  13153. }
  13154. };
  13155. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  13156. function simpleBind(context, fn) {
  13157. return function(value) {
  13158. fn.call(context, value);
  13159. };
  13160. }
  13161. function processQueue(state) {
  13162. var fn, deferred, pending;
  13163. pending = state.pending;
  13164. state.processScheduled = false;
  13165. state.pending = undefined;
  13166. for (var i = 0, ii = pending.length; i < ii; ++i) {
  13167. deferred = pending[i][0];
  13168. fn = pending[i][state.status];
  13169. try {
  13170. if (isFunction(fn)) {
  13171. deferred.resolve(fn(state.value));
  13172. } else if (state.status === 1) {
  13173. deferred.resolve(state.value);
  13174. } else {
  13175. deferred.reject(state.value);
  13176. }
  13177. } catch (e) {
  13178. deferred.reject(e);
  13179. exceptionHandler(e);
  13180. }
  13181. }
  13182. }
  13183. function scheduleProcessQueue(state) {
  13184. if (state.processScheduled || !state.pending) return;
  13185. state.processScheduled = true;
  13186. nextTick(function() { processQueue(state); });
  13187. }
  13188. function Deferred() {
  13189. this.promise = new Promise();
  13190. //Necessary to support unbound execution :/
  13191. this.resolve = simpleBind(this, this.resolve);
  13192. this.reject = simpleBind(this, this.reject);
  13193. this.notify = simpleBind(this, this.notify);
  13194. }
  13195. Deferred.prototype = {
  13196. resolve: function(val) {
  13197. if (this.promise.$$state.status) return;
  13198. if (val === this.promise) {
  13199. this.$$reject($qMinErr(
  13200. 'qcycle',
  13201. "Expected promise to be resolved with value other than itself '{0}'",
  13202. val));
  13203. } else {
  13204. this.$$resolve(val);
  13205. }
  13206. },
  13207. $$resolve: function(val) {
  13208. var then, fns;
  13209. fns = callOnce(this, this.$$resolve, this.$$reject);
  13210. try {
  13211. if ((isObject(val) || isFunction(val))) then = val && val.then;
  13212. if (isFunction(then)) {
  13213. this.promise.$$state.status = -1;
  13214. then.call(val, fns[0], fns[1], this.notify);
  13215. } else {
  13216. this.promise.$$state.value = val;
  13217. this.promise.$$state.status = 1;
  13218. scheduleProcessQueue(this.promise.$$state);
  13219. }
  13220. } catch (e) {
  13221. fns[1](e);
  13222. exceptionHandler(e);
  13223. }
  13224. },
  13225. reject: function(reason) {
  13226. if (this.promise.$$state.status) return;
  13227. this.$$reject(reason);
  13228. },
  13229. $$reject: function(reason) {
  13230. this.promise.$$state.value = reason;
  13231. this.promise.$$state.status = 2;
  13232. scheduleProcessQueue(this.promise.$$state);
  13233. },
  13234. notify: function(progress) {
  13235. var callbacks = this.promise.$$state.pending;
  13236. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  13237. nextTick(function() {
  13238. var callback, result;
  13239. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  13240. result = callbacks[i][0];
  13241. callback = callbacks[i][3];
  13242. try {
  13243. result.notify(isFunction(callback) ? callback(progress) : progress);
  13244. } catch (e) {
  13245. exceptionHandler(e);
  13246. }
  13247. }
  13248. });
  13249. }
  13250. }
  13251. };
  13252. /**
  13253. * @ngdoc method
  13254. * @name $q#reject
  13255. * @kind function
  13256. *
  13257. * @description
  13258. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  13259. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  13260. * a promise chain, you don't need to worry about it.
  13261. *
  13262. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  13263. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  13264. * a promise error callback and you want to forward the error to the promise derived from the
  13265. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  13266. * `reject`.
  13267. *
  13268. * ```js
  13269. * promiseB = promiseA.then(function(result) {
  13270. * // success: do something and resolve promiseB
  13271. * // with the old or a new result
  13272. * return result;
  13273. * }, function(reason) {
  13274. * // error: handle the error if possible and
  13275. * // resolve promiseB with newPromiseOrValue,
  13276. * // otherwise forward the rejection to promiseB
  13277. * if (canHandle(reason)) {
  13278. * // handle the error and recover
  13279. * return newPromiseOrValue;
  13280. * }
  13281. * return $q.reject(reason);
  13282. * });
  13283. * ```
  13284. *
  13285. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  13286. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  13287. */
  13288. var reject = function(reason) {
  13289. var result = new Deferred();
  13290. result.reject(reason);
  13291. return result.promise;
  13292. };
  13293. var makePromise = function makePromise(value, resolved) {
  13294. var result = new Deferred();
  13295. if (resolved) {
  13296. result.resolve(value);
  13297. } else {
  13298. result.reject(value);
  13299. }
  13300. return result.promise;
  13301. };
  13302. var handleCallback = function handleCallback(value, isResolved, callback) {
  13303. var callbackOutput = null;
  13304. try {
  13305. if (isFunction(callback)) callbackOutput = callback();
  13306. } catch (e) {
  13307. return makePromise(e, false);
  13308. }
  13309. if (isPromiseLike(callbackOutput)) {
  13310. return callbackOutput.then(function() {
  13311. return makePromise(value, isResolved);
  13312. }, function(error) {
  13313. return makePromise(error, false);
  13314. });
  13315. } else {
  13316. return makePromise(value, isResolved);
  13317. }
  13318. };
  13319. /**
  13320. * @ngdoc method
  13321. * @name $q#when
  13322. * @kind function
  13323. *
  13324. * @description
  13325. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  13326. * This is useful when you are dealing with an object that might or might not be a promise, or if
  13327. * the promise comes from a source that can't be trusted.
  13328. *
  13329. * @param {*} value Value or a promise
  13330. * @returns {Promise} Returns a promise of the passed value or promise
  13331. */
  13332. var when = function(value, callback, errback, progressBack) {
  13333. var result = new Deferred();
  13334. result.resolve(value);
  13335. return result.promise.then(callback, errback, progressBack);
  13336. };
  13337. /**
  13338. * @ngdoc method
  13339. * @name $q#resolve
  13340. * @kind function
  13341. *
  13342. * @description
  13343. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  13344. *
  13345. * @param {*} value Value or a promise
  13346. * @returns {Promise} Returns a promise of the passed value or promise
  13347. */
  13348. var resolve = when;
  13349. /**
  13350. * @ngdoc method
  13351. * @name $q#all
  13352. * @kind function
  13353. *
  13354. * @description
  13355. * Combines multiple promises into a single promise that is resolved when all of the input
  13356. * promises are resolved.
  13357. *
  13358. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  13359. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  13360. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  13361. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  13362. * with the same rejection value.
  13363. */
  13364. function all(promises) {
  13365. var deferred = new Deferred(),
  13366. counter = 0,
  13367. results = isArray(promises) ? [] : {};
  13368. forEach(promises, function(promise, key) {
  13369. counter++;
  13370. when(promise).then(function(value) {
  13371. if (results.hasOwnProperty(key)) return;
  13372. results[key] = value;
  13373. if (!(--counter)) deferred.resolve(results);
  13374. }, function(reason) {
  13375. if (results.hasOwnProperty(key)) return;
  13376. deferred.reject(reason);
  13377. });
  13378. });
  13379. if (counter === 0) {
  13380. deferred.resolve(results);
  13381. }
  13382. return deferred.promise;
  13383. }
  13384. var $Q = function Q(resolver) {
  13385. if (!isFunction(resolver)) {
  13386. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  13387. }
  13388. if (!(this instanceof Q)) {
  13389. // More useful when $Q is the Promise itself.
  13390. return new Q(resolver);
  13391. }
  13392. var deferred = new Deferred();
  13393. function resolveFn(value) {
  13394. deferred.resolve(value);
  13395. }
  13396. function rejectFn(reason) {
  13397. deferred.reject(reason);
  13398. }
  13399. resolver(resolveFn, rejectFn);
  13400. return deferred.promise;
  13401. };
  13402. $Q.defer = defer;
  13403. $Q.reject = reject;
  13404. $Q.when = when;
  13405. $Q.resolve = resolve;
  13406. $Q.all = all;
  13407. return $Q;
  13408. }
  13409. function $$RAFProvider() { //rAF
  13410. this.$get = ['$window', '$timeout', function($window, $timeout) {
  13411. var requestAnimationFrame = $window.requestAnimationFrame ||
  13412. $window.webkitRequestAnimationFrame;
  13413. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  13414. $window.webkitCancelAnimationFrame ||
  13415. $window.webkitCancelRequestAnimationFrame;
  13416. var rafSupported = !!requestAnimationFrame;
  13417. var rafFn = rafSupported
  13418. ? function(fn) {
  13419. var id = requestAnimationFrame(fn);
  13420. return function() {
  13421. cancelAnimationFrame(id);
  13422. };
  13423. }
  13424. : function(fn) {
  13425. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  13426. return function() {
  13427. $timeout.cancel(timer);
  13428. };
  13429. };
  13430. queueFn.supported = rafSupported;
  13431. var cancelLastRAF;
  13432. var taskCount = 0;
  13433. var taskQueue = [];
  13434. return queueFn;
  13435. function flush() {
  13436. for (var i = 0; i < taskQueue.length; i++) {
  13437. var task = taskQueue[i];
  13438. if (task) {
  13439. taskQueue[i] = null;
  13440. task();
  13441. }
  13442. }
  13443. taskCount = taskQueue.length = 0;
  13444. }
  13445. function queueFn(asyncFn) {
  13446. var index = taskQueue.length;
  13447. taskCount++;
  13448. taskQueue.push(asyncFn);
  13449. if (index === 0) {
  13450. cancelLastRAF = rafFn(flush);
  13451. }
  13452. return function cancelQueueFn() {
  13453. if (index >= 0) {
  13454. taskQueue[index] = null;
  13455. index = null;
  13456. if (--taskCount === 0 && cancelLastRAF) {
  13457. cancelLastRAF();
  13458. cancelLastRAF = null;
  13459. taskQueue.length = 0;
  13460. }
  13461. }
  13462. };
  13463. }
  13464. }];
  13465. }
  13466. /**
  13467. * DESIGN NOTES
  13468. *
  13469. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  13470. *
  13471. * The typical use of scope is to watch the expressions, which most of the time return the same
  13472. * value as last time so we optimize the operation.
  13473. *
  13474. * Closures construction is expensive in terms of speed as well as memory:
  13475. * - No closures, instead use prototypical inheritance for API
  13476. * - Internal state needs to be stored on scope directly, which means that private state is
  13477. * exposed as $$____ properties
  13478. *
  13479. * Loop operations are optimized by using while(count--) { ... }
  13480. * - this means that in order to keep the same order of execution as addition we have to add
  13481. * items to the array at the beginning (unshift) instead of at the end (push)
  13482. *
  13483. * Child scopes are created and removed often
  13484. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  13485. *
  13486. * There are few watches then a lot of observers. This is why you don't want the observer to be
  13487. * implemented in the same way as watch. Watch requires return of initialization function which
  13488. * are expensive to construct.
  13489. */
  13490. /**
  13491. * @ngdoc provider
  13492. * @name $rootScopeProvider
  13493. * @description
  13494. *
  13495. * Provider for the $rootScope service.
  13496. */
  13497. /**
  13498. * @ngdoc method
  13499. * @name $rootScopeProvider#digestTtl
  13500. * @description
  13501. *
  13502. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  13503. * assuming that the model is unstable.
  13504. *
  13505. * The current default is 10 iterations.
  13506. *
  13507. * In complex applications it's possible that the dependencies between `$watch`s will result in
  13508. * several digest iterations. However if an application needs more than the default 10 digest
  13509. * iterations for its model to stabilize then you should investigate what is causing the model to
  13510. * continuously change during the digest.
  13511. *
  13512. * Increasing the TTL could have performance implications, so you should not change it without
  13513. * proper justification.
  13514. *
  13515. * @param {number} limit The number of digest iterations.
  13516. */
  13517. /**
  13518. * @ngdoc service
  13519. * @name $rootScope
  13520. * @description
  13521. *
  13522. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  13523. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  13524. * between the model and the view, via a mechanism for watching the model for changes.
  13525. * They also provide an event emission/broadcast and subscription facility. See the
  13526. * {@link guide/scope developer guide on scopes}.
  13527. */
  13528. function $RootScopeProvider() {
  13529. var TTL = 10;
  13530. var $rootScopeMinErr = minErr('$rootScope');
  13531. var lastDirtyWatch = null;
  13532. var applyAsyncId = null;
  13533. this.digestTtl = function(value) {
  13534. if (arguments.length) {
  13535. TTL = value;
  13536. }
  13537. return TTL;
  13538. };
  13539. function createChildScopeClass(parent) {
  13540. function ChildScope() {
  13541. this.$$watchers = this.$$nextSibling =
  13542. this.$$childHead = this.$$childTail = null;
  13543. this.$$listeners = {};
  13544. this.$$listenerCount = {};
  13545. this.$$watchersCount = 0;
  13546. this.$id = nextUid();
  13547. this.$$ChildScope = null;
  13548. }
  13549. ChildScope.prototype = parent;
  13550. return ChildScope;
  13551. }
  13552. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  13553. function($injector, $exceptionHandler, $parse, $browser) {
  13554. function destroyChildScope($event) {
  13555. $event.currentScope.$$destroyed = true;
  13556. }
  13557. /**
  13558. * @ngdoc type
  13559. * @name $rootScope.Scope
  13560. *
  13561. * @description
  13562. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  13563. * {@link auto.$injector $injector}. Child scopes are created using the
  13564. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  13565. * compiled HTML template is executed.)
  13566. *
  13567. * Here is a simple scope snippet to show how you can interact with the scope.
  13568. * ```html
  13569. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  13570. * ```
  13571. *
  13572. * # Inheritance
  13573. * A scope can inherit from a parent scope, as in this example:
  13574. * ```js
  13575. var parent = $rootScope;
  13576. var child = parent.$new();
  13577. parent.salutation = "Hello";
  13578. expect(child.salutation).toEqual('Hello');
  13579. child.salutation = "Welcome";
  13580. expect(child.salutation).toEqual('Welcome');
  13581. expect(parent.salutation).toEqual('Hello');
  13582. * ```
  13583. *
  13584. * When interacting with `Scope` in tests, additional helper methods are available on the
  13585. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  13586. * details.
  13587. *
  13588. *
  13589. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  13590. * provided for the current scope. Defaults to {@link ng}.
  13591. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  13592. * append/override services provided by `providers`. This is handy
  13593. * when unit-testing and having the need to override a default
  13594. * service.
  13595. * @returns {Object} Newly created scope.
  13596. *
  13597. */
  13598. function Scope() {
  13599. this.$id = nextUid();
  13600. this.$$phase = this.$parent = this.$$watchers =
  13601. this.$$nextSibling = this.$$prevSibling =
  13602. this.$$childHead = this.$$childTail = null;
  13603. this.$root = this;
  13604. this.$$destroyed = false;
  13605. this.$$listeners = {};
  13606. this.$$listenerCount = {};
  13607. this.$$watchersCount = 0;
  13608. this.$$isolateBindings = null;
  13609. }
  13610. /**
  13611. * @ngdoc property
  13612. * @name $rootScope.Scope#$id
  13613. *
  13614. * @description
  13615. * Unique scope ID (monotonically increasing) useful for debugging.
  13616. */
  13617. /**
  13618. * @ngdoc property
  13619. * @name $rootScope.Scope#$parent
  13620. *
  13621. * @description
  13622. * Reference to the parent scope.
  13623. */
  13624. /**
  13625. * @ngdoc property
  13626. * @name $rootScope.Scope#$root
  13627. *
  13628. * @description
  13629. * Reference to the root scope.
  13630. */
  13631. Scope.prototype = {
  13632. constructor: Scope,
  13633. /**
  13634. * @ngdoc method
  13635. * @name $rootScope.Scope#$new
  13636. * @kind function
  13637. *
  13638. * @description
  13639. * Creates a new child {@link ng.$rootScope.Scope scope}.
  13640. *
  13641. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  13642. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  13643. *
  13644. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  13645. * desired for the scope and its child scopes to be permanently detached from the parent and
  13646. * thus stop participating in model change detection and listener notification by invoking.
  13647. *
  13648. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  13649. * parent scope. The scope is isolated, as it can not see parent scope properties.
  13650. * When creating widgets, it is useful for the widget to not accidentally read parent
  13651. * state.
  13652. *
  13653. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  13654. * of the newly created scope. Defaults to `this` scope if not provided.
  13655. * This is used when creating a transclude scope to correctly place it
  13656. * in the scope hierarchy while maintaining the correct prototypical
  13657. * inheritance.
  13658. *
  13659. * @returns {Object} The newly created child scope.
  13660. *
  13661. */
  13662. $new: function(isolate, parent) {
  13663. var child;
  13664. parent = parent || this;
  13665. if (isolate) {
  13666. child = new Scope();
  13667. child.$root = this.$root;
  13668. } else {
  13669. // Only create a child scope class if somebody asks for one,
  13670. // but cache it to allow the VM to optimize lookups.
  13671. if (!this.$$ChildScope) {
  13672. this.$$ChildScope = createChildScopeClass(this);
  13673. }
  13674. child = new this.$$ChildScope();
  13675. }
  13676. child.$parent = parent;
  13677. child.$$prevSibling = parent.$$childTail;
  13678. if (parent.$$childHead) {
  13679. parent.$$childTail.$$nextSibling = child;
  13680. parent.$$childTail = child;
  13681. } else {
  13682. parent.$$childHead = parent.$$childTail = child;
  13683. }
  13684. // When the new scope is not isolated or we inherit from `this`, and
  13685. // the parent scope is destroyed, the property `$$destroyed` is inherited
  13686. // prototypically. In all other cases, this property needs to be set
  13687. // when the parent scope is destroyed.
  13688. // The listener needs to be added after the parent is set
  13689. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  13690. return child;
  13691. },
  13692. /**
  13693. * @ngdoc method
  13694. * @name $rootScope.Scope#$watch
  13695. * @kind function
  13696. *
  13697. * @description
  13698. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  13699. *
  13700. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  13701. * $digest()} and should return the value that will be watched. (Since
  13702. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  13703. * `watchExpression` can execute multiple times per
  13704. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  13705. * - The `listener` is called only when the value from the current `watchExpression` and the
  13706. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  13707. * see below). Inequality is determined according to reference inequality,
  13708. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  13709. * via the `!==` Javascript operator, unless `objectEquality == true`
  13710. * (see next point)
  13711. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  13712. * according to the {@link angular.equals} function. To save the value of the object for
  13713. * later comparison, the {@link angular.copy} function is used. This therefore means that
  13714. * watching complex objects will have adverse memory and performance implications.
  13715. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  13716. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  13717. * iteration limit is 10 to prevent an infinite loop deadlock.
  13718. *
  13719. *
  13720. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  13721. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  13722. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  13723. * change is detected, be prepared for multiple calls to your listener.)
  13724. *
  13725. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  13726. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  13727. * watcher. In rare cases, this is undesirable because the listener is called when the result
  13728. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  13729. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  13730. * listener was called due to initialization.
  13731. *
  13732. *
  13733. *
  13734. * # Example
  13735. * ```js
  13736. // let's assume that scope was dependency injected as the $rootScope
  13737. var scope = $rootScope;
  13738. scope.name = 'misko';
  13739. scope.counter = 0;
  13740. expect(scope.counter).toEqual(0);
  13741. scope.$watch('name', function(newValue, oldValue) {
  13742. scope.counter = scope.counter + 1;
  13743. });
  13744. expect(scope.counter).toEqual(0);
  13745. scope.$digest();
  13746. // the listener is always called during the first $digest loop after it was registered
  13747. expect(scope.counter).toEqual(1);
  13748. scope.$digest();
  13749. // but now it will not be called unless the value changes
  13750. expect(scope.counter).toEqual(1);
  13751. scope.name = 'adam';
  13752. scope.$digest();
  13753. expect(scope.counter).toEqual(2);
  13754. // Using a function as a watchExpression
  13755. var food;
  13756. scope.foodCounter = 0;
  13757. expect(scope.foodCounter).toEqual(0);
  13758. scope.$watch(
  13759. // This function returns the value being watched. It is called for each turn of the $digest loop
  13760. function() { return food; },
  13761. // This is the change listener, called when the value returned from the above function changes
  13762. function(newValue, oldValue) {
  13763. if ( newValue !== oldValue ) {
  13764. // Only increment the counter if the value changed
  13765. scope.foodCounter = scope.foodCounter + 1;
  13766. }
  13767. }
  13768. );
  13769. // No digest has been run so the counter will be zero
  13770. expect(scope.foodCounter).toEqual(0);
  13771. // Run the digest but since food has not changed count will still be zero
  13772. scope.$digest();
  13773. expect(scope.foodCounter).toEqual(0);
  13774. // Update food and run digest. Now the counter will increment
  13775. food = 'cheeseburger';
  13776. scope.$digest();
  13777. expect(scope.foodCounter).toEqual(1);
  13778. * ```
  13779. *
  13780. *
  13781. *
  13782. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  13783. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  13784. * a call to the `listener`.
  13785. *
  13786. * - `string`: Evaluated as {@link guide/expression expression}
  13787. * - `function(scope)`: called with current `scope` as a parameter.
  13788. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  13789. * of `watchExpression` changes.
  13790. *
  13791. * - `newVal` contains the current value of the `watchExpression`
  13792. * - `oldVal` contains the previous value of the `watchExpression`
  13793. * - `scope` refers to the current scope
  13794. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  13795. * comparing for reference equality.
  13796. * @returns {function()} Returns a deregistration function for this listener.
  13797. */
  13798. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  13799. var get = $parse(watchExp);
  13800. if (get.$$watchDelegate) {
  13801. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  13802. }
  13803. var scope = this,
  13804. array = scope.$$watchers,
  13805. watcher = {
  13806. fn: listener,
  13807. last: initWatchVal,
  13808. get: get,
  13809. exp: prettyPrintExpression || watchExp,
  13810. eq: !!objectEquality
  13811. };
  13812. lastDirtyWatch = null;
  13813. if (!isFunction(listener)) {
  13814. watcher.fn = noop;
  13815. }
  13816. if (!array) {
  13817. array = scope.$$watchers = [];
  13818. }
  13819. // we use unshift since we use a while loop in $digest for speed.
  13820. // the while loop reads in reverse order.
  13821. array.unshift(watcher);
  13822. incrementWatchersCount(this, 1);
  13823. return function deregisterWatch() {
  13824. if (arrayRemove(array, watcher) >= 0) {
  13825. incrementWatchersCount(scope, -1);
  13826. }
  13827. lastDirtyWatch = null;
  13828. };
  13829. },
  13830. /**
  13831. * @ngdoc method
  13832. * @name $rootScope.Scope#$watchGroup
  13833. * @kind function
  13834. *
  13835. * @description
  13836. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  13837. * If any one expression in the collection changes the `listener` is executed.
  13838. *
  13839. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  13840. * call to $digest() to see if any items changes.
  13841. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  13842. *
  13843. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  13844. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  13845. *
  13846. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  13847. * expression in `watchExpressions` changes
  13848. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  13849. * those of `watchExpression`
  13850. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  13851. * those of `watchExpression`
  13852. * The `scope` refers to the current scope.
  13853. * @returns {function()} Returns a de-registration function for all listeners.
  13854. */
  13855. $watchGroup: function(watchExpressions, listener) {
  13856. var oldValues = new Array(watchExpressions.length);
  13857. var newValues = new Array(watchExpressions.length);
  13858. var deregisterFns = [];
  13859. var self = this;
  13860. var changeReactionScheduled = false;
  13861. var firstRun = true;
  13862. if (!watchExpressions.length) {
  13863. // No expressions means we call the listener ASAP
  13864. var shouldCall = true;
  13865. self.$evalAsync(function() {
  13866. if (shouldCall) listener(newValues, newValues, self);
  13867. });
  13868. return function deregisterWatchGroup() {
  13869. shouldCall = false;
  13870. };
  13871. }
  13872. if (watchExpressions.length === 1) {
  13873. // Special case size of one
  13874. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  13875. newValues[0] = value;
  13876. oldValues[0] = oldValue;
  13877. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  13878. });
  13879. }
  13880. forEach(watchExpressions, function(expr, i) {
  13881. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  13882. newValues[i] = value;
  13883. oldValues[i] = oldValue;
  13884. if (!changeReactionScheduled) {
  13885. changeReactionScheduled = true;
  13886. self.$evalAsync(watchGroupAction);
  13887. }
  13888. });
  13889. deregisterFns.push(unwatchFn);
  13890. });
  13891. function watchGroupAction() {
  13892. changeReactionScheduled = false;
  13893. if (firstRun) {
  13894. firstRun = false;
  13895. listener(newValues, newValues, self);
  13896. } else {
  13897. listener(newValues, oldValues, self);
  13898. }
  13899. }
  13900. return function deregisterWatchGroup() {
  13901. while (deregisterFns.length) {
  13902. deregisterFns.shift()();
  13903. }
  13904. };
  13905. },
  13906. /**
  13907. * @ngdoc method
  13908. * @name $rootScope.Scope#$watchCollection
  13909. * @kind function
  13910. *
  13911. * @description
  13912. * Shallow watches the properties of an object and fires whenever any of the properties change
  13913. * (for arrays, this implies watching the array items; for object maps, this implies watching
  13914. * the properties). If a change is detected, the `listener` callback is fired.
  13915. *
  13916. * - The `obj` collection is observed via standard $watch operation and is examined on every
  13917. * call to $digest() to see if any items have been added, removed, or moved.
  13918. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  13919. * adding, removing, and moving items belonging to an object or array.
  13920. *
  13921. *
  13922. * # Example
  13923. * ```js
  13924. $scope.names = ['igor', 'matias', 'misko', 'james'];
  13925. $scope.dataCount = 4;
  13926. $scope.$watchCollection('names', function(newNames, oldNames) {
  13927. $scope.dataCount = newNames.length;
  13928. });
  13929. expect($scope.dataCount).toEqual(4);
  13930. $scope.$digest();
  13931. //still at 4 ... no changes
  13932. expect($scope.dataCount).toEqual(4);
  13933. $scope.names.pop();
  13934. $scope.$digest();
  13935. //now there's been a change
  13936. expect($scope.dataCount).toEqual(3);
  13937. * ```
  13938. *
  13939. *
  13940. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  13941. * expression value should evaluate to an object or an array which is observed on each
  13942. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  13943. * collection will trigger a call to the `listener`.
  13944. *
  13945. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  13946. * when a change is detected.
  13947. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  13948. * - The `oldCollection` object is a copy of the former collection data.
  13949. * Due to performance considerations, the`oldCollection` value is computed only if the
  13950. * `listener` function declares two or more arguments.
  13951. * - The `scope` argument refers to the current scope.
  13952. *
  13953. * @returns {function()} Returns a de-registration function for this listener. When the
  13954. * de-registration function is executed, the internal watch operation is terminated.
  13955. */
  13956. $watchCollection: function(obj, listener) {
  13957. $watchCollectionInterceptor.$stateful = true;
  13958. var self = this;
  13959. // the current value, updated on each dirty-check run
  13960. var newValue;
  13961. // a shallow copy of the newValue from the last dirty-check run,
  13962. // updated to match newValue during dirty-check run
  13963. var oldValue;
  13964. // a shallow copy of the newValue from when the last change happened
  13965. var veryOldValue;
  13966. // only track veryOldValue if the listener is asking for it
  13967. var trackVeryOldValue = (listener.length > 1);
  13968. var changeDetected = 0;
  13969. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  13970. var internalArray = [];
  13971. var internalObject = {};
  13972. var initRun = true;
  13973. var oldLength = 0;
  13974. function $watchCollectionInterceptor(_value) {
  13975. newValue = _value;
  13976. var newLength, key, bothNaN, newItem, oldItem;
  13977. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  13978. if (isUndefined(newValue)) return;
  13979. if (!isObject(newValue)) { // if primitive
  13980. if (oldValue !== newValue) {
  13981. oldValue = newValue;
  13982. changeDetected++;
  13983. }
  13984. } else if (isArrayLike(newValue)) {
  13985. if (oldValue !== internalArray) {
  13986. // we are transitioning from something which was not an array into array.
  13987. oldValue = internalArray;
  13988. oldLength = oldValue.length = 0;
  13989. changeDetected++;
  13990. }
  13991. newLength = newValue.length;
  13992. if (oldLength !== newLength) {
  13993. // if lengths do not match we need to trigger change notification
  13994. changeDetected++;
  13995. oldValue.length = oldLength = newLength;
  13996. }
  13997. // copy the items to oldValue and look for changes.
  13998. for (var i = 0; i < newLength; i++) {
  13999. oldItem = oldValue[i];
  14000. newItem = newValue[i];
  14001. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14002. if (!bothNaN && (oldItem !== newItem)) {
  14003. changeDetected++;
  14004. oldValue[i] = newItem;
  14005. }
  14006. }
  14007. } else {
  14008. if (oldValue !== internalObject) {
  14009. // we are transitioning from something which was not an object into object.
  14010. oldValue = internalObject = {};
  14011. oldLength = 0;
  14012. changeDetected++;
  14013. }
  14014. // copy the items to oldValue and look for changes.
  14015. newLength = 0;
  14016. for (key in newValue) {
  14017. if (newValue.hasOwnProperty(key)) {
  14018. newLength++;
  14019. newItem = newValue[key];
  14020. oldItem = oldValue[key];
  14021. if (key in oldValue) {
  14022. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14023. if (!bothNaN && (oldItem !== newItem)) {
  14024. changeDetected++;
  14025. oldValue[key] = newItem;
  14026. }
  14027. } else {
  14028. oldLength++;
  14029. oldValue[key] = newItem;
  14030. changeDetected++;
  14031. }
  14032. }
  14033. }
  14034. if (oldLength > newLength) {
  14035. // we used to have more keys, need to find them and destroy them.
  14036. changeDetected++;
  14037. for (key in oldValue) {
  14038. if (!newValue.hasOwnProperty(key)) {
  14039. oldLength--;
  14040. delete oldValue[key];
  14041. }
  14042. }
  14043. }
  14044. }
  14045. return changeDetected;
  14046. }
  14047. function $watchCollectionAction() {
  14048. if (initRun) {
  14049. initRun = false;
  14050. listener(newValue, newValue, self);
  14051. } else {
  14052. listener(newValue, veryOldValue, self);
  14053. }
  14054. // make a copy for the next time a collection is changed
  14055. if (trackVeryOldValue) {
  14056. if (!isObject(newValue)) {
  14057. //primitive
  14058. veryOldValue = newValue;
  14059. } else if (isArrayLike(newValue)) {
  14060. veryOldValue = new Array(newValue.length);
  14061. for (var i = 0; i < newValue.length; i++) {
  14062. veryOldValue[i] = newValue[i];
  14063. }
  14064. } else { // if object
  14065. veryOldValue = {};
  14066. for (var key in newValue) {
  14067. if (hasOwnProperty.call(newValue, key)) {
  14068. veryOldValue[key] = newValue[key];
  14069. }
  14070. }
  14071. }
  14072. }
  14073. }
  14074. return this.$watch(changeDetector, $watchCollectionAction);
  14075. },
  14076. /**
  14077. * @ngdoc method
  14078. * @name $rootScope.Scope#$digest
  14079. * @kind function
  14080. *
  14081. * @description
  14082. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  14083. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  14084. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  14085. * until no more listeners are firing. This means that it is possible to get into an infinite
  14086. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  14087. * iterations exceeds 10.
  14088. *
  14089. * Usually, you don't call `$digest()` directly in
  14090. * {@link ng.directive:ngController controllers} or in
  14091. * {@link ng.$compileProvider#directive directives}.
  14092. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  14093. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  14094. *
  14095. * If you want to be notified whenever `$digest()` is called,
  14096. * you can register a `watchExpression` function with
  14097. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  14098. *
  14099. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  14100. *
  14101. * # Example
  14102. * ```js
  14103. var scope = ...;
  14104. scope.name = 'misko';
  14105. scope.counter = 0;
  14106. expect(scope.counter).toEqual(0);
  14107. scope.$watch('name', function(newValue, oldValue) {
  14108. scope.counter = scope.counter + 1;
  14109. });
  14110. expect(scope.counter).toEqual(0);
  14111. scope.$digest();
  14112. // the listener is always called during the first $digest loop after it was registered
  14113. expect(scope.counter).toEqual(1);
  14114. scope.$digest();
  14115. // but now it will not be called unless the value changes
  14116. expect(scope.counter).toEqual(1);
  14117. scope.name = 'adam';
  14118. scope.$digest();
  14119. expect(scope.counter).toEqual(2);
  14120. * ```
  14121. *
  14122. */
  14123. $digest: function() {
  14124. var watch, value, last,
  14125. watchers,
  14126. length,
  14127. dirty, ttl = TTL,
  14128. next, current, target = this,
  14129. watchLog = [],
  14130. logIdx, logMsg, asyncTask;
  14131. beginPhase('$digest');
  14132. // Check for changes to browser url that happened in sync before the call to $digest
  14133. $browser.$$checkUrlChange();
  14134. if (this === $rootScope && applyAsyncId !== null) {
  14135. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  14136. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  14137. $browser.defer.cancel(applyAsyncId);
  14138. flushApplyAsync();
  14139. }
  14140. lastDirtyWatch = null;
  14141. do { // "while dirty" loop
  14142. dirty = false;
  14143. current = target;
  14144. while (asyncQueue.length) {
  14145. try {
  14146. asyncTask = asyncQueue.shift();
  14147. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  14148. } catch (e) {
  14149. $exceptionHandler(e);
  14150. }
  14151. lastDirtyWatch = null;
  14152. }
  14153. traverseScopesLoop:
  14154. do { // "traverse the scopes" loop
  14155. if ((watchers = current.$$watchers)) {
  14156. // process our watches
  14157. length = watchers.length;
  14158. while (length--) {
  14159. try {
  14160. watch = watchers[length];
  14161. // Most common watches are on primitives, in which case we can short
  14162. // circuit it with === operator, only when === fails do we use .equals
  14163. if (watch) {
  14164. if ((value = watch.get(current)) !== (last = watch.last) &&
  14165. !(watch.eq
  14166. ? equals(value, last)
  14167. : (typeof value === 'number' && typeof last === 'number'
  14168. && isNaN(value) && isNaN(last)))) {
  14169. dirty = true;
  14170. lastDirtyWatch = watch;
  14171. watch.last = watch.eq ? copy(value, null) : value;
  14172. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  14173. if (ttl < 5) {
  14174. logIdx = 4 - ttl;
  14175. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  14176. watchLog[logIdx].push({
  14177. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  14178. newVal: value,
  14179. oldVal: last
  14180. });
  14181. }
  14182. } else if (watch === lastDirtyWatch) {
  14183. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  14184. // have already been tested.
  14185. dirty = false;
  14186. break traverseScopesLoop;
  14187. }
  14188. }
  14189. } catch (e) {
  14190. $exceptionHandler(e);
  14191. }
  14192. }
  14193. }
  14194. // Insanity Warning: scope depth-first traversal
  14195. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14196. // this piece should be kept in sync with the traversal in $broadcast
  14197. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  14198. (current !== target && current.$$nextSibling)))) {
  14199. while (current !== target && !(next = current.$$nextSibling)) {
  14200. current = current.$parent;
  14201. }
  14202. }
  14203. } while ((current = next));
  14204. // `break traverseScopesLoop;` takes us to here
  14205. if ((dirty || asyncQueue.length) && !(ttl--)) {
  14206. clearPhase();
  14207. throw $rootScopeMinErr('infdig',
  14208. '{0} $digest() iterations reached. Aborting!\n' +
  14209. 'Watchers fired in the last 5 iterations: {1}',
  14210. TTL, watchLog);
  14211. }
  14212. } while (dirty || asyncQueue.length);
  14213. clearPhase();
  14214. while (postDigestQueue.length) {
  14215. try {
  14216. postDigestQueue.shift()();
  14217. } catch (e) {
  14218. $exceptionHandler(e);
  14219. }
  14220. }
  14221. },
  14222. /**
  14223. * @ngdoc event
  14224. * @name $rootScope.Scope#$destroy
  14225. * @eventType broadcast on scope being destroyed
  14226. *
  14227. * @description
  14228. * Broadcasted when a scope and its children are being destroyed.
  14229. *
  14230. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14231. * clean up DOM bindings before an element is removed from the DOM.
  14232. */
  14233. /**
  14234. * @ngdoc method
  14235. * @name $rootScope.Scope#$destroy
  14236. * @kind function
  14237. *
  14238. * @description
  14239. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  14240. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  14241. * propagate to the current scope and its children. Removal also implies that the current
  14242. * scope is eligible for garbage collection.
  14243. *
  14244. * The `$destroy()` is usually used by directives such as
  14245. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  14246. * unrolling of the loop.
  14247. *
  14248. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  14249. * Application code can register a `$destroy` event handler that will give it a chance to
  14250. * perform any necessary cleanup.
  14251. *
  14252. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14253. * clean up DOM bindings before an element is removed from the DOM.
  14254. */
  14255. $destroy: function() {
  14256. // We can't destroy a scope that has been already destroyed.
  14257. if (this.$$destroyed) return;
  14258. var parent = this.$parent;
  14259. this.$broadcast('$destroy');
  14260. this.$$destroyed = true;
  14261. if (this === $rootScope) {
  14262. //Remove handlers attached to window when $rootScope is removed
  14263. $browser.$$applicationDestroyed();
  14264. }
  14265. incrementWatchersCount(this, -this.$$watchersCount);
  14266. for (var eventName in this.$$listenerCount) {
  14267. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  14268. }
  14269. // sever all the references to parent scopes (after this cleanup, the current scope should
  14270. // not be retained by any of our references and should be eligible for garbage collection)
  14271. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  14272. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  14273. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  14274. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  14275. // Disable listeners, watchers and apply/digest methods
  14276. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  14277. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  14278. this.$$listeners = {};
  14279. // All of the code below is bogus code that works around V8's memory leak via optimized code
  14280. // and inline caches.
  14281. //
  14282. // see:
  14283. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  14284. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  14285. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  14286. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  14287. this.$$childTail = this.$root = this.$$watchers = null;
  14288. },
  14289. /**
  14290. * @ngdoc method
  14291. * @name $rootScope.Scope#$eval
  14292. * @kind function
  14293. *
  14294. * @description
  14295. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  14296. * the expression are propagated (uncaught). This is useful when evaluating Angular
  14297. * expressions.
  14298. *
  14299. * # Example
  14300. * ```js
  14301. var scope = ng.$rootScope.Scope();
  14302. scope.a = 1;
  14303. scope.b = 2;
  14304. expect(scope.$eval('a+b')).toEqual(3);
  14305. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  14306. * ```
  14307. *
  14308. * @param {(string|function())=} expression An angular expression to be executed.
  14309. *
  14310. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14311. * - `function(scope)`: execute the function with the current `scope` parameter.
  14312. *
  14313. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14314. * @returns {*} The result of evaluating the expression.
  14315. */
  14316. $eval: function(expr, locals) {
  14317. return $parse(expr)(this, locals);
  14318. },
  14319. /**
  14320. * @ngdoc method
  14321. * @name $rootScope.Scope#$evalAsync
  14322. * @kind function
  14323. *
  14324. * @description
  14325. * Executes the expression on the current scope at a later point in time.
  14326. *
  14327. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  14328. * that:
  14329. *
  14330. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  14331. * rendering).
  14332. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  14333. * `expression` execution.
  14334. *
  14335. * Any exceptions from the execution of the expression are forwarded to the
  14336. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14337. *
  14338. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  14339. * will be scheduled. However, it is encouraged to always call code that changes the model
  14340. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  14341. *
  14342. * @param {(string|function())=} expression An angular expression to be executed.
  14343. *
  14344. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14345. * - `function(scope)`: execute the function with the current `scope` parameter.
  14346. *
  14347. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14348. */
  14349. $evalAsync: function(expr, locals) {
  14350. // if we are outside of an $digest loop and this is the first time we are scheduling async
  14351. // task also schedule async auto-flush
  14352. if (!$rootScope.$$phase && !asyncQueue.length) {
  14353. $browser.defer(function() {
  14354. if (asyncQueue.length) {
  14355. $rootScope.$digest();
  14356. }
  14357. });
  14358. }
  14359. asyncQueue.push({scope: this, expression: expr, locals: locals});
  14360. },
  14361. $$postDigest: function(fn) {
  14362. postDigestQueue.push(fn);
  14363. },
  14364. /**
  14365. * @ngdoc method
  14366. * @name $rootScope.Scope#$apply
  14367. * @kind function
  14368. *
  14369. * @description
  14370. * `$apply()` is used to execute an expression in angular from outside of the angular
  14371. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  14372. * Because we are calling into the angular framework we need to perform proper scope life
  14373. * cycle of {@link ng.$exceptionHandler exception handling},
  14374. * {@link ng.$rootScope.Scope#$digest executing watches}.
  14375. *
  14376. * ## Life cycle
  14377. *
  14378. * # Pseudo-Code of `$apply()`
  14379. * ```js
  14380. function $apply(expr) {
  14381. try {
  14382. return $eval(expr);
  14383. } catch (e) {
  14384. $exceptionHandler(e);
  14385. } finally {
  14386. $root.$digest();
  14387. }
  14388. }
  14389. * ```
  14390. *
  14391. *
  14392. * Scope's `$apply()` method transitions through the following stages:
  14393. *
  14394. * 1. The {@link guide/expression expression} is executed using the
  14395. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  14396. * 2. Any exceptions from the execution of the expression are forwarded to the
  14397. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14398. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  14399. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  14400. *
  14401. *
  14402. * @param {(string|function())=} exp An angular expression to be executed.
  14403. *
  14404. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14405. * - `function(scope)`: execute the function with current `scope` parameter.
  14406. *
  14407. * @returns {*} The result of evaluating the expression.
  14408. */
  14409. $apply: function(expr) {
  14410. try {
  14411. beginPhase('$apply');
  14412. return this.$eval(expr);
  14413. } catch (e) {
  14414. $exceptionHandler(e);
  14415. } finally {
  14416. clearPhase();
  14417. try {
  14418. $rootScope.$digest();
  14419. } catch (e) {
  14420. $exceptionHandler(e);
  14421. throw e;
  14422. }
  14423. }
  14424. },
  14425. /**
  14426. * @ngdoc method
  14427. * @name $rootScope.Scope#$applyAsync
  14428. * @kind function
  14429. *
  14430. * @description
  14431. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  14432. * varies across browsers, but is typically around ~10 milliseconds.
  14433. *
  14434. * This can be used to queue up multiple expressions which need to be evaluated in the same
  14435. * digest.
  14436. *
  14437. * @param {(string|function())=} exp An angular expression to be executed.
  14438. *
  14439. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14440. * - `function(scope)`: execute the function with current `scope` parameter.
  14441. */
  14442. $applyAsync: function(expr) {
  14443. var scope = this;
  14444. expr && applyAsyncQueue.push($applyAsyncExpression);
  14445. scheduleApplyAsync();
  14446. function $applyAsyncExpression() {
  14447. scope.$eval(expr);
  14448. }
  14449. },
  14450. /**
  14451. * @ngdoc method
  14452. * @name $rootScope.Scope#$on
  14453. * @kind function
  14454. *
  14455. * @description
  14456. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  14457. * discussion of event life cycle.
  14458. *
  14459. * The event listener function format is: `function(event, args...)`. The `event` object
  14460. * passed into the listener has the following attributes:
  14461. *
  14462. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  14463. * `$broadcast`-ed.
  14464. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  14465. * event propagates through the scope hierarchy, this property is set to null.
  14466. * - `name` - `{string}`: name of the event.
  14467. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  14468. * further event propagation (available only for events that were `$emit`-ed).
  14469. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  14470. * to true.
  14471. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  14472. *
  14473. * @param {string} name Event name to listen on.
  14474. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  14475. * @returns {function()} Returns a deregistration function for this listener.
  14476. */
  14477. $on: function(name, listener) {
  14478. var namedListeners = this.$$listeners[name];
  14479. if (!namedListeners) {
  14480. this.$$listeners[name] = namedListeners = [];
  14481. }
  14482. namedListeners.push(listener);
  14483. var current = this;
  14484. do {
  14485. if (!current.$$listenerCount[name]) {
  14486. current.$$listenerCount[name] = 0;
  14487. }
  14488. current.$$listenerCount[name]++;
  14489. } while ((current = current.$parent));
  14490. var self = this;
  14491. return function() {
  14492. var indexOfListener = namedListeners.indexOf(listener);
  14493. if (indexOfListener !== -1) {
  14494. namedListeners[indexOfListener] = null;
  14495. decrementListenerCount(self, 1, name);
  14496. }
  14497. };
  14498. },
  14499. /**
  14500. * @ngdoc method
  14501. * @name $rootScope.Scope#$emit
  14502. * @kind function
  14503. *
  14504. * @description
  14505. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  14506. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14507. *
  14508. * The event life cycle starts at the scope on which `$emit` was called. All
  14509. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14510. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  14511. * registered listeners along the way. The event will stop propagating if one of the listeners
  14512. * cancels it.
  14513. *
  14514. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14515. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14516. *
  14517. * @param {string} name Event name to emit.
  14518. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14519. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  14520. */
  14521. $emit: function(name, args) {
  14522. var empty = [],
  14523. namedListeners,
  14524. scope = this,
  14525. stopPropagation = false,
  14526. event = {
  14527. name: name,
  14528. targetScope: scope,
  14529. stopPropagation: function() {stopPropagation = true;},
  14530. preventDefault: function() {
  14531. event.defaultPrevented = true;
  14532. },
  14533. defaultPrevented: false
  14534. },
  14535. listenerArgs = concat([event], arguments, 1),
  14536. i, length;
  14537. do {
  14538. namedListeners = scope.$$listeners[name] || empty;
  14539. event.currentScope = scope;
  14540. for (i = 0, length = namedListeners.length; i < length; i++) {
  14541. // if listeners were deregistered, defragment the array
  14542. if (!namedListeners[i]) {
  14543. namedListeners.splice(i, 1);
  14544. i--;
  14545. length--;
  14546. continue;
  14547. }
  14548. try {
  14549. //allow all listeners attached to the current scope to run
  14550. namedListeners[i].apply(null, listenerArgs);
  14551. } catch (e) {
  14552. $exceptionHandler(e);
  14553. }
  14554. }
  14555. //if any listener on the current scope stops propagation, prevent bubbling
  14556. if (stopPropagation) {
  14557. event.currentScope = null;
  14558. return event;
  14559. }
  14560. //traverse upwards
  14561. scope = scope.$parent;
  14562. } while (scope);
  14563. event.currentScope = null;
  14564. return event;
  14565. },
  14566. /**
  14567. * @ngdoc method
  14568. * @name $rootScope.Scope#$broadcast
  14569. * @kind function
  14570. *
  14571. * @description
  14572. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  14573. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14574. *
  14575. * The event life cycle starts at the scope on which `$broadcast` was called. All
  14576. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14577. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  14578. * scope and calls all registered listeners along the way. The event cannot be canceled.
  14579. *
  14580. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14581. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14582. *
  14583. * @param {string} name Event name to broadcast.
  14584. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14585. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  14586. */
  14587. $broadcast: function(name, args) {
  14588. var target = this,
  14589. current = target,
  14590. next = target,
  14591. event = {
  14592. name: name,
  14593. targetScope: target,
  14594. preventDefault: function() {
  14595. event.defaultPrevented = true;
  14596. },
  14597. defaultPrevented: false
  14598. };
  14599. if (!target.$$listenerCount[name]) return event;
  14600. var listenerArgs = concat([event], arguments, 1),
  14601. listeners, i, length;
  14602. //down while you can, then up and next sibling or up and next sibling until back at root
  14603. while ((current = next)) {
  14604. event.currentScope = current;
  14605. listeners = current.$$listeners[name] || [];
  14606. for (i = 0, length = listeners.length; i < length; i++) {
  14607. // if listeners were deregistered, defragment the array
  14608. if (!listeners[i]) {
  14609. listeners.splice(i, 1);
  14610. i--;
  14611. length--;
  14612. continue;
  14613. }
  14614. try {
  14615. listeners[i].apply(null, listenerArgs);
  14616. } catch (e) {
  14617. $exceptionHandler(e);
  14618. }
  14619. }
  14620. // Insanity Warning: scope depth-first traversal
  14621. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14622. // this piece should be kept in sync with the traversal in $digest
  14623. // (though it differs due to having the extra check for $$listenerCount)
  14624. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  14625. (current !== target && current.$$nextSibling)))) {
  14626. while (current !== target && !(next = current.$$nextSibling)) {
  14627. current = current.$parent;
  14628. }
  14629. }
  14630. }
  14631. event.currentScope = null;
  14632. return event;
  14633. }
  14634. };
  14635. var $rootScope = new Scope();
  14636. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  14637. var asyncQueue = $rootScope.$$asyncQueue = [];
  14638. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  14639. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  14640. return $rootScope;
  14641. function beginPhase(phase) {
  14642. if ($rootScope.$$phase) {
  14643. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  14644. }
  14645. $rootScope.$$phase = phase;
  14646. }
  14647. function clearPhase() {
  14648. $rootScope.$$phase = null;
  14649. }
  14650. function incrementWatchersCount(current, count) {
  14651. do {
  14652. current.$$watchersCount += count;
  14653. } while ((current = current.$parent));
  14654. }
  14655. function decrementListenerCount(current, count, name) {
  14656. do {
  14657. current.$$listenerCount[name] -= count;
  14658. if (current.$$listenerCount[name] === 0) {
  14659. delete current.$$listenerCount[name];
  14660. }
  14661. } while ((current = current.$parent));
  14662. }
  14663. /**
  14664. * function used as an initial value for watchers.
  14665. * because it's unique we can easily tell it apart from other values
  14666. */
  14667. function initWatchVal() {}
  14668. function flushApplyAsync() {
  14669. while (applyAsyncQueue.length) {
  14670. try {
  14671. applyAsyncQueue.shift()();
  14672. } catch (e) {
  14673. $exceptionHandler(e);
  14674. }
  14675. }
  14676. applyAsyncId = null;
  14677. }
  14678. function scheduleApplyAsync() {
  14679. if (applyAsyncId === null) {
  14680. applyAsyncId = $browser.defer(function() {
  14681. $rootScope.$apply(flushApplyAsync);
  14682. });
  14683. }
  14684. }
  14685. }];
  14686. }
  14687. /**
  14688. * @description
  14689. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  14690. */
  14691. function $$SanitizeUriProvider() {
  14692. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  14693. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  14694. /**
  14695. * @description
  14696. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14697. * urls during a[href] sanitization.
  14698. *
  14699. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14700. *
  14701. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  14702. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  14703. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14704. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14705. *
  14706. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14707. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14708. * chaining otherwise.
  14709. */
  14710. this.aHrefSanitizationWhitelist = function(regexp) {
  14711. if (isDefined(regexp)) {
  14712. aHrefSanitizationWhitelist = regexp;
  14713. return this;
  14714. }
  14715. return aHrefSanitizationWhitelist;
  14716. };
  14717. /**
  14718. * @description
  14719. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14720. * urls during img[src] sanitization.
  14721. *
  14722. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14723. *
  14724. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  14725. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  14726. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14727. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14728. *
  14729. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14730. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14731. * chaining otherwise.
  14732. */
  14733. this.imgSrcSanitizationWhitelist = function(regexp) {
  14734. if (isDefined(regexp)) {
  14735. imgSrcSanitizationWhitelist = regexp;
  14736. return this;
  14737. }
  14738. return imgSrcSanitizationWhitelist;
  14739. };
  14740. this.$get = function() {
  14741. return function sanitizeUri(uri, isImage) {
  14742. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  14743. var normalizedVal;
  14744. normalizedVal = urlResolve(uri).href;
  14745. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  14746. return 'unsafe:' + normalizedVal;
  14747. }
  14748. return uri;
  14749. };
  14750. };
  14751. }
  14752. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  14753. * Any commits to this file should be reviewed with security in mind. *
  14754. * Changes to this file can potentially create security vulnerabilities. *
  14755. * An approval from 2 Core members with history of modifying *
  14756. * this file is required. *
  14757. * *
  14758. * Does the change somehow allow for arbitrary javascript to be executed? *
  14759. * Or allows for someone to change the prototype of built-in objects? *
  14760. * Or gives undesired access to variables likes document or window? *
  14761. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  14762. var $sceMinErr = minErr('$sce');
  14763. var SCE_CONTEXTS = {
  14764. HTML: 'html',
  14765. CSS: 'css',
  14766. URL: 'url',
  14767. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  14768. // url. (e.g. ng-include, script src, templateUrl)
  14769. RESOURCE_URL: 'resourceUrl',
  14770. JS: 'js'
  14771. };
  14772. // Helper functions follow.
  14773. function adjustMatcher(matcher) {
  14774. if (matcher === 'self') {
  14775. return matcher;
  14776. } else if (isString(matcher)) {
  14777. // Strings match exactly except for 2 wildcards - '*' and '**'.
  14778. // '*' matches any character except those from the set ':/.?&'.
  14779. // '**' matches any character (like .* in a RegExp).
  14780. // More than 2 *'s raises an error as it's ill defined.
  14781. if (matcher.indexOf('***') > -1) {
  14782. throw $sceMinErr('iwcard',
  14783. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  14784. }
  14785. matcher = escapeForRegexp(matcher).
  14786. replace('\\*\\*', '.*').
  14787. replace('\\*', '[^:/.?&;]*');
  14788. return new RegExp('^' + matcher + '$');
  14789. } else if (isRegExp(matcher)) {
  14790. // The only other type of matcher allowed is a Regexp.
  14791. // Match entire URL / disallow partial matches.
  14792. // Flags are reset (i.e. no global, ignoreCase or multiline)
  14793. return new RegExp('^' + matcher.source + '$');
  14794. } else {
  14795. throw $sceMinErr('imatcher',
  14796. 'Matchers may only be "self", string patterns or RegExp objects');
  14797. }
  14798. }
  14799. function adjustMatchers(matchers) {
  14800. var adjustedMatchers = [];
  14801. if (isDefined(matchers)) {
  14802. forEach(matchers, function(matcher) {
  14803. adjustedMatchers.push(adjustMatcher(matcher));
  14804. });
  14805. }
  14806. return adjustedMatchers;
  14807. }
  14808. /**
  14809. * @ngdoc service
  14810. * @name $sceDelegate
  14811. * @kind function
  14812. *
  14813. * @description
  14814. *
  14815. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  14816. * Contextual Escaping (SCE)} services to AngularJS.
  14817. *
  14818. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  14819. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  14820. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  14821. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  14822. * work because `$sce` delegates to `$sceDelegate` for these operations.
  14823. *
  14824. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  14825. *
  14826. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  14827. * can override it completely to change the behavior of `$sce`, the common case would
  14828. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  14829. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  14830. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  14831. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  14832. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14833. */
  14834. /**
  14835. * @ngdoc provider
  14836. * @name $sceDelegateProvider
  14837. * @description
  14838. *
  14839. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  14840. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  14841. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  14842. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  14843. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14844. *
  14845. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  14846. * Strict Contextual Escaping (SCE)}.
  14847. *
  14848. * **Example**: Consider the following case. <a name="example"></a>
  14849. *
  14850. * - your app is hosted at url `http://myapp.example.com/`
  14851. * - but some of your templates are hosted on other domains you control such as
  14852. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  14853. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  14854. *
  14855. * Here is what a secure configuration for this scenario might look like:
  14856. *
  14857. * ```
  14858. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  14859. * $sceDelegateProvider.resourceUrlWhitelist([
  14860. * // Allow same origin resource loads.
  14861. * 'self',
  14862. * // Allow loading from our assets domain. Notice the difference between * and **.
  14863. * 'http://srv*.assets.example.com/**'
  14864. * ]);
  14865. *
  14866. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  14867. * $sceDelegateProvider.resourceUrlBlacklist([
  14868. * 'http://myapp.example.com/clickThru**'
  14869. * ]);
  14870. * });
  14871. * ```
  14872. */
  14873. function $SceDelegateProvider() {
  14874. this.SCE_CONTEXTS = SCE_CONTEXTS;
  14875. // Resource URLs can also be trusted by policy.
  14876. var resourceUrlWhitelist = ['self'],
  14877. resourceUrlBlacklist = [];
  14878. /**
  14879. * @ngdoc method
  14880. * @name $sceDelegateProvider#resourceUrlWhitelist
  14881. * @kind function
  14882. *
  14883. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  14884. * provided. This must be an array or null. A snapshot of this array is used so further
  14885. * changes to the array are ignored.
  14886. *
  14887. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14888. * allowed in this array.
  14889. *
  14890. * Note: **an empty whitelist array will block all URLs**!
  14891. *
  14892. * @return {Array} the currently set whitelist array.
  14893. *
  14894. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  14895. * same origin resource requests.
  14896. *
  14897. * @description
  14898. * Sets/Gets the whitelist of trusted resource URLs.
  14899. */
  14900. this.resourceUrlWhitelist = function(value) {
  14901. if (arguments.length) {
  14902. resourceUrlWhitelist = adjustMatchers(value);
  14903. }
  14904. return resourceUrlWhitelist;
  14905. };
  14906. /**
  14907. * @ngdoc method
  14908. * @name $sceDelegateProvider#resourceUrlBlacklist
  14909. * @kind function
  14910. *
  14911. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  14912. * provided. This must be an array or null. A snapshot of this array is used so further
  14913. * changes to the array are ignored.
  14914. *
  14915. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14916. * allowed in this array.
  14917. *
  14918. * The typical usage for the blacklist is to **block
  14919. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  14920. * these would otherwise be trusted but actually return content from the redirected domain.
  14921. *
  14922. * Finally, **the blacklist overrides the whitelist** and has the final say.
  14923. *
  14924. * @return {Array} the currently set blacklist array.
  14925. *
  14926. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  14927. * is no blacklist.)
  14928. *
  14929. * @description
  14930. * Sets/Gets the blacklist of trusted resource URLs.
  14931. */
  14932. this.resourceUrlBlacklist = function(value) {
  14933. if (arguments.length) {
  14934. resourceUrlBlacklist = adjustMatchers(value);
  14935. }
  14936. return resourceUrlBlacklist;
  14937. };
  14938. this.$get = ['$injector', function($injector) {
  14939. var htmlSanitizer = function htmlSanitizer(html) {
  14940. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  14941. };
  14942. if ($injector.has('$sanitize')) {
  14943. htmlSanitizer = $injector.get('$sanitize');
  14944. }
  14945. function matchUrl(matcher, parsedUrl) {
  14946. if (matcher === 'self') {
  14947. return urlIsSameOrigin(parsedUrl);
  14948. } else {
  14949. // definitely a regex. See adjustMatchers()
  14950. return !!matcher.exec(parsedUrl.href);
  14951. }
  14952. }
  14953. function isResourceUrlAllowedByPolicy(url) {
  14954. var parsedUrl = urlResolve(url.toString());
  14955. var i, n, allowed = false;
  14956. // Ensure that at least one item from the whitelist allows this url.
  14957. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  14958. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  14959. allowed = true;
  14960. break;
  14961. }
  14962. }
  14963. if (allowed) {
  14964. // Ensure that no item from the blacklist blocked this url.
  14965. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  14966. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  14967. allowed = false;
  14968. break;
  14969. }
  14970. }
  14971. }
  14972. return allowed;
  14973. }
  14974. function generateHolderType(Base) {
  14975. var holderType = function TrustedValueHolderType(trustedValue) {
  14976. this.$$unwrapTrustedValue = function() {
  14977. return trustedValue;
  14978. };
  14979. };
  14980. if (Base) {
  14981. holderType.prototype = new Base();
  14982. }
  14983. holderType.prototype.valueOf = function sceValueOf() {
  14984. return this.$$unwrapTrustedValue();
  14985. };
  14986. holderType.prototype.toString = function sceToString() {
  14987. return this.$$unwrapTrustedValue().toString();
  14988. };
  14989. return holderType;
  14990. }
  14991. var trustedValueHolderBase = generateHolderType(),
  14992. byType = {};
  14993. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  14994. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  14995. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  14996. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  14997. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  14998. /**
  14999. * @ngdoc method
  15000. * @name $sceDelegate#trustAs
  15001. *
  15002. * @description
  15003. * Returns an object that is trusted by angular for use in specified strict
  15004. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  15005. * attribute interpolation, any dom event binding attribute interpolation
  15006. * such as for onclick, etc.) that uses the provided value.
  15007. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  15008. *
  15009. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15010. * resourceUrl, html, js and css.
  15011. * @param {*} value The value that that should be considered trusted/safe.
  15012. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15013. * where Angular expects a $sce.trustAs() return value.
  15014. */
  15015. function trustAs(type, trustedValue) {
  15016. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15017. if (!Constructor) {
  15018. throw $sceMinErr('icontext',
  15019. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  15020. type, trustedValue);
  15021. }
  15022. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  15023. return trustedValue;
  15024. }
  15025. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  15026. // mutable objects, we ensure here that the value passed in is actually a string.
  15027. if (typeof trustedValue !== 'string') {
  15028. throw $sceMinErr('itype',
  15029. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  15030. type);
  15031. }
  15032. return new Constructor(trustedValue);
  15033. }
  15034. /**
  15035. * @ngdoc method
  15036. * @name $sceDelegate#valueOf
  15037. *
  15038. * @description
  15039. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  15040. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  15041. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  15042. *
  15043. * If the passed parameter is not a value that had been returned by {@link
  15044. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  15045. *
  15046. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  15047. * call or anything else.
  15048. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  15049. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  15050. * `value` unchanged.
  15051. */
  15052. function valueOf(maybeTrusted) {
  15053. if (maybeTrusted instanceof trustedValueHolderBase) {
  15054. return maybeTrusted.$$unwrapTrustedValue();
  15055. } else {
  15056. return maybeTrusted;
  15057. }
  15058. }
  15059. /**
  15060. * @ngdoc method
  15061. * @name $sceDelegate#getTrusted
  15062. *
  15063. * @description
  15064. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  15065. * returns the originally supplied value if the queried context type is a supertype of the
  15066. * created type. If this condition isn't satisfied, throws an exception.
  15067. *
  15068. * @param {string} type The kind of context in which this value is to be used.
  15069. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  15070. * `$sceDelegate.trustAs`} call.
  15071. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  15072. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  15073. */
  15074. function getTrusted(type, maybeTrusted) {
  15075. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  15076. return maybeTrusted;
  15077. }
  15078. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15079. if (constructor && maybeTrusted instanceof constructor) {
  15080. return maybeTrusted.$$unwrapTrustedValue();
  15081. }
  15082. // If we get here, then we may only take one of two actions.
  15083. // 1. sanitize the value for the requested type, or
  15084. // 2. throw an exception.
  15085. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  15086. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  15087. return maybeTrusted;
  15088. } else {
  15089. throw $sceMinErr('insecurl',
  15090. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  15091. maybeTrusted.toString());
  15092. }
  15093. } else if (type === SCE_CONTEXTS.HTML) {
  15094. return htmlSanitizer(maybeTrusted);
  15095. }
  15096. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15097. }
  15098. return { trustAs: trustAs,
  15099. getTrusted: getTrusted,
  15100. valueOf: valueOf };
  15101. }];
  15102. }
  15103. /**
  15104. * @ngdoc provider
  15105. * @name $sceProvider
  15106. * @description
  15107. *
  15108. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  15109. * - enable/disable Strict Contextual Escaping (SCE) in a module
  15110. * - override the default implementation with a custom delegate
  15111. *
  15112. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  15113. */
  15114. /* jshint maxlen: false*/
  15115. /**
  15116. * @ngdoc service
  15117. * @name $sce
  15118. * @kind function
  15119. *
  15120. * @description
  15121. *
  15122. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  15123. *
  15124. * # Strict Contextual Escaping
  15125. *
  15126. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  15127. * contexts to result in a value that is marked as safe to use for that context. One example of
  15128. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  15129. * to these contexts as privileged or SCE contexts.
  15130. *
  15131. * As of version 1.2, Angular ships with SCE enabled by default.
  15132. *
  15133. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  15134. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  15135. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  15136. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  15137. * to the top of your HTML document.
  15138. *
  15139. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  15140. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  15141. *
  15142. * Here's an example of a binding in a privileged context:
  15143. *
  15144. * ```
  15145. * <input ng-model="userHtml" aria-label="User input">
  15146. * <div ng-bind-html="userHtml"></div>
  15147. * ```
  15148. *
  15149. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  15150. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  15151. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  15152. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  15153. * security vulnerabilities.)
  15154. *
  15155. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  15156. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  15157. *
  15158. * How would you ensure that every place that used these types of bindings was bound to a value that
  15159. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  15160. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  15161. * properties/fields and forgot to update the binding to the sanitized value?
  15162. *
  15163. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  15164. * determine that something explicitly says it's safe to use a value for binding in that
  15165. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  15166. * for those values that you can easily tell are safe - because they were received from your server,
  15167. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  15168. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  15169. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  15170. *
  15171. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  15172. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  15173. * obtain values that will be accepted by SCE / privileged contexts.
  15174. *
  15175. *
  15176. * ## How does it work?
  15177. *
  15178. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  15179. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  15180. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  15181. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  15182. *
  15183. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  15184. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  15185. * simplified):
  15186. *
  15187. * ```
  15188. * var ngBindHtmlDirective = ['$sce', function($sce) {
  15189. * return function(scope, element, attr) {
  15190. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  15191. * element.html(value || '');
  15192. * });
  15193. * };
  15194. * }];
  15195. * ```
  15196. *
  15197. * ## Impact on loading templates
  15198. *
  15199. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  15200. * `templateUrl`'s specified by {@link guide/directive directives}.
  15201. *
  15202. * By default, Angular only loads templates from the same domain and protocol as the application
  15203. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  15204. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  15205. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  15206. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  15207. *
  15208. * *Please note*:
  15209. * The browser's
  15210. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  15211. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  15212. * policy apply in addition to this and may further restrict whether the template is successfully
  15213. * loaded. This means that without the right CORS policy, loading templates from a different domain
  15214. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  15215. * browsers.
  15216. *
  15217. * ## This feels like too much overhead
  15218. *
  15219. * It's important to remember that SCE only applies to interpolation expressions.
  15220. *
  15221. * If your expressions are constant literals, they're automatically trusted and you don't need to
  15222. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  15223. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  15224. *
  15225. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  15226. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  15227. *
  15228. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  15229. * templates in `ng-include` from your application's domain without having to even know about SCE.
  15230. * It blocks loading templates from other domains or loading templates over http from an https
  15231. * served document. You can change these by setting your own custom {@link
  15232. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  15233. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  15234. *
  15235. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  15236. * application that's secure and can be audited to verify that with much more ease than bolting
  15237. * security onto an application later.
  15238. *
  15239. * <a name="contexts"></a>
  15240. * ## What trusted context types are supported?
  15241. *
  15242. * | Context | Notes |
  15243. * |---------------------|----------------|
  15244. * | `$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. |
  15245. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  15246. * | `$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. |
  15247. * | `$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. |
  15248. * | `$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. |
  15249. *
  15250. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  15251. *
  15252. * Each element in these arrays must be one of the following:
  15253. *
  15254. * - **'self'**
  15255. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  15256. * domain** as the application document using the **same protocol**.
  15257. * - **String** (except the special value `'self'`)
  15258. * - The string is matched against the full *normalized / absolute URL* of the resource
  15259. * being tested (substring matches are not good enough.)
  15260. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  15261. * match themselves.
  15262. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  15263. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  15264. * in a whitelist.
  15265. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  15266. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  15267. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  15268. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  15269. * http://foo.example.com/templates/**).
  15270. * - **RegExp** (*see caveat below*)
  15271. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  15272. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  15273. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  15274. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  15275. * small number of cases. A `.` character in the regex used when matching the scheme or a
  15276. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  15277. * is highly recommended to use the string patterns and only fall back to regular expressions
  15278. * if they as a last resort.
  15279. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  15280. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  15281. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  15282. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  15283. * - If you are generating your JavaScript from some other templating engine (not
  15284. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  15285. * remember to escape your regular expression (and be aware that you might need more than
  15286. * one level of escaping depending on your templating engine and the way you interpolated
  15287. * the value.) Do make use of your platform's escaping mechanism as it might be good
  15288. * enough before coding your own. e.g. Ruby has
  15289. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  15290. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  15291. * Javascript lacks a similar built in function for escaping. Take a look at Google
  15292. * Closure library's [goog.string.regExpEscape(s)](
  15293. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  15294. *
  15295. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  15296. *
  15297. * ## Show me an example using SCE.
  15298. *
  15299. * <example module="mySceApp" deps="angular-sanitize.js">
  15300. * <file name="index.html">
  15301. * <div ng-controller="AppController as myCtrl">
  15302. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  15303. * <b>User comments</b><br>
  15304. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  15305. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  15306. * exploit.
  15307. * <div class="well">
  15308. * <div ng-repeat="userComment in myCtrl.userComments">
  15309. * <b>{{userComment.name}}</b>:
  15310. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  15311. * <br>
  15312. * </div>
  15313. * </div>
  15314. * </div>
  15315. * </file>
  15316. *
  15317. * <file name="script.js">
  15318. * angular.module('mySceApp', ['ngSanitize'])
  15319. * .controller('AppController', ['$http', '$templateCache', '$sce',
  15320. * function($http, $templateCache, $sce) {
  15321. * var self = this;
  15322. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  15323. * self.userComments = userComments;
  15324. * });
  15325. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  15326. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15327. * 'sanitization.&quot;">Hover over this text.</span>');
  15328. * }]);
  15329. * </file>
  15330. *
  15331. * <file name="test_data.json">
  15332. * [
  15333. * { "name": "Alice",
  15334. * "htmlComment":
  15335. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  15336. * },
  15337. * { "name": "Bob",
  15338. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  15339. * }
  15340. * ]
  15341. * </file>
  15342. *
  15343. * <file name="protractor.js" type="protractor">
  15344. * describe('SCE doc demo', function() {
  15345. * it('should sanitize untrusted values', function() {
  15346. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  15347. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  15348. * });
  15349. *
  15350. * it('should NOT sanitize explicitly trusted values', function() {
  15351. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  15352. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15353. * 'sanitization.&quot;">Hover over this text.</span>');
  15354. * });
  15355. * });
  15356. * </file>
  15357. * </example>
  15358. *
  15359. *
  15360. *
  15361. * ## Can I disable SCE completely?
  15362. *
  15363. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  15364. * for little coding overhead. It will be much harder to take an SCE disabled application and
  15365. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  15366. * for cases where you have a lot of existing code that was written before SCE was introduced and
  15367. * you're migrating them a module at a time.
  15368. *
  15369. * That said, here's how you can completely disable SCE:
  15370. *
  15371. * ```
  15372. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  15373. * // Completely disable SCE. For demonstration purposes only!
  15374. * // Do not use in new projects.
  15375. * $sceProvider.enabled(false);
  15376. * });
  15377. * ```
  15378. *
  15379. */
  15380. /* jshint maxlen: 100 */
  15381. function $SceProvider() {
  15382. var enabled = true;
  15383. /**
  15384. * @ngdoc method
  15385. * @name $sceProvider#enabled
  15386. * @kind function
  15387. *
  15388. * @param {boolean=} value If provided, then enables/disables SCE.
  15389. * @return {boolean} true if SCE is enabled, false otherwise.
  15390. *
  15391. * @description
  15392. * Enables/disables SCE and returns the current value.
  15393. */
  15394. this.enabled = function(value) {
  15395. if (arguments.length) {
  15396. enabled = !!value;
  15397. }
  15398. return enabled;
  15399. };
  15400. /* Design notes on the default implementation for SCE.
  15401. *
  15402. * The API contract for the SCE delegate
  15403. * -------------------------------------
  15404. * The SCE delegate object must provide the following 3 methods:
  15405. *
  15406. * - trustAs(contextEnum, value)
  15407. * This method is used to tell the SCE service that the provided value is OK to use in the
  15408. * contexts specified by contextEnum. It must return an object that will be accepted by
  15409. * getTrusted() for a compatible contextEnum and return this value.
  15410. *
  15411. * - valueOf(value)
  15412. * For values that were not produced by trustAs(), return them as is. For values that were
  15413. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  15414. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  15415. * such a value.
  15416. *
  15417. * - getTrusted(contextEnum, value)
  15418. * This function should return the a value that is safe to use in the context specified by
  15419. * contextEnum or throw and exception otherwise.
  15420. *
  15421. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  15422. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  15423. * instance, an implementation could maintain a registry of all trusted objects by context. In
  15424. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  15425. * return the same object passed in if it was found in the registry under a compatible context or
  15426. * throw an exception otherwise. An implementation might only wrap values some of the time based
  15427. * on some criteria. getTrusted() might return a value and not throw an exception for special
  15428. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  15429. *
  15430. *
  15431. * A note on the inheritance model for SCE contexts
  15432. * ------------------------------------------------
  15433. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  15434. * is purely an implementation details.
  15435. *
  15436. * The contract is simply this:
  15437. *
  15438. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  15439. * will also succeed.
  15440. *
  15441. * Inheritance happens to capture this in a natural way. In some future, we
  15442. * may not use inheritance anymore. That is OK because no code outside of
  15443. * sce.js and sceSpecs.js would need to be aware of this detail.
  15444. */
  15445. this.$get = ['$parse', '$sceDelegate', function(
  15446. $parse, $sceDelegate) {
  15447. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  15448. // the "expression(javascript expression)" syntax which is insecure.
  15449. if (enabled && msie < 8) {
  15450. throw $sceMinErr('iequirks',
  15451. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  15452. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  15453. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  15454. }
  15455. var sce = shallowCopy(SCE_CONTEXTS);
  15456. /**
  15457. * @ngdoc method
  15458. * @name $sce#isEnabled
  15459. * @kind function
  15460. *
  15461. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  15462. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  15463. *
  15464. * @description
  15465. * Returns a boolean indicating if SCE is enabled.
  15466. */
  15467. sce.isEnabled = function() {
  15468. return enabled;
  15469. };
  15470. sce.trustAs = $sceDelegate.trustAs;
  15471. sce.getTrusted = $sceDelegate.getTrusted;
  15472. sce.valueOf = $sceDelegate.valueOf;
  15473. if (!enabled) {
  15474. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  15475. sce.valueOf = identity;
  15476. }
  15477. /**
  15478. * @ngdoc method
  15479. * @name $sce#parseAs
  15480. *
  15481. * @description
  15482. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  15483. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  15484. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  15485. * *result*)}
  15486. *
  15487. * @param {string} type The kind of SCE context in which this result will be used.
  15488. * @param {string} expression String expression to compile.
  15489. * @returns {function(context, locals)} a function which represents the compiled expression:
  15490. *
  15491. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15492. * are evaluated against (typically a scope object).
  15493. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15494. * `context`.
  15495. */
  15496. sce.parseAs = function sceParseAs(type, expr) {
  15497. var parsed = $parse(expr);
  15498. if (parsed.literal && parsed.constant) {
  15499. return parsed;
  15500. } else {
  15501. return $parse(expr, function(value) {
  15502. return sce.getTrusted(type, value);
  15503. });
  15504. }
  15505. };
  15506. /**
  15507. * @ngdoc method
  15508. * @name $sce#trustAs
  15509. *
  15510. * @description
  15511. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  15512. * returns an object that is trusted by angular for use in specified strict contextual
  15513. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  15514. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  15515. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  15516. * escaping.
  15517. *
  15518. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15519. * resourceUrl, html, js and css.
  15520. * @param {*} value The value that that should be considered trusted/safe.
  15521. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15522. * where Angular expects a $sce.trustAs() return value.
  15523. */
  15524. /**
  15525. * @ngdoc method
  15526. * @name $sce#trustAsHtml
  15527. *
  15528. * @description
  15529. * Shorthand method. `$sce.trustAsHtml(value)` →
  15530. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  15531. *
  15532. * @param {*} value The value to trustAs.
  15533. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  15534. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  15535. * only accept expressions that are either literal constants or are the
  15536. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15537. */
  15538. /**
  15539. * @ngdoc method
  15540. * @name $sce#trustAsUrl
  15541. *
  15542. * @description
  15543. * Shorthand method. `$sce.trustAsUrl(value)` →
  15544. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  15545. *
  15546. * @param {*} value The value to trustAs.
  15547. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  15548. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  15549. * only accept expressions that are either literal constants or are the
  15550. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15551. */
  15552. /**
  15553. * @ngdoc method
  15554. * @name $sce#trustAsResourceUrl
  15555. *
  15556. * @description
  15557. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  15558. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  15559. *
  15560. * @param {*} value The value to trustAs.
  15561. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  15562. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  15563. * only accept expressions that are either literal constants or are the return
  15564. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15565. */
  15566. /**
  15567. * @ngdoc method
  15568. * @name $sce#trustAsJs
  15569. *
  15570. * @description
  15571. * Shorthand method. `$sce.trustAsJs(value)` →
  15572. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  15573. *
  15574. * @param {*} value The value to trustAs.
  15575. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  15576. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  15577. * only accept expressions that are either literal constants or are the
  15578. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15579. */
  15580. /**
  15581. * @ngdoc method
  15582. * @name $sce#getTrusted
  15583. *
  15584. * @description
  15585. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  15586. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  15587. * originally supplied value if the queried context type is a supertype of the created type.
  15588. * If this condition isn't satisfied, throws an exception.
  15589. *
  15590. * @param {string} type The kind of context in which this value is to be used.
  15591. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  15592. * call.
  15593. * @returns {*} The value the was originally provided to
  15594. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  15595. * Otherwise, throws an exception.
  15596. */
  15597. /**
  15598. * @ngdoc method
  15599. * @name $sce#getTrustedHtml
  15600. *
  15601. * @description
  15602. * Shorthand method. `$sce.getTrustedHtml(value)` →
  15603. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  15604. *
  15605. * @param {*} value The value to pass to `$sce.getTrusted`.
  15606. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  15607. */
  15608. /**
  15609. * @ngdoc method
  15610. * @name $sce#getTrustedCss
  15611. *
  15612. * @description
  15613. * Shorthand method. `$sce.getTrustedCss(value)` →
  15614. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  15615. *
  15616. * @param {*} value The value to pass to `$sce.getTrusted`.
  15617. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  15618. */
  15619. /**
  15620. * @ngdoc method
  15621. * @name $sce#getTrustedUrl
  15622. *
  15623. * @description
  15624. * Shorthand method. `$sce.getTrustedUrl(value)` →
  15625. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  15626. *
  15627. * @param {*} value The value to pass to `$sce.getTrusted`.
  15628. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  15629. */
  15630. /**
  15631. * @ngdoc method
  15632. * @name $sce#getTrustedResourceUrl
  15633. *
  15634. * @description
  15635. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  15636. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  15637. *
  15638. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  15639. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  15640. */
  15641. /**
  15642. * @ngdoc method
  15643. * @name $sce#getTrustedJs
  15644. *
  15645. * @description
  15646. * Shorthand method. `$sce.getTrustedJs(value)` →
  15647. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  15648. *
  15649. * @param {*} value The value to pass to `$sce.getTrusted`.
  15650. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  15651. */
  15652. /**
  15653. * @ngdoc method
  15654. * @name $sce#parseAsHtml
  15655. *
  15656. * @description
  15657. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  15658. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  15659. *
  15660. * @param {string} expression String expression to compile.
  15661. * @returns {function(context, locals)} a function which represents the compiled expression:
  15662. *
  15663. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15664. * are evaluated against (typically a scope object).
  15665. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15666. * `context`.
  15667. */
  15668. /**
  15669. * @ngdoc method
  15670. * @name $sce#parseAsCss
  15671. *
  15672. * @description
  15673. * Shorthand method. `$sce.parseAsCss(value)` →
  15674. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  15675. *
  15676. * @param {string} expression String expression to compile.
  15677. * @returns {function(context, locals)} a function which represents the compiled expression:
  15678. *
  15679. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15680. * are evaluated against (typically a scope object).
  15681. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15682. * `context`.
  15683. */
  15684. /**
  15685. * @ngdoc method
  15686. * @name $sce#parseAsUrl
  15687. *
  15688. * @description
  15689. * Shorthand method. `$sce.parseAsUrl(value)` →
  15690. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  15691. *
  15692. * @param {string} expression String expression to compile.
  15693. * @returns {function(context, locals)} a function which represents the compiled expression:
  15694. *
  15695. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15696. * are evaluated against (typically a scope object).
  15697. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15698. * `context`.
  15699. */
  15700. /**
  15701. * @ngdoc method
  15702. * @name $sce#parseAsResourceUrl
  15703. *
  15704. * @description
  15705. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  15706. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  15707. *
  15708. * @param {string} expression String expression to compile.
  15709. * @returns {function(context, locals)} a function which represents the compiled expression:
  15710. *
  15711. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15712. * are evaluated against (typically a scope object).
  15713. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15714. * `context`.
  15715. */
  15716. /**
  15717. * @ngdoc method
  15718. * @name $sce#parseAsJs
  15719. *
  15720. * @description
  15721. * Shorthand method. `$sce.parseAsJs(value)` →
  15722. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  15723. *
  15724. * @param {string} expression String expression to compile.
  15725. * @returns {function(context, locals)} a function which represents the compiled expression:
  15726. *
  15727. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15728. * are evaluated against (typically a scope object).
  15729. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15730. * `context`.
  15731. */
  15732. // Shorthand delegations.
  15733. var parse = sce.parseAs,
  15734. getTrusted = sce.getTrusted,
  15735. trustAs = sce.trustAs;
  15736. forEach(SCE_CONTEXTS, function(enumValue, name) {
  15737. var lName = lowercase(name);
  15738. sce[camelCase("parse_as_" + lName)] = function(expr) {
  15739. return parse(enumValue, expr);
  15740. };
  15741. sce[camelCase("get_trusted_" + lName)] = function(value) {
  15742. return getTrusted(enumValue, value);
  15743. };
  15744. sce[camelCase("trust_as_" + lName)] = function(value) {
  15745. return trustAs(enumValue, value);
  15746. };
  15747. });
  15748. return sce;
  15749. }];
  15750. }
  15751. /**
  15752. * !!! This is an undocumented "private" service !!!
  15753. *
  15754. * @name $sniffer
  15755. * @requires $window
  15756. * @requires $document
  15757. *
  15758. * @property {boolean} history Does the browser support html5 history api ?
  15759. * @property {boolean} transitions Does the browser support CSS transition events ?
  15760. * @property {boolean} animations Does the browser support CSS animation events ?
  15761. *
  15762. * @description
  15763. * This is very simple implementation of testing browser's features.
  15764. */
  15765. function $SnifferProvider() {
  15766. this.$get = ['$window', '$document', function($window, $document) {
  15767. var eventSupport = {},
  15768. android =
  15769. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  15770. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  15771. document = $document[0] || {},
  15772. vendorPrefix,
  15773. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  15774. bodyStyle = document.body && document.body.style,
  15775. transitions = false,
  15776. animations = false,
  15777. match;
  15778. if (bodyStyle) {
  15779. for (var prop in bodyStyle) {
  15780. if (match = vendorRegex.exec(prop)) {
  15781. vendorPrefix = match[0];
  15782. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  15783. break;
  15784. }
  15785. }
  15786. if (!vendorPrefix) {
  15787. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  15788. }
  15789. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  15790. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  15791. if (android && (!transitions || !animations)) {
  15792. transitions = isString(bodyStyle.webkitTransition);
  15793. animations = isString(bodyStyle.webkitAnimation);
  15794. }
  15795. }
  15796. return {
  15797. // Android has history.pushState, but it does not update location correctly
  15798. // so let's not use the history API at all.
  15799. // http://code.google.com/p/android/issues/detail?id=17471
  15800. // https://github.com/angular/angular.js/issues/904
  15801. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  15802. // so let's not use the history API also
  15803. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  15804. // jshint -W018
  15805. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  15806. // jshint +W018
  15807. hasEvent: function(event) {
  15808. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  15809. // it. In particular the event is not fired when backspace or delete key are pressed or
  15810. // when cut operation is performed.
  15811. // IE10+ implements 'input' event but it erroneously fires under various situations,
  15812. // e.g. when placeholder changes, or a form is focused.
  15813. if (event === 'input' && msie <= 11) return false;
  15814. if (isUndefined(eventSupport[event])) {
  15815. var divElm = document.createElement('div');
  15816. eventSupport[event] = 'on' + event in divElm;
  15817. }
  15818. return eventSupport[event];
  15819. },
  15820. csp: csp(),
  15821. vendorPrefix: vendorPrefix,
  15822. transitions: transitions,
  15823. animations: animations,
  15824. android: android
  15825. };
  15826. }];
  15827. }
  15828. var $compileMinErr = minErr('$compile');
  15829. /**
  15830. * @ngdoc service
  15831. * @name $templateRequest
  15832. *
  15833. * @description
  15834. * The `$templateRequest` service runs security checks then downloads the provided template using
  15835. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  15836. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  15837. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  15838. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  15839. * when `tpl` is of type string and `$templateCache` has the matching entry.
  15840. *
  15841. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  15842. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  15843. *
  15844. * @return {Promise} a promise for the HTTP response data of the given URL.
  15845. *
  15846. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  15847. */
  15848. function $TemplateRequestProvider() {
  15849. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  15850. function handleRequestFn(tpl, ignoreRequestError) {
  15851. handleRequestFn.totalPendingRequests++;
  15852. // We consider the template cache holds only trusted templates, so
  15853. // there's no need to go through whitelisting again for keys that already
  15854. // are included in there. This also makes Angular accept any script
  15855. // directive, no matter its name. However, we still need to unwrap trusted
  15856. // types.
  15857. if (!isString(tpl) || !$templateCache.get(tpl)) {
  15858. tpl = $sce.getTrustedResourceUrl(tpl);
  15859. }
  15860. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  15861. if (isArray(transformResponse)) {
  15862. transformResponse = transformResponse.filter(function(transformer) {
  15863. return transformer !== defaultHttpResponseTransform;
  15864. });
  15865. } else if (transformResponse === defaultHttpResponseTransform) {
  15866. transformResponse = null;
  15867. }
  15868. var httpOptions = {
  15869. cache: $templateCache,
  15870. transformResponse: transformResponse
  15871. };
  15872. return $http.get(tpl, httpOptions)
  15873. ['finally'](function() {
  15874. handleRequestFn.totalPendingRequests--;
  15875. })
  15876. .then(function(response) {
  15877. $templateCache.put(tpl, response.data);
  15878. return response.data;
  15879. }, handleError);
  15880. function handleError(resp) {
  15881. if (!ignoreRequestError) {
  15882. throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  15883. tpl, resp.status, resp.statusText);
  15884. }
  15885. return $q.reject(resp);
  15886. }
  15887. }
  15888. handleRequestFn.totalPendingRequests = 0;
  15889. return handleRequestFn;
  15890. }];
  15891. }
  15892. function $$TestabilityProvider() {
  15893. this.$get = ['$rootScope', '$browser', '$location',
  15894. function($rootScope, $browser, $location) {
  15895. /**
  15896. * @name $testability
  15897. *
  15898. * @description
  15899. * The private $$testability service provides a collection of methods for use when debugging
  15900. * or by automated test and debugging tools.
  15901. */
  15902. var testability = {};
  15903. /**
  15904. * @name $$testability#findBindings
  15905. *
  15906. * @description
  15907. * Returns an array of elements that are bound (via ng-bind or {{}})
  15908. * to expressions matching the input.
  15909. *
  15910. * @param {Element} element The element root to search from.
  15911. * @param {string} expression The binding expression to match.
  15912. * @param {boolean} opt_exactMatch If true, only returns exact matches
  15913. * for the expression. Filters and whitespace are ignored.
  15914. */
  15915. testability.findBindings = function(element, expression, opt_exactMatch) {
  15916. var bindings = element.getElementsByClassName('ng-binding');
  15917. var matches = [];
  15918. forEach(bindings, function(binding) {
  15919. var dataBinding = angular.element(binding).data('$binding');
  15920. if (dataBinding) {
  15921. forEach(dataBinding, function(bindingName) {
  15922. if (opt_exactMatch) {
  15923. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  15924. if (matcher.test(bindingName)) {
  15925. matches.push(binding);
  15926. }
  15927. } else {
  15928. if (bindingName.indexOf(expression) != -1) {
  15929. matches.push(binding);
  15930. }
  15931. }
  15932. });
  15933. }
  15934. });
  15935. return matches;
  15936. };
  15937. /**
  15938. * @name $$testability#findModels
  15939. *
  15940. * @description
  15941. * Returns an array of elements that are two-way found via ng-model to
  15942. * expressions matching the input.
  15943. *
  15944. * @param {Element} element The element root to search from.
  15945. * @param {string} expression The model expression to match.
  15946. * @param {boolean} opt_exactMatch If true, only returns exact matches
  15947. * for the expression.
  15948. */
  15949. testability.findModels = function(element, expression, opt_exactMatch) {
  15950. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  15951. for (var p = 0; p < prefixes.length; ++p) {
  15952. var attributeEquals = opt_exactMatch ? '=' : '*=';
  15953. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  15954. var elements = element.querySelectorAll(selector);
  15955. if (elements.length) {
  15956. return elements;
  15957. }
  15958. }
  15959. };
  15960. /**
  15961. * @name $$testability#getLocation
  15962. *
  15963. * @description
  15964. * Shortcut for getting the location in a browser agnostic way. Returns
  15965. * the path, search, and hash. (e.g. /path?a=b#hash)
  15966. */
  15967. testability.getLocation = function() {
  15968. return $location.url();
  15969. };
  15970. /**
  15971. * @name $$testability#setLocation
  15972. *
  15973. * @description
  15974. * Shortcut for navigating to a location without doing a full page reload.
  15975. *
  15976. * @param {string} url The location url (path, search and hash,
  15977. * e.g. /path?a=b#hash) to go to.
  15978. */
  15979. testability.setLocation = function(url) {
  15980. if (url !== $location.url()) {
  15981. $location.url(url);
  15982. $rootScope.$digest();
  15983. }
  15984. };
  15985. /**
  15986. * @name $$testability#whenStable
  15987. *
  15988. * @description
  15989. * Calls the callback when $timeout and $http requests are completed.
  15990. *
  15991. * @param {function} callback
  15992. */
  15993. testability.whenStable = function(callback) {
  15994. $browser.notifyWhenNoOutstandingRequests(callback);
  15995. };
  15996. return testability;
  15997. }];
  15998. }
  15999. function $TimeoutProvider() {
  16000. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  16001. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  16002. var deferreds = {};
  16003. /**
  16004. * @ngdoc service
  16005. * @name $timeout
  16006. *
  16007. * @description
  16008. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  16009. * block and delegates any exceptions to
  16010. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16011. *
  16012. * The return value of calling `$timeout` is a promise, which will be resolved when
  16013. * the delay has passed and the timeout function, if provided, is executed.
  16014. *
  16015. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  16016. *
  16017. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  16018. * synchronously flush the queue of deferred functions.
  16019. *
  16020. * If you only want a promise that will be resolved after some specified delay
  16021. * then you can call `$timeout` without the `fn` function.
  16022. *
  16023. * @param {function()=} fn A function, whose execution should be delayed.
  16024. * @param {number=} [delay=0] Delay in milliseconds.
  16025. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  16026. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  16027. * @param {...*=} Pass additional parameters to the executed function.
  16028. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  16029. * promise will be resolved with is the return value of the `fn` function.
  16030. *
  16031. */
  16032. function timeout(fn, delay, invokeApply) {
  16033. if (!isFunction(fn)) {
  16034. invokeApply = delay;
  16035. delay = fn;
  16036. fn = noop;
  16037. }
  16038. var args = sliceArgs(arguments, 3),
  16039. skipApply = (isDefined(invokeApply) && !invokeApply),
  16040. deferred = (skipApply ? $$q : $q).defer(),
  16041. promise = deferred.promise,
  16042. timeoutId;
  16043. timeoutId = $browser.defer(function() {
  16044. try {
  16045. deferred.resolve(fn.apply(null, args));
  16046. } catch (e) {
  16047. deferred.reject(e);
  16048. $exceptionHandler(e);
  16049. }
  16050. finally {
  16051. delete deferreds[promise.$$timeoutId];
  16052. }
  16053. if (!skipApply) $rootScope.$apply();
  16054. }, delay);
  16055. promise.$$timeoutId = timeoutId;
  16056. deferreds[timeoutId] = deferred;
  16057. return promise;
  16058. }
  16059. /**
  16060. * @ngdoc method
  16061. * @name $timeout#cancel
  16062. *
  16063. * @description
  16064. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  16065. * resolved with a rejection.
  16066. *
  16067. * @param {Promise=} promise Promise returned by the `$timeout` function.
  16068. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  16069. * canceled.
  16070. */
  16071. timeout.cancel = function(promise) {
  16072. if (promise && promise.$$timeoutId in deferreds) {
  16073. deferreds[promise.$$timeoutId].reject('canceled');
  16074. delete deferreds[promise.$$timeoutId];
  16075. return $browser.defer.cancel(promise.$$timeoutId);
  16076. }
  16077. return false;
  16078. };
  16079. return timeout;
  16080. }];
  16081. }
  16082. // NOTE: The usage of window and document instead of $window and $document here is
  16083. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  16084. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  16085. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  16086. // doesn't know about mocked locations and resolves URLs to the real document - which is
  16087. // exactly the behavior needed here. There is little value is mocking these out for this
  16088. // service.
  16089. var urlParsingNode = document.createElement("a");
  16090. var originUrl = urlResolve(window.location.href);
  16091. /**
  16092. *
  16093. * Implementation Notes for non-IE browsers
  16094. * ----------------------------------------
  16095. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  16096. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  16097. * URL will be resolved into an absolute URL in the context of the application document.
  16098. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  16099. * properties are all populated to reflect the normalized URL. This approach has wide
  16100. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  16101. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16102. *
  16103. * Implementation Notes for IE
  16104. * ---------------------------
  16105. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  16106. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  16107. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  16108. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  16109. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  16110. * properties such as protocol, hostname, port, etc.
  16111. *
  16112. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  16113. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  16114. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  16115. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  16116. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  16117. * method and IE < 8 is unsupported.
  16118. *
  16119. * References:
  16120. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  16121. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16122. * http://url.spec.whatwg.org/#urlutils
  16123. * https://github.com/angular/angular.js/pull/2902
  16124. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  16125. *
  16126. * @kind function
  16127. * @param {string} url The URL to be parsed.
  16128. * @description Normalizes and parses a URL.
  16129. * @returns {object} Returns the normalized URL as a dictionary.
  16130. *
  16131. * | member name | Description |
  16132. * |---------------|----------------|
  16133. * | href | A normalized version of the provided URL if it was not an absolute URL |
  16134. * | protocol | The protocol including the trailing colon |
  16135. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  16136. * | search | The search params, minus the question mark |
  16137. * | hash | The hash string, minus the hash symbol
  16138. * | hostname | The hostname
  16139. * | port | The port, without ":"
  16140. * | pathname | The pathname, beginning with "/"
  16141. *
  16142. */
  16143. function urlResolve(url) {
  16144. var href = url;
  16145. if (msie) {
  16146. // Normalize before parse. Refer Implementation Notes on why this is
  16147. // done in two steps on IE.
  16148. urlParsingNode.setAttribute("href", href);
  16149. href = urlParsingNode.href;
  16150. }
  16151. urlParsingNode.setAttribute('href', href);
  16152. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  16153. return {
  16154. href: urlParsingNode.href,
  16155. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  16156. host: urlParsingNode.host,
  16157. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  16158. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  16159. hostname: urlParsingNode.hostname,
  16160. port: urlParsingNode.port,
  16161. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  16162. ? urlParsingNode.pathname
  16163. : '/' + urlParsingNode.pathname
  16164. };
  16165. }
  16166. /**
  16167. * Parse a request URL and determine whether this is a same-origin request as the application document.
  16168. *
  16169. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  16170. * or a parsed URL object.
  16171. * @returns {boolean} Whether the request is for the same origin as the application document.
  16172. */
  16173. function urlIsSameOrigin(requestUrl) {
  16174. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  16175. return (parsed.protocol === originUrl.protocol &&
  16176. parsed.host === originUrl.host);
  16177. }
  16178. /**
  16179. * @ngdoc service
  16180. * @name $window
  16181. *
  16182. * @description
  16183. * A reference to the browser's `window` object. While `window`
  16184. * is globally available in JavaScript, it causes testability problems, because
  16185. * it is a global variable. In angular we always refer to it through the
  16186. * `$window` service, so it may be overridden, removed or mocked for testing.
  16187. *
  16188. * Expressions, like the one defined for the `ngClick` directive in the example
  16189. * below, are evaluated with respect to the current scope. Therefore, there is
  16190. * no risk of inadvertently coding in a dependency on a global value in such an
  16191. * expression.
  16192. *
  16193. * @example
  16194. <example module="windowExample">
  16195. <file name="index.html">
  16196. <script>
  16197. angular.module('windowExample', [])
  16198. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  16199. $scope.greeting = 'Hello, World!';
  16200. $scope.doGreeting = function(greeting) {
  16201. $window.alert(greeting);
  16202. };
  16203. }]);
  16204. </script>
  16205. <div ng-controller="ExampleController">
  16206. <input type="text" ng-model="greeting" aria-label="greeting" />
  16207. <button ng-click="doGreeting(greeting)">ALERT</button>
  16208. </div>
  16209. </file>
  16210. <file name="protractor.js" type="protractor">
  16211. it('should display the greeting in the input box', function() {
  16212. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  16213. // If we click the button it will block the test runner
  16214. // element(':button').click();
  16215. });
  16216. </file>
  16217. </example>
  16218. */
  16219. function $WindowProvider() {
  16220. this.$get = valueFn(window);
  16221. }
  16222. /**
  16223. * @name $$cookieReader
  16224. * @requires $document
  16225. *
  16226. * @description
  16227. * This is a private service for reading cookies used by $http and ngCookies
  16228. *
  16229. * @return {Object} a key/value map of the current cookies
  16230. */
  16231. function $$CookieReader($document) {
  16232. var rawDocument = $document[0] || {};
  16233. var lastCookies = {};
  16234. var lastCookieString = '';
  16235. function safeDecodeURIComponent(str) {
  16236. try {
  16237. return decodeURIComponent(str);
  16238. } catch (e) {
  16239. return str;
  16240. }
  16241. }
  16242. return function() {
  16243. var cookieArray, cookie, i, index, name;
  16244. var currentCookieString = rawDocument.cookie || '';
  16245. if (currentCookieString !== lastCookieString) {
  16246. lastCookieString = currentCookieString;
  16247. cookieArray = lastCookieString.split('; ');
  16248. lastCookies = {};
  16249. for (i = 0; i < cookieArray.length; i++) {
  16250. cookie = cookieArray[i];
  16251. index = cookie.indexOf('=');
  16252. if (index > 0) { //ignore nameless cookies
  16253. name = safeDecodeURIComponent(cookie.substring(0, index));
  16254. // the first value that is seen for a cookie is the most
  16255. // specific one. values for the same cookie name that
  16256. // follow are for less specific paths.
  16257. if (lastCookies[name] === undefined) {
  16258. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  16259. }
  16260. }
  16261. }
  16262. }
  16263. return lastCookies;
  16264. };
  16265. }
  16266. $$CookieReader.$inject = ['$document'];
  16267. function $$CookieReaderProvider() {
  16268. this.$get = $$CookieReader;
  16269. }
  16270. /* global currencyFilter: true,
  16271. dateFilter: true,
  16272. filterFilter: true,
  16273. jsonFilter: true,
  16274. limitToFilter: true,
  16275. lowercaseFilter: true,
  16276. numberFilter: true,
  16277. orderByFilter: true,
  16278. uppercaseFilter: true,
  16279. */
  16280. /**
  16281. * @ngdoc provider
  16282. * @name $filterProvider
  16283. * @description
  16284. *
  16285. * Filters are just functions which transform input to an output. However filters need to be
  16286. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  16287. * annotated with dependencies and is responsible for creating a filter function.
  16288. *
  16289. * <div class="alert alert-warning">
  16290. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16291. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16292. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16293. * (`myapp_subsection_filterx`).
  16294. * </div>
  16295. *
  16296. * ```js
  16297. * // Filter registration
  16298. * function MyModule($provide, $filterProvider) {
  16299. * // create a service to demonstrate injection (not always needed)
  16300. * $provide.value('greet', function(name){
  16301. * return 'Hello ' + name + '!';
  16302. * });
  16303. *
  16304. * // register a filter factory which uses the
  16305. * // greet service to demonstrate DI.
  16306. * $filterProvider.register('greet', function(greet){
  16307. * // return the filter function which uses the greet service
  16308. * // to generate salutation
  16309. * return function(text) {
  16310. * // filters need to be forgiving so check input validity
  16311. * return text && greet(text) || text;
  16312. * };
  16313. * });
  16314. * }
  16315. * ```
  16316. *
  16317. * The filter function is registered with the `$injector` under the filter name suffix with
  16318. * `Filter`.
  16319. *
  16320. * ```js
  16321. * it('should be the same instance', inject(
  16322. * function($filterProvider) {
  16323. * $filterProvider.register('reverse', function(){
  16324. * return ...;
  16325. * });
  16326. * },
  16327. * function($filter, reverseFilter) {
  16328. * expect($filter('reverse')).toBe(reverseFilter);
  16329. * });
  16330. * ```
  16331. *
  16332. *
  16333. * For more information about how angular filters work, and how to create your own filters, see
  16334. * {@link guide/filter Filters} in the Angular Developer Guide.
  16335. */
  16336. /**
  16337. * @ngdoc service
  16338. * @name $filter
  16339. * @kind function
  16340. * @description
  16341. * Filters are used for formatting data displayed to the user.
  16342. *
  16343. * The general syntax in templates is as follows:
  16344. *
  16345. * {{ expression [| filter_name[:parameter_value] ... ] }}
  16346. *
  16347. * @param {String} name Name of the filter function to retrieve
  16348. * @return {Function} the filter function
  16349. * @example
  16350. <example name="$filter" module="filterExample">
  16351. <file name="index.html">
  16352. <div ng-controller="MainCtrl">
  16353. <h3>{{ originalText }}</h3>
  16354. <h3>{{ filteredText }}</h3>
  16355. </div>
  16356. </file>
  16357. <file name="script.js">
  16358. angular.module('filterExample', [])
  16359. .controller('MainCtrl', function($scope, $filter) {
  16360. $scope.originalText = 'hello';
  16361. $scope.filteredText = $filter('uppercase')($scope.originalText);
  16362. });
  16363. </file>
  16364. </example>
  16365. */
  16366. $FilterProvider.$inject = ['$provide'];
  16367. function $FilterProvider($provide) {
  16368. var suffix = 'Filter';
  16369. /**
  16370. * @ngdoc method
  16371. * @name $filterProvider#register
  16372. * @param {string|Object} name Name of the filter function, or an object map of filters where
  16373. * the keys are the filter names and the values are the filter factories.
  16374. *
  16375. * <div class="alert alert-warning">
  16376. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16377. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16378. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16379. * (`myapp_subsection_filterx`).
  16380. * </div>
  16381. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  16382. * of the registered filter instances.
  16383. */
  16384. function register(name, factory) {
  16385. if (isObject(name)) {
  16386. var filters = {};
  16387. forEach(name, function(filter, key) {
  16388. filters[key] = register(key, filter);
  16389. });
  16390. return filters;
  16391. } else {
  16392. return $provide.factory(name + suffix, factory);
  16393. }
  16394. }
  16395. this.register = register;
  16396. this.$get = ['$injector', function($injector) {
  16397. return function(name) {
  16398. return $injector.get(name + suffix);
  16399. };
  16400. }];
  16401. ////////////////////////////////////////
  16402. /* global
  16403. currencyFilter: false,
  16404. dateFilter: false,
  16405. filterFilter: false,
  16406. jsonFilter: false,
  16407. limitToFilter: false,
  16408. lowercaseFilter: false,
  16409. numberFilter: false,
  16410. orderByFilter: false,
  16411. uppercaseFilter: false,
  16412. */
  16413. register('currency', currencyFilter);
  16414. register('date', dateFilter);
  16415. register('filter', filterFilter);
  16416. register('json', jsonFilter);
  16417. register('limitTo', limitToFilter);
  16418. register('lowercase', lowercaseFilter);
  16419. register('number', numberFilter);
  16420. register('orderBy', orderByFilter);
  16421. register('uppercase', uppercaseFilter);
  16422. }
  16423. /**
  16424. * @ngdoc filter
  16425. * @name filter
  16426. * @kind function
  16427. *
  16428. * @description
  16429. * Selects a subset of items from `array` and returns it as a new array.
  16430. *
  16431. * @param {Array} array The source array.
  16432. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  16433. * `array`.
  16434. *
  16435. * Can be one of:
  16436. *
  16437. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  16438. * objects with string properties in `array` that match this string will be returned. This also
  16439. * applies to nested object properties.
  16440. * The predicate can be negated by prefixing the string with `!`.
  16441. *
  16442. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  16443. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  16444. * which have property `name` containing "M" and property `phone` containing "1". A special
  16445. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  16446. * property of the object or its nested object properties. That's equivalent to the simple
  16447. * substring match with a `string` as described above. The predicate can be negated by prefixing
  16448. * the string with `!`.
  16449. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  16450. * not containing "M".
  16451. *
  16452. * Note that a named property will match properties on the same level only, while the special
  16453. * `$` property will match properties on the same level or deeper. E.g. an array item like
  16454. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  16455. * **will** be matched by `{$: 'John'}`.
  16456. *
  16457. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  16458. * The function is called for each element of the array, with the element, its index, and
  16459. * the entire array itself as arguments.
  16460. *
  16461. * The final result is an array of those elements that the predicate returned true for.
  16462. *
  16463. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  16464. * determining if the expected value (from the filter expression) and actual value (from
  16465. * the object in the array) should be considered a match.
  16466. *
  16467. * Can be one of:
  16468. *
  16469. * - `function(actual, expected)`:
  16470. * The function will be given the object value and the predicate value to compare and
  16471. * should return true if both values should be considered equal.
  16472. *
  16473. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  16474. * This is essentially strict comparison of expected and actual.
  16475. *
  16476. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  16477. * insensitive way.
  16478. *
  16479. * Primitive values are converted to strings. Objects are not compared against primitives,
  16480. * unless they have a custom `toString` method (e.g. `Date` objects).
  16481. *
  16482. * @example
  16483. <example>
  16484. <file name="index.html">
  16485. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  16486. {name:'Mary', phone:'800-BIG-MARY'},
  16487. {name:'Mike', phone:'555-4321'},
  16488. {name:'Adam', phone:'555-5678'},
  16489. {name:'Julie', phone:'555-8765'},
  16490. {name:'Juliette', phone:'555-5678'}]"></div>
  16491. <label>Search: <input ng-model="searchText"></label>
  16492. <table id="searchTextResults">
  16493. <tr><th>Name</th><th>Phone</th></tr>
  16494. <tr ng-repeat="friend in friends | filter:searchText">
  16495. <td>{{friend.name}}</td>
  16496. <td>{{friend.phone}}</td>
  16497. </tr>
  16498. </table>
  16499. <hr>
  16500. <label>Any: <input ng-model="search.$"></label> <br>
  16501. <label>Name only <input ng-model="search.name"></label><br>
  16502. <label>Phone only <input ng-model="search.phone"></label><br>
  16503. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  16504. <table id="searchObjResults">
  16505. <tr><th>Name</th><th>Phone</th></tr>
  16506. <tr ng-repeat="friendObj in friends | filter:search:strict">
  16507. <td>{{friendObj.name}}</td>
  16508. <td>{{friendObj.phone}}</td>
  16509. </tr>
  16510. </table>
  16511. </file>
  16512. <file name="protractor.js" type="protractor">
  16513. var expectFriendNames = function(expectedNames, key) {
  16514. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  16515. arr.forEach(function(wd, i) {
  16516. expect(wd.getText()).toMatch(expectedNames[i]);
  16517. });
  16518. });
  16519. };
  16520. it('should search across all fields when filtering with a string', function() {
  16521. var searchText = element(by.model('searchText'));
  16522. searchText.clear();
  16523. searchText.sendKeys('m');
  16524. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  16525. searchText.clear();
  16526. searchText.sendKeys('76');
  16527. expectFriendNames(['John', 'Julie'], 'friend');
  16528. });
  16529. it('should search in specific fields when filtering with a predicate object', function() {
  16530. var searchAny = element(by.model('search.$'));
  16531. searchAny.clear();
  16532. searchAny.sendKeys('i');
  16533. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  16534. });
  16535. it('should use a equal comparison when comparator is true', function() {
  16536. var searchName = element(by.model('search.name'));
  16537. var strict = element(by.model('strict'));
  16538. searchName.clear();
  16539. searchName.sendKeys('Julie');
  16540. strict.click();
  16541. expectFriendNames(['Julie'], 'friendObj');
  16542. });
  16543. </file>
  16544. </example>
  16545. */
  16546. function filterFilter() {
  16547. return function(array, expression, comparator) {
  16548. if (!isArrayLike(array)) {
  16549. if (array == null) {
  16550. return array;
  16551. } else {
  16552. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  16553. }
  16554. }
  16555. var expressionType = getTypeForFilter(expression);
  16556. var predicateFn;
  16557. var matchAgainstAnyProp;
  16558. switch (expressionType) {
  16559. case 'function':
  16560. predicateFn = expression;
  16561. break;
  16562. case 'boolean':
  16563. case 'null':
  16564. case 'number':
  16565. case 'string':
  16566. matchAgainstAnyProp = true;
  16567. //jshint -W086
  16568. case 'object':
  16569. //jshint +W086
  16570. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  16571. break;
  16572. default:
  16573. return array;
  16574. }
  16575. return Array.prototype.filter.call(array, predicateFn);
  16576. };
  16577. }
  16578. // Helper functions for `filterFilter`
  16579. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  16580. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  16581. var predicateFn;
  16582. if (comparator === true) {
  16583. comparator = equals;
  16584. } else if (!isFunction(comparator)) {
  16585. comparator = function(actual, expected) {
  16586. if (isUndefined(actual)) {
  16587. // No substring matching against `undefined`
  16588. return false;
  16589. }
  16590. if ((actual === null) || (expected === null)) {
  16591. // No substring matching against `null`; only match against `null`
  16592. return actual === expected;
  16593. }
  16594. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  16595. // Should not compare primitives against objects, unless they have custom `toString` method
  16596. return false;
  16597. }
  16598. actual = lowercase('' + actual);
  16599. expected = lowercase('' + expected);
  16600. return actual.indexOf(expected) !== -1;
  16601. };
  16602. }
  16603. predicateFn = function(item) {
  16604. if (shouldMatchPrimitives && !isObject(item)) {
  16605. return deepCompare(item, expression.$, comparator, false);
  16606. }
  16607. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  16608. };
  16609. return predicateFn;
  16610. }
  16611. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  16612. var actualType = getTypeForFilter(actual);
  16613. var expectedType = getTypeForFilter(expected);
  16614. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  16615. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  16616. } else if (isArray(actual)) {
  16617. // In case `actual` is an array, consider it a match
  16618. // if ANY of it's items matches `expected`
  16619. return actual.some(function(item) {
  16620. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  16621. });
  16622. }
  16623. switch (actualType) {
  16624. case 'object':
  16625. var key;
  16626. if (matchAgainstAnyProp) {
  16627. for (key in actual) {
  16628. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  16629. return true;
  16630. }
  16631. }
  16632. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  16633. } else if (expectedType === 'object') {
  16634. for (key in expected) {
  16635. var expectedVal = expected[key];
  16636. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  16637. continue;
  16638. }
  16639. var matchAnyProperty = key === '$';
  16640. var actualVal = matchAnyProperty ? actual : actual[key];
  16641. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  16642. return false;
  16643. }
  16644. }
  16645. return true;
  16646. } else {
  16647. return comparator(actual, expected);
  16648. }
  16649. break;
  16650. case 'function':
  16651. return false;
  16652. default:
  16653. return comparator(actual, expected);
  16654. }
  16655. }
  16656. // Used for easily differentiating between `null` and actual `object`
  16657. function getTypeForFilter(val) {
  16658. return (val === null) ? 'null' : typeof val;
  16659. }
  16660. /**
  16661. * @ngdoc filter
  16662. * @name currency
  16663. * @kind function
  16664. *
  16665. * @description
  16666. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  16667. * symbol for current locale is used.
  16668. *
  16669. * @param {number} amount Input to filter.
  16670. * @param {string=} symbol Currency symbol or identifier to be displayed.
  16671. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  16672. * @returns {string} Formatted number.
  16673. *
  16674. *
  16675. * @example
  16676. <example module="currencyExample">
  16677. <file name="index.html">
  16678. <script>
  16679. angular.module('currencyExample', [])
  16680. .controller('ExampleController', ['$scope', function($scope) {
  16681. $scope.amount = 1234.56;
  16682. }]);
  16683. </script>
  16684. <div ng-controller="ExampleController">
  16685. <input type="number" ng-model="amount" aria-label="amount"> <br>
  16686. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  16687. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  16688. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  16689. </div>
  16690. </file>
  16691. <file name="protractor.js" type="protractor">
  16692. it('should init with 1234.56', function() {
  16693. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  16694. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  16695. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  16696. });
  16697. it('should update', function() {
  16698. if (browser.params.browser == 'safari') {
  16699. // Safari does not understand the minus key. See
  16700. // https://github.com/angular/protractor/issues/481
  16701. return;
  16702. }
  16703. element(by.model('amount')).clear();
  16704. element(by.model('amount')).sendKeys('-1234');
  16705. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  16706. expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
  16707. expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
  16708. });
  16709. </file>
  16710. </example>
  16711. */
  16712. currencyFilter.$inject = ['$locale'];
  16713. function currencyFilter($locale) {
  16714. var formats = $locale.NUMBER_FORMATS;
  16715. return function(amount, currencySymbol, fractionSize) {
  16716. if (isUndefined(currencySymbol)) {
  16717. currencySymbol = formats.CURRENCY_SYM;
  16718. }
  16719. if (isUndefined(fractionSize)) {
  16720. fractionSize = formats.PATTERNS[1].maxFrac;
  16721. }
  16722. // if null or undefined pass it through
  16723. return (amount == null)
  16724. ? amount
  16725. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  16726. replace(/\u00A4/g, currencySymbol);
  16727. };
  16728. }
  16729. /**
  16730. * @ngdoc filter
  16731. * @name number
  16732. * @kind function
  16733. *
  16734. * @description
  16735. * Formats a number as text.
  16736. *
  16737. * If the input is null or undefined, it will just be returned.
  16738. * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
  16739. * If the input is not a number an empty string is returned.
  16740. *
  16741. *
  16742. * @param {number|string} number Number to format.
  16743. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  16744. * If this is not provided then the fraction size is computed from the current locale's number
  16745. * formatting pattern. In the case of the default locale, it will be 3.
  16746. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  16747. *
  16748. * @example
  16749. <example module="numberFilterExample">
  16750. <file name="index.html">
  16751. <script>
  16752. angular.module('numberFilterExample', [])
  16753. .controller('ExampleController', ['$scope', function($scope) {
  16754. $scope.val = 1234.56789;
  16755. }]);
  16756. </script>
  16757. <div ng-controller="ExampleController">
  16758. <label>Enter number: <input ng-model='val'></label><br>
  16759. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  16760. No fractions: <span>{{val | number:0}}</span><br>
  16761. Negative number: <span>{{-val | number:4}}</span>
  16762. </div>
  16763. </file>
  16764. <file name="protractor.js" type="protractor">
  16765. it('should format numbers', function() {
  16766. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  16767. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  16768. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  16769. });
  16770. it('should update', function() {
  16771. element(by.model('val')).clear();
  16772. element(by.model('val')).sendKeys('3374.333');
  16773. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  16774. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  16775. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  16776. });
  16777. </file>
  16778. </example>
  16779. */
  16780. numberFilter.$inject = ['$locale'];
  16781. function numberFilter($locale) {
  16782. var formats = $locale.NUMBER_FORMATS;
  16783. return function(number, fractionSize) {
  16784. // if null or undefined pass it through
  16785. return (number == null)
  16786. ? number
  16787. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  16788. fractionSize);
  16789. };
  16790. }
  16791. var DECIMAL_SEP = '.';
  16792. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  16793. if (isObject(number)) return '';
  16794. var isNegative = number < 0;
  16795. number = Math.abs(number);
  16796. var isInfinity = number === Infinity;
  16797. if (!isInfinity && !isFinite(number)) return '';
  16798. var numStr = number + '',
  16799. formatedText = '',
  16800. hasExponent = false,
  16801. parts = [];
  16802. if (isInfinity) formatedText = '\u221e';
  16803. if (!isInfinity && numStr.indexOf('e') !== -1) {
  16804. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  16805. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  16806. number = 0;
  16807. } else {
  16808. formatedText = numStr;
  16809. hasExponent = true;
  16810. }
  16811. }
  16812. if (!isInfinity && !hasExponent) {
  16813. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  16814. // determine fractionSize if it is not specified
  16815. if (isUndefined(fractionSize)) {
  16816. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  16817. }
  16818. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  16819. // inspired by:
  16820. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  16821. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  16822. var fraction = ('' + number).split(DECIMAL_SEP);
  16823. var whole = fraction[0];
  16824. fraction = fraction[1] || '';
  16825. var i, pos = 0,
  16826. lgroup = pattern.lgSize,
  16827. group = pattern.gSize;
  16828. if (whole.length >= (lgroup + group)) {
  16829. pos = whole.length - lgroup;
  16830. for (i = 0; i < pos; i++) {
  16831. if ((pos - i) % group === 0 && i !== 0) {
  16832. formatedText += groupSep;
  16833. }
  16834. formatedText += whole.charAt(i);
  16835. }
  16836. }
  16837. for (i = pos; i < whole.length; i++) {
  16838. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  16839. formatedText += groupSep;
  16840. }
  16841. formatedText += whole.charAt(i);
  16842. }
  16843. // format fraction part.
  16844. while (fraction.length < fractionSize) {
  16845. fraction += '0';
  16846. }
  16847. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  16848. } else {
  16849. if (fractionSize > 0 && number < 1) {
  16850. formatedText = number.toFixed(fractionSize);
  16851. number = parseFloat(formatedText);
  16852. }
  16853. }
  16854. if (number === 0) {
  16855. isNegative = false;
  16856. }
  16857. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  16858. formatedText,
  16859. isNegative ? pattern.negSuf : pattern.posSuf);
  16860. return parts.join('');
  16861. }
  16862. function padNumber(num, digits, trim) {
  16863. var neg = '';
  16864. if (num < 0) {
  16865. neg = '-';
  16866. num = -num;
  16867. }
  16868. num = '' + num;
  16869. while (num.length < digits) num = '0' + num;
  16870. if (trim) {
  16871. num = num.substr(num.length - digits);
  16872. }
  16873. return neg + num;
  16874. }
  16875. function dateGetter(name, size, offset, trim) {
  16876. offset = offset || 0;
  16877. return function(date) {
  16878. var value = date['get' + name]();
  16879. if (offset > 0 || value > -offset) {
  16880. value += offset;
  16881. }
  16882. if (value === 0 && offset == -12) value = 12;
  16883. return padNumber(value, size, trim);
  16884. };
  16885. }
  16886. function dateStrGetter(name, shortForm) {
  16887. return function(date, formats) {
  16888. var value = date['get' + name]();
  16889. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  16890. return formats[get][value];
  16891. };
  16892. }
  16893. function timeZoneGetter(date, formats, offset) {
  16894. var zone = -1 * offset;
  16895. var paddedZone = (zone >= 0) ? "+" : "";
  16896. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  16897. padNumber(Math.abs(zone % 60), 2);
  16898. return paddedZone;
  16899. }
  16900. function getFirstThursdayOfYear(year) {
  16901. // 0 = index of January
  16902. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  16903. // 4 = index of Thursday (+1 to account for 1st = 5)
  16904. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  16905. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  16906. }
  16907. function getThursdayThisWeek(datetime) {
  16908. return new Date(datetime.getFullYear(), datetime.getMonth(),
  16909. // 4 = index of Thursday
  16910. datetime.getDate() + (4 - datetime.getDay()));
  16911. }
  16912. function weekGetter(size) {
  16913. return function(date) {
  16914. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  16915. thisThurs = getThursdayThisWeek(date);
  16916. var diff = +thisThurs - +firstThurs,
  16917. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  16918. return padNumber(result, size);
  16919. };
  16920. }
  16921. function ampmGetter(date, formats) {
  16922. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  16923. }
  16924. function eraGetter(date, formats) {
  16925. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  16926. }
  16927. function longEraGetter(date, formats) {
  16928. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  16929. }
  16930. var DATE_FORMATS = {
  16931. yyyy: dateGetter('FullYear', 4),
  16932. yy: dateGetter('FullYear', 2, 0, true),
  16933. y: dateGetter('FullYear', 1),
  16934. MMMM: dateStrGetter('Month'),
  16935. MMM: dateStrGetter('Month', true),
  16936. MM: dateGetter('Month', 2, 1),
  16937. M: dateGetter('Month', 1, 1),
  16938. dd: dateGetter('Date', 2),
  16939. d: dateGetter('Date', 1),
  16940. HH: dateGetter('Hours', 2),
  16941. H: dateGetter('Hours', 1),
  16942. hh: dateGetter('Hours', 2, -12),
  16943. h: dateGetter('Hours', 1, -12),
  16944. mm: dateGetter('Minutes', 2),
  16945. m: dateGetter('Minutes', 1),
  16946. ss: dateGetter('Seconds', 2),
  16947. s: dateGetter('Seconds', 1),
  16948. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  16949. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  16950. sss: dateGetter('Milliseconds', 3),
  16951. EEEE: dateStrGetter('Day'),
  16952. EEE: dateStrGetter('Day', true),
  16953. a: ampmGetter,
  16954. Z: timeZoneGetter,
  16955. ww: weekGetter(2),
  16956. w: weekGetter(1),
  16957. G: eraGetter,
  16958. GG: eraGetter,
  16959. GGG: eraGetter,
  16960. GGGG: longEraGetter
  16961. };
  16962. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  16963. NUMBER_STRING = /^\-?\d+$/;
  16964. /**
  16965. * @ngdoc filter
  16966. * @name date
  16967. * @kind function
  16968. *
  16969. * @description
  16970. * Formats `date` to a string based on the requested `format`.
  16971. *
  16972. * `format` string can be composed of the following elements:
  16973. *
  16974. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  16975. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  16976. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  16977. * * `'MMMM'`: Month in year (January-December)
  16978. * * `'MMM'`: Month in year (Jan-Dec)
  16979. * * `'MM'`: Month in year, padded (01-12)
  16980. * * `'M'`: Month in year (1-12)
  16981. * * `'dd'`: Day in month, padded (01-31)
  16982. * * `'d'`: Day in month (1-31)
  16983. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  16984. * * `'EEE'`: Day in Week, (Sun-Sat)
  16985. * * `'HH'`: Hour in day, padded (00-23)
  16986. * * `'H'`: Hour in day (0-23)
  16987. * * `'hh'`: Hour in AM/PM, padded (01-12)
  16988. * * `'h'`: Hour in AM/PM, (1-12)
  16989. * * `'mm'`: Minute in hour, padded (00-59)
  16990. * * `'m'`: Minute in hour (0-59)
  16991. * * `'ss'`: Second in minute, padded (00-59)
  16992. * * `'s'`: Second in minute (0-59)
  16993. * * `'sss'`: Millisecond in second, padded (000-999)
  16994. * * `'a'`: AM/PM marker
  16995. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  16996. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  16997. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  16998. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  16999. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  17000. *
  17001. * `format` string can also be one of the following predefined
  17002. * {@link guide/i18n localizable formats}:
  17003. *
  17004. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  17005. * (e.g. Sep 3, 2010 12:05:08 PM)
  17006. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  17007. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  17008. * (e.g. Friday, September 3, 2010)
  17009. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  17010. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  17011. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  17012. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  17013. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  17014. *
  17015. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  17016. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  17017. * (e.g. `"h 'o''clock'"`).
  17018. *
  17019. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  17020. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  17021. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  17022. * specified in the string input, the time is considered to be in the local timezone.
  17023. * @param {string=} format Formatting rules (see Description). If not specified,
  17024. * `mediumDate` is used.
  17025. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  17026. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  17027. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  17028. * If not specified, the timezone of the browser will be used.
  17029. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  17030. *
  17031. * @example
  17032. <example>
  17033. <file name="index.html">
  17034. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  17035. <span>{{1288323623006 | date:'medium'}}</span><br>
  17036. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  17037. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  17038. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  17039. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  17040. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  17041. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  17042. </file>
  17043. <file name="protractor.js" type="protractor">
  17044. it('should format date', function() {
  17045. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  17046. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  17047. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  17048. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  17049. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  17050. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  17051. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  17052. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  17053. });
  17054. </file>
  17055. </example>
  17056. */
  17057. dateFilter.$inject = ['$locale'];
  17058. function dateFilter($locale) {
  17059. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  17060. // 1 2 3 4 5 6 7 8 9 10 11
  17061. function jsonStringToDate(string) {
  17062. var match;
  17063. if (match = string.match(R_ISO8601_STR)) {
  17064. var date = new Date(0),
  17065. tzHour = 0,
  17066. tzMin = 0,
  17067. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  17068. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  17069. if (match[9]) {
  17070. tzHour = toInt(match[9] + match[10]);
  17071. tzMin = toInt(match[9] + match[11]);
  17072. }
  17073. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  17074. var h = toInt(match[4] || 0) - tzHour;
  17075. var m = toInt(match[5] || 0) - tzMin;
  17076. var s = toInt(match[6] || 0);
  17077. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  17078. timeSetter.call(date, h, m, s, ms);
  17079. return date;
  17080. }
  17081. return string;
  17082. }
  17083. return function(date, format, timezone) {
  17084. var text = '',
  17085. parts = [],
  17086. fn, match;
  17087. format = format || 'mediumDate';
  17088. format = $locale.DATETIME_FORMATS[format] || format;
  17089. if (isString(date)) {
  17090. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  17091. }
  17092. if (isNumber(date)) {
  17093. date = new Date(date);
  17094. }
  17095. if (!isDate(date) || !isFinite(date.getTime())) {
  17096. return date;
  17097. }
  17098. while (format) {
  17099. match = DATE_FORMATS_SPLIT.exec(format);
  17100. if (match) {
  17101. parts = concat(parts, match, 1);
  17102. format = parts.pop();
  17103. } else {
  17104. parts.push(format);
  17105. format = null;
  17106. }
  17107. }
  17108. var dateTimezoneOffset = date.getTimezoneOffset();
  17109. if (timezone) {
  17110. dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  17111. date = convertTimezoneToLocal(date, timezone, true);
  17112. }
  17113. forEach(parts, function(value) {
  17114. fn = DATE_FORMATS[value];
  17115. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  17116. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  17117. });
  17118. return text;
  17119. };
  17120. }
  17121. /**
  17122. * @ngdoc filter
  17123. * @name json
  17124. * @kind function
  17125. *
  17126. * @description
  17127. * Allows you to convert a JavaScript object into JSON string.
  17128. *
  17129. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  17130. * the binding is automatically converted to JSON.
  17131. *
  17132. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  17133. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  17134. * @returns {string} JSON string.
  17135. *
  17136. *
  17137. * @example
  17138. <example>
  17139. <file name="index.html">
  17140. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  17141. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  17142. </file>
  17143. <file name="protractor.js" type="protractor">
  17144. it('should jsonify filtered objects', function() {
  17145. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17146. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17147. });
  17148. </file>
  17149. </example>
  17150. *
  17151. */
  17152. function jsonFilter() {
  17153. return function(object, spacing) {
  17154. if (isUndefined(spacing)) {
  17155. spacing = 2;
  17156. }
  17157. return toJson(object, spacing);
  17158. };
  17159. }
  17160. /**
  17161. * @ngdoc filter
  17162. * @name lowercase
  17163. * @kind function
  17164. * @description
  17165. * Converts string to lowercase.
  17166. * @see angular.lowercase
  17167. */
  17168. var lowercaseFilter = valueFn(lowercase);
  17169. /**
  17170. * @ngdoc filter
  17171. * @name uppercase
  17172. * @kind function
  17173. * @description
  17174. * Converts string to uppercase.
  17175. * @see angular.uppercase
  17176. */
  17177. var uppercaseFilter = valueFn(uppercase);
  17178. /**
  17179. * @ngdoc filter
  17180. * @name limitTo
  17181. * @kind function
  17182. *
  17183. * @description
  17184. * Creates a new array or string containing only a specified number of elements. The elements
  17185. * are taken from either the beginning or the end of the source array, string or number, as specified by
  17186. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  17187. * converted to a string.
  17188. *
  17189. * @param {Array|string|number} input Source array, string or number to be limited.
  17190. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  17191. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  17192. * If the number is negative, `limit` number of items from the end of the source array/string
  17193. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  17194. * the input will be returned unchanged.
  17195. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  17196. * indicates an offset from the end of `input`. Defaults to `0`.
  17197. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  17198. * had less than `limit` elements.
  17199. *
  17200. * @example
  17201. <example module="limitToExample">
  17202. <file name="index.html">
  17203. <script>
  17204. angular.module('limitToExample', [])
  17205. .controller('ExampleController', ['$scope', function($scope) {
  17206. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  17207. $scope.letters = "abcdefghi";
  17208. $scope.longNumber = 2345432342;
  17209. $scope.numLimit = 3;
  17210. $scope.letterLimit = 3;
  17211. $scope.longNumberLimit = 3;
  17212. }]);
  17213. </script>
  17214. <div ng-controller="ExampleController">
  17215. <label>
  17216. Limit {{numbers}} to:
  17217. <input type="number" step="1" ng-model="numLimit">
  17218. </label>
  17219. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  17220. <label>
  17221. Limit {{letters}} to:
  17222. <input type="number" step="1" ng-model="letterLimit">
  17223. </label>
  17224. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  17225. <label>
  17226. Limit {{longNumber}} to:
  17227. <input type="number" step="1" ng-model="longNumberLimit">
  17228. </label>
  17229. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  17230. </div>
  17231. </file>
  17232. <file name="protractor.js" type="protractor">
  17233. var numLimitInput = element(by.model('numLimit'));
  17234. var letterLimitInput = element(by.model('letterLimit'));
  17235. var longNumberLimitInput = element(by.model('longNumberLimit'));
  17236. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  17237. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  17238. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  17239. it('should limit the number array to first three items', function() {
  17240. expect(numLimitInput.getAttribute('value')).toBe('3');
  17241. expect(letterLimitInput.getAttribute('value')).toBe('3');
  17242. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  17243. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  17244. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  17245. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  17246. });
  17247. // There is a bug in safari and protractor that doesn't like the minus key
  17248. // it('should update the output when -3 is entered', function() {
  17249. // numLimitInput.clear();
  17250. // numLimitInput.sendKeys('-3');
  17251. // letterLimitInput.clear();
  17252. // letterLimitInput.sendKeys('-3');
  17253. // longNumberLimitInput.clear();
  17254. // longNumberLimitInput.sendKeys('-3');
  17255. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  17256. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  17257. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  17258. // });
  17259. it('should not exceed the maximum size of input array', function() {
  17260. numLimitInput.clear();
  17261. numLimitInput.sendKeys('100');
  17262. letterLimitInput.clear();
  17263. letterLimitInput.sendKeys('100');
  17264. longNumberLimitInput.clear();
  17265. longNumberLimitInput.sendKeys('100');
  17266. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  17267. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  17268. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  17269. });
  17270. </file>
  17271. </example>
  17272. */
  17273. function limitToFilter() {
  17274. return function(input, limit, begin) {
  17275. if (Math.abs(Number(limit)) === Infinity) {
  17276. limit = Number(limit);
  17277. } else {
  17278. limit = toInt(limit);
  17279. }
  17280. if (isNaN(limit)) return input;
  17281. if (isNumber(input)) input = input.toString();
  17282. if (!isArray(input) && !isString(input)) return input;
  17283. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  17284. begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;
  17285. if (limit >= 0) {
  17286. return input.slice(begin, begin + limit);
  17287. } else {
  17288. if (begin === 0) {
  17289. return input.slice(limit, input.length);
  17290. } else {
  17291. return input.slice(Math.max(0, begin + limit), begin);
  17292. }
  17293. }
  17294. };
  17295. }
  17296. /**
  17297. * @ngdoc filter
  17298. * @name orderBy
  17299. * @kind function
  17300. *
  17301. * @description
  17302. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  17303. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  17304. * as expected, make sure they are actually being saved as numbers and not strings.
  17305. *
  17306. * @param {Array} array The array to sort.
  17307. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  17308. * used by the comparator to determine the order of elements.
  17309. *
  17310. * Can be one of:
  17311. *
  17312. * - `function`: Getter function. The result of this function will be sorted using the
  17313. * `<`, `===`, `>` operator.
  17314. * - `string`: An Angular expression. The result of this expression is used to compare elements
  17315. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  17316. * 3 first characters of a property called `name`). The result of a constant expression
  17317. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  17318. * to sort object by the value of their `special name` property). An expression can be
  17319. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  17320. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  17321. * element itself is used to compare where sorting.
  17322. * - `Array`: An array of function or string predicates. The first predicate in the array
  17323. * is used for sorting, but when two items are equivalent, the next predicate is used.
  17324. *
  17325. * If the predicate is missing or empty then it defaults to `'+'`.
  17326. *
  17327. * @param {boolean=} reverse Reverse the order of the array.
  17328. * @returns {Array} Sorted copy of the source array.
  17329. *
  17330. *
  17331. * @example
  17332. * The example below demonstrates a simple ngRepeat, where the data is sorted
  17333. * by age in descending order (predicate is set to `'-age'`).
  17334. * `reverse` is not set, which means it defaults to `false`.
  17335. <example module="orderByExample">
  17336. <file name="index.html">
  17337. <script>
  17338. angular.module('orderByExample', [])
  17339. .controller('ExampleController', ['$scope', function($scope) {
  17340. $scope.friends =
  17341. [{name:'John', phone:'555-1212', age:10},
  17342. {name:'Mary', phone:'555-9876', age:19},
  17343. {name:'Mike', phone:'555-4321', age:21},
  17344. {name:'Adam', phone:'555-5678', age:35},
  17345. {name:'Julie', phone:'555-8765', age:29}];
  17346. }]);
  17347. </script>
  17348. <div ng-controller="ExampleController">
  17349. <table class="friend">
  17350. <tr>
  17351. <th>Name</th>
  17352. <th>Phone Number</th>
  17353. <th>Age</th>
  17354. </tr>
  17355. <tr ng-repeat="friend in friends | orderBy:'-age'">
  17356. <td>{{friend.name}}</td>
  17357. <td>{{friend.phone}}</td>
  17358. <td>{{friend.age}}</td>
  17359. </tr>
  17360. </table>
  17361. </div>
  17362. </file>
  17363. </example>
  17364. *
  17365. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  17366. * as shown in the next example.
  17367. * @example
  17368. <example module="orderByExample">
  17369. <file name="index.html">
  17370. <script>
  17371. angular.module('orderByExample', [])
  17372. .controller('ExampleController', ['$scope', function($scope) {
  17373. $scope.friends =
  17374. [{name:'John', phone:'555-1212', age:10},
  17375. {name:'Mary', phone:'555-9876', age:19},
  17376. {name:'Mike', phone:'555-4321', age:21},
  17377. {name:'Adam', phone:'555-5678', age:35},
  17378. {name:'Julie', phone:'555-8765', age:29}];
  17379. $scope.predicate = 'age';
  17380. $scope.reverse = true;
  17381. $scope.order = function(predicate) {
  17382. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  17383. $scope.predicate = predicate;
  17384. };
  17385. }]);
  17386. </script>
  17387. <style type="text/css">
  17388. .sortorder:after {
  17389. content: '\25b2';
  17390. }
  17391. .sortorder.reverse:after {
  17392. content: '\25bc';
  17393. }
  17394. </style>
  17395. <div ng-controller="ExampleController">
  17396. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  17397. <hr/>
  17398. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  17399. <table class="friend">
  17400. <tr>
  17401. <th>
  17402. <a href="" ng-click="order('name')">Name</a>
  17403. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  17404. </th>
  17405. <th>
  17406. <a href="" ng-click="order('phone')">Phone Number</a>
  17407. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  17408. </th>
  17409. <th>
  17410. <a href="" ng-click="order('age')">Age</a>
  17411. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  17412. </th>
  17413. </tr>
  17414. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  17415. <td>{{friend.name}}</td>
  17416. <td>{{friend.phone}}</td>
  17417. <td>{{friend.age}}</td>
  17418. </tr>
  17419. </table>
  17420. </div>
  17421. </file>
  17422. </example>
  17423. *
  17424. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  17425. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  17426. * desired parameters.
  17427. *
  17428. * Example:
  17429. *
  17430. * @example
  17431. <example module="orderByExample">
  17432. <file name="index.html">
  17433. <div ng-controller="ExampleController">
  17434. <table class="friend">
  17435. <tr>
  17436. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  17437. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  17438. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  17439. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  17440. </tr>
  17441. <tr ng-repeat="friend in friends">
  17442. <td>{{friend.name}}</td>
  17443. <td>{{friend.phone}}</td>
  17444. <td>{{friend.age}}</td>
  17445. </tr>
  17446. </table>
  17447. </div>
  17448. </file>
  17449. <file name="script.js">
  17450. angular.module('orderByExample', [])
  17451. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  17452. var orderBy = $filter('orderBy');
  17453. $scope.friends = [
  17454. { name: 'John', phone: '555-1212', age: 10 },
  17455. { name: 'Mary', phone: '555-9876', age: 19 },
  17456. { name: 'Mike', phone: '555-4321', age: 21 },
  17457. { name: 'Adam', phone: '555-5678', age: 35 },
  17458. { name: 'Julie', phone: '555-8765', age: 29 }
  17459. ];
  17460. $scope.order = function(predicate, reverse) {
  17461. $scope.friends = orderBy($scope.friends, predicate, reverse);
  17462. };
  17463. $scope.order('-age',false);
  17464. }]);
  17465. </file>
  17466. </example>
  17467. */
  17468. orderByFilter.$inject = ['$parse'];
  17469. function orderByFilter($parse) {
  17470. return function(array, sortPredicate, reverseOrder) {
  17471. if (!(isArrayLike(array))) return array;
  17472. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  17473. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  17474. var predicates = processPredicates(sortPredicate, reverseOrder);
  17475. // The next three lines are a version of a Swartzian Transform idiom from Perl
  17476. // (sometimes called the Decorate-Sort-Undecorate idiom)
  17477. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  17478. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  17479. compareValues.sort(doComparison);
  17480. array = compareValues.map(function(item) { return item.value; });
  17481. return array;
  17482. function getComparisonObject(value, index) {
  17483. return {
  17484. value: value,
  17485. predicateValues: predicates.map(function(predicate) {
  17486. return getPredicateValue(predicate.get(value), index);
  17487. })
  17488. };
  17489. }
  17490. function doComparison(v1, v2) {
  17491. var result = 0;
  17492. for (var index=0, length = predicates.length; index < length; ++index) {
  17493. result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
  17494. if (result) break;
  17495. }
  17496. return result;
  17497. }
  17498. };
  17499. function processPredicates(sortPredicate, reverseOrder) {
  17500. reverseOrder = reverseOrder ? -1 : 1;
  17501. return sortPredicate.map(function(predicate) {
  17502. var descending = 1, get = identity;
  17503. if (isFunction(predicate)) {
  17504. get = predicate;
  17505. } else if (isString(predicate)) {
  17506. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  17507. descending = predicate.charAt(0) == '-' ? -1 : 1;
  17508. predicate = predicate.substring(1);
  17509. }
  17510. if (predicate !== '') {
  17511. get = $parse(predicate);
  17512. if (get.constant) {
  17513. var key = get();
  17514. get = function(value) { return value[key]; };
  17515. }
  17516. }
  17517. }
  17518. return { get: get, descending: descending * reverseOrder };
  17519. });
  17520. }
  17521. function isPrimitive(value) {
  17522. switch (typeof value) {
  17523. case 'number': /* falls through */
  17524. case 'boolean': /* falls through */
  17525. case 'string':
  17526. return true;
  17527. default:
  17528. return false;
  17529. }
  17530. }
  17531. function objectValue(value, index) {
  17532. // If `valueOf` is a valid function use that
  17533. if (typeof value.valueOf === 'function') {
  17534. value = value.valueOf();
  17535. if (isPrimitive(value)) return value;
  17536. }
  17537. // If `toString` is a valid function and not the one from `Object.prototype` use that
  17538. if (hasCustomToString(value)) {
  17539. value = value.toString();
  17540. if (isPrimitive(value)) return value;
  17541. }
  17542. // We have a basic object so we use the position of the object in the collection
  17543. return index;
  17544. }
  17545. function getPredicateValue(value, index) {
  17546. var type = typeof value;
  17547. if (value === null) {
  17548. type = 'string';
  17549. value = 'null';
  17550. } else if (type === 'string') {
  17551. value = value.toLowerCase();
  17552. } else if (type === 'object') {
  17553. value = objectValue(value, index);
  17554. }
  17555. return { value: value, type: type };
  17556. }
  17557. function compare(v1, v2) {
  17558. var result = 0;
  17559. if (v1.type === v2.type) {
  17560. if (v1.value !== v2.value) {
  17561. result = v1.value < v2.value ? -1 : 1;
  17562. }
  17563. } else {
  17564. result = v1.type < v2.type ? -1 : 1;
  17565. }
  17566. return result;
  17567. }
  17568. }
  17569. function ngDirective(directive) {
  17570. if (isFunction(directive)) {
  17571. directive = {
  17572. link: directive
  17573. };
  17574. }
  17575. directive.restrict = directive.restrict || 'AC';
  17576. return valueFn(directive);
  17577. }
  17578. /**
  17579. * @ngdoc directive
  17580. * @name a
  17581. * @restrict E
  17582. *
  17583. * @description
  17584. * Modifies the default behavior of the html A tag so that the default action is prevented when
  17585. * the href attribute is empty.
  17586. *
  17587. * This change permits the easy creation of action links with the `ngClick` directive
  17588. * without changing the location or causing page reloads, e.g.:
  17589. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  17590. */
  17591. var htmlAnchorDirective = valueFn({
  17592. restrict: 'E',
  17593. compile: function(element, attr) {
  17594. if (!attr.href && !attr.xlinkHref) {
  17595. return function(scope, element) {
  17596. // If the linked element is not an anchor tag anymore, do nothing
  17597. if (element[0].nodeName.toLowerCase() !== 'a') return;
  17598. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  17599. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  17600. 'xlink:href' : 'href';
  17601. element.on('click', function(event) {
  17602. // if we have no href url, then don't navigate anywhere.
  17603. if (!element.attr(href)) {
  17604. event.preventDefault();
  17605. }
  17606. });
  17607. };
  17608. }
  17609. }
  17610. });
  17611. /**
  17612. * @ngdoc directive
  17613. * @name ngHref
  17614. * @restrict A
  17615. * @priority 99
  17616. *
  17617. * @description
  17618. * Using Angular markup like `{{hash}}` in an href attribute will
  17619. * make the link go to the wrong URL if the user clicks it before
  17620. * Angular has a chance to replace the `{{hash}}` markup with its
  17621. * value. Until Angular replaces the markup the link will be broken
  17622. * and will most likely return a 404 error. The `ngHref` directive
  17623. * solves this problem.
  17624. *
  17625. * The wrong way to write it:
  17626. * ```html
  17627. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17628. * ```
  17629. *
  17630. * The correct way to write it:
  17631. * ```html
  17632. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17633. * ```
  17634. *
  17635. * @element A
  17636. * @param {template} ngHref any string which can contain `{{}}` markup.
  17637. *
  17638. * @example
  17639. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  17640. * in links and their different behaviors:
  17641. <example>
  17642. <file name="index.html">
  17643. <input ng-model="value" /><br />
  17644. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  17645. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  17646. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  17647. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  17648. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  17649. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  17650. </file>
  17651. <file name="protractor.js" type="protractor">
  17652. it('should execute ng-click but not reload when href without value', function() {
  17653. element(by.id('link-1')).click();
  17654. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  17655. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  17656. });
  17657. it('should execute ng-click but not reload when href empty string', function() {
  17658. element(by.id('link-2')).click();
  17659. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  17660. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  17661. });
  17662. it('should execute ng-click and change url when ng-href specified', function() {
  17663. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  17664. element(by.id('link-3')).click();
  17665. // At this point, we navigate away from an Angular page, so we need
  17666. // to use browser.driver to get the base webdriver.
  17667. browser.wait(function() {
  17668. return browser.driver.getCurrentUrl().then(function(url) {
  17669. return url.match(/\/123$/);
  17670. });
  17671. }, 5000, 'page should navigate to /123');
  17672. });
  17673. it('should execute ng-click but not reload when href empty string and name specified', function() {
  17674. element(by.id('link-4')).click();
  17675. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  17676. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  17677. });
  17678. it('should execute ng-click but not reload when no href but name specified', function() {
  17679. element(by.id('link-5')).click();
  17680. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  17681. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  17682. });
  17683. it('should only change url when only ng-href', function() {
  17684. element(by.model('value')).clear();
  17685. element(by.model('value')).sendKeys('6');
  17686. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  17687. element(by.id('link-6')).click();
  17688. // At this point, we navigate away from an Angular page, so we need
  17689. // to use browser.driver to get the base webdriver.
  17690. browser.wait(function() {
  17691. return browser.driver.getCurrentUrl().then(function(url) {
  17692. return url.match(/\/6$/);
  17693. });
  17694. }, 5000, 'page should navigate to /6');
  17695. });
  17696. </file>
  17697. </example>
  17698. */
  17699. /**
  17700. * @ngdoc directive
  17701. * @name ngSrc
  17702. * @restrict A
  17703. * @priority 99
  17704. *
  17705. * @description
  17706. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  17707. * work right: The browser will fetch from the URL with the literal
  17708. * text `{{hash}}` until Angular replaces the expression inside
  17709. * `{{hash}}`. The `ngSrc` directive solves this problem.
  17710. *
  17711. * The buggy way to write it:
  17712. * ```html
  17713. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  17714. * ```
  17715. *
  17716. * The correct way to write it:
  17717. * ```html
  17718. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  17719. * ```
  17720. *
  17721. * @element IMG
  17722. * @param {template} ngSrc any string which can contain `{{}}` markup.
  17723. */
  17724. /**
  17725. * @ngdoc directive
  17726. * @name ngSrcset
  17727. * @restrict A
  17728. * @priority 99
  17729. *
  17730. * @description
  17731. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  17732. * work right: The browser will fetch from the URL with the literal
  17733. * text `{{hash}}` until Angular replaces the expression inside
  17734. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  17735. *
  17736. * The buggy way to write it:
  17737. * ```html
  17738. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  17739. * ```
  17740. *
  17741. * The correct way to write it:
  17742. * ```html
  17743. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  17744. * ```
  17745. *
  17746. * @element IMG
  17747. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  17748. */
  17749. /**
  17750. * @ngdoc directive
  17751. * @name ngDisabled
  17752. * @restrict A
  17753. * @priority 100
  17754. *
  17755. * @description
  17756. *
  17757. * This directive sets the `disabled` attribute on the element if the
  17758. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  17759. *
  17760. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  17761. * attribute. The following example would make the button enabled on Chrome/Firefox
  17762. * but not on older IEs:
  17763. *
  17764. * ```html
  17765. * <!-- See below for an example of ng-disabled being used correctly -->
  17766. * <div ng-init="isDisabled = false">
  17767. * <button disabled="{{isDisabled}}">Disabled</button>
  17768. * </div>
  17769. * ```
  17770. *
  17771. * This is because the HTML specification does not require browsers to preserve the values of
  17772. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  17773. * If we put an Angular interpolation expression into such an attribute then the
  17774. * binding information would be lost when the browser removes the attribute.
  17775. *
  17776. * @example
  17777. <example>
  17778. <file name="index.html">
  17779. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  17780. <button ng-model="button" ng-disabled="checked">Button</button>
  17781. </file>
  17782. <file name="protractor.js" type="protractor">
  17783. it('should toggle button', function() {
  17784. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  17785. element(by.model('checked')).click();
  17786. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  17787. });
  17788. </file>
  17789. </example>
  17790. *
  17791. * @element INPUT
  17792. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  17793. * then the `disabled` attribute will be set on the element
  17794. */
  17795. /**
  17796. * @ngdoc directive
  17797. * @name ngChecked
  17798. * @restrict A
  17799. * @priority 100
  17800. *
  17801. * @description
  17802. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  17803. *
  17804. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  17805. * as this can lead to unexpected behavior.
  17806. *
  17807. * ### Why do we need `ngChecked`?
  17808. *
  17809. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17810. * such as checked. (Their presence means true and their absence means false.)
  17811. * If we put an Angular interpolation expression into such an attribute then the
  17812. * binding information would be lost when the browser removes the attribute.
  17813. * The `ngChecked` directive solves this problem for the `checked` attribute.
  17814. * This complementary directive is not removed by the browser and so provides
  17815. * a permanent reliable place to store the binding information.
  17816. * @example
  17817. <example>
  17818. <file name="index.html">
  17819. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  17820. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  17821. </file>
  17822. <file name="protractor.js" type="protractor">
  17823. it('should check both checkBoxes', function() {
  17824. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  17825. element(by.model('master')).click();
  17826. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  17827. });
  17828. </file>
  17829. </example>
  17830. *
  17831. * @element INPUT
  17832. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  17833. * then the `checked` attribute will be set on the element
  17834. */
  17835. /**
  17836. * @ngdoc directive
  17837. * @name ngReadonly
  17838. * @restrict A
  17839. * @priority 100
  17840. *
  17841. * @description
  17842. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17843. * such as readonly. (Their presence means true and their absence means false.)
  17844. * If we put an Angular interpolation expression into such an attribute then the
  17845. * binding information would be lost when the browser removes the attribute.
  17846. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  17847. * This complementary directive is not removed by the browser and so provides
  17848. * a permanent reliable place to store the binding information.
  17849. * @example
  17850. <example>
  17851. <file name="index.html">
  17852. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  17853. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  17854. </file>
  17855. <file name="protractor.js" type="protractor">
  17856. it('should toggle readonly attr', function() {
  17857. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  17858. element(by.model('checked')).click();
  17859. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  17860. });
  17861. </file>
  17862. </example>
  17863. *
  17864. * @element INPUT
  17865. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  17866. * then special attribute "readonly" will be set on the element
  17867. */
  17868. /**
  17869. * @ngdoc directive
  17870. * @name ngSelected
  17871. * @restrict A
  17872. * @priority 100
  17873. *
  17874. * @description
  17875. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17876. * such as selected. (Their presence means true and their absence means false.)
  17877. * If we put an Angular interpolation expression into such an attribute then the
  17878. * binding information would be lost when the browser removes the attribute.
  17879. * The `ngSelected` directive solves this problem for the `selected` attribute.
  17880. * This complementary directive is not removed by the browser and so provides
  17881. * a permanent reliable place to store the binding information.
  17882. *
  17883. * @example
  17884. <example>
  17885. <file name="index.html">
  17886. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  17887. <select aria-label="ngSelected demo">
  17888. <option>Hello!</option>
  17889. <option id="greet" ng-selected="selected">Greetings!</option>
  17890. </select>
  17891. </file>
  17892. <file name="protractor.js" type="protractor">
  17893. it('should select Greetings!', function() {
  17894. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  17895. element(by.model('selected')).click();
  17896. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  17897. });
  17898. </file>
  17899. </example>
  17900. *
  17901. * @element OPTION
  17902. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  17903. * then special attribute "selected" will be set on the element
  17904. */
  17905. /**
  17906. * @ngdoc directive
  17907. * @name ngOpen
  17908. * @restrict A
  17909. * @priority 100
  17910. *
  17911. * @description
  17912. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17913. * such as open. (Their presence means true and their absence means false.)
  17914. * If we put an Angular interpolation expression into such an attribute then the
  17915. * binding information would be lost when the browser removes the attribute.
  17916. * The `ngOpen` directive solves this problem for the `open` attribute.
  17917. * This complementary directive is not removed by the browser and so provides
  17918. * a permanent reliable place to store the binding information.
  17919. * @example
  17920. <example>
  17921. <file name="index.html">
  17922. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  17923. <details id="details" ng-open="open">
  17924. <summary>Show/Hide me</summary>
  17925. </details>
  17926. </file>
  17927. <file name="protractor.js" type="protractor">
  17928. it('should toggle open', function() {
  17929. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  17930. element(by.model('open')).click();
  17931. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  17932. });
  17933. </file>
  17934. </example>
  17935. *
  17936. * @element DETAILS
  17937. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  17938. * then special attribute "open" will be set on the element
  17939. */
  17940. var ngAttributeAliasDirectives = {};
  17941. // boolean attrs are evaluated
  17942. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  17943. // binding to multiple is not supported
  17944. if (propName == "multiple") return;
  17945. function defaultLinkFn(scope, element, attr) {
  17946. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  17947. attr.$set(attrName, !!value);
  17948. });
  17949. }
  17950. var normalized = directiveNormalize('ng-' + attrName);
  17951. var linkFn = defaultLinkFn;
  17952. if (propName === 'checked') {
  17953. linkFn = function(scope, element, attr) {
  17954. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  17955. if (attr.ngModel !== attr[normalized]) {
  17956. defaultLinkFn(scope, element, attr);
  17957. }
  17958. };
  17959. }
  17960. ngAttributeAliasDirectives[normalized] = function() {
  17961. return {
  17962. restrict: 'A',
  17963. priority: 100,
  17964. link: linkFn
  17965. };
  17966. };
  17967. });
  17968. // aliased input attrs are evaluated
  17969. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  17970. ngAttributeAliasDirectives[ngAttr] = function() {
  17971. return {
  17972. priority: 100,
  17973. link: function(scope, element, attr) {
  17974. //special case ngPattern when a literal regular expression value
  17975. //is used as the expression (this way we don't have to watch anything).
  17976. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  17977. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  17978. if (match) {
  17979. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  17980. return;
  17981. }
  17982. }
  17983. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  17984. attr.$set(ngAttr, value);
  17985. });
  17986. }
  17987. };
  17988. };
  17989. });
  17990. // ng-src, ng-srcset, ng-href are interpolated
  17991. forEach(['src', 'srcset', 'href'], function(attrName) {
  17992. var normalized = directiveNormalize('ng-' + attrName);
  17993. ngAttributeAliasDirectives[normalized] = function() {
  17994. return {
  17995. priority: 99, // it needs to run after the attributes are interpolated
  17996. link: function(scope, element, attr) {
  17997. var propName = attrName,
  17998. name = attrName;
  17999. if (attrName === 'href' &&
  18000. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  18001. name = 'xlinkHref';
  18002. attr.$attr[name] = 'xlink:href';
  18003. propName = null;
  18004. }
  18005. attr.$observe(normalized, function(value) {
  18006. if (!value) {
  18007. if (attrName === 'href') {
  18008. attr.$set(name, null);
  18009. }
  18010. return;
  18011. }
  18012. attr.$set(name, value);
  18013. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  18014. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  18015. // to set the property as well to achieve the desired effect.
  18016. // we use attr[attrName] value since $set can sanitize the url.
  18017. if (msie && propName) element.prop(propName, attr[name]);
  18018. });
  18019. }
  18020. };
  18021. };
  18022. });
  18023. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  18024. */
  18025. var nullFormCtrl = {
  18026. $addControl: noop,
  18027. $$renameControl: nullFormRenameControl,
  18028. $removeControl: noop,
  18029. $setValidity: noop,
  18030. $setDirty: noop,
  18031. $setPristine: noop,
  18032. $setSubmitted: noop
  18033. },
  18034. SUBMITTED_CLASS = 'ng-submitted';
  18035. function nullFormRenameControl(control, name) {
  18036. control.$name = name;
  18037. }
  18038. /**
  18039. * @ngdoc type
  18040. * @name form.FormController
  18041. *
  18042. * @property {boolean} $pristine True if user has not interacted with the form yet.
  18043. * @property {boolean} $dirty True if user has already interacted with the form.
  18044. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  18045. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  18046. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  18047. *
  18048. * @property {Object} $error Is an object hash, containing references to controls or
  18049. * forms with failing validators, where:
  18050. *
  18051. * - keys are validation tokens (error names),
  18052. * - values are arrays of controls or forms that have a failing validator for given error name.
  18053. *
  18054. * Built-in validation tokens:
  18055. *
  18056. * - `email`
  18057. * - `max`
  18058. * - `maxlength`
  18059. * - `min`
  18060. * - `minlength`
  18061. * - `number`
  18062. * - `pattern`
  18063. * - `required`
  18064. * - `url`
  18065. * - `date`
  18066. * - `datetimelocal`
  18067. * - `time`
  18068. * - `week`
  18069. * - `month`
  18070. *
  18071. * @description
  18072. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  18073. * such as being valid/invalid or dirty/pristine.
  18074. *
  18075. * Each {@link ng.directive:form form} directive creates an instance
  18076. * of `FormController`.
  18077. *
  18078. */
  18079. //asks for $scope to fool the BC controller module
  18080. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  18081. function FormController(element, attrs, $scope, $animate, $interpolate) {
  18082. var form = this,
  18083. controls = [];
  18084. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  18085. // init state
  18086. form.$error = {};
  18087. form.$$success = {};
  18088. form.$pending = undefined;
  18089. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  18090. form.$dirty = false;
  18091. form.$pristine = true;
  18092. form.$valid = true;
  18093. form.$invalid = false;
  18094. form.$submitted = false;
  18095. parentForm.$addControl(form);
  18096. /**
  18097. * @ngdoc method
  18098. * @name form.FormController#$rollbackViewValue
  18099. *
  18100. * @description
  18101. * Rollback all form controls pending updates to the `$modelValue`.
  18102. *
  18103. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18104. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  18105. * a form that uses `ng-model-options` to pend updates.
  18106. */
  18107. form.$rollbackViewValue = function() {
  18108. forEach(controls, function(control) {
  18109. control.$rollbackViewValue();
  18110. });
  18111. };
  18112. /**
  18113. * @ngdoc method
  18114. * @name form.FormController#$commitViewValue
  18115. *
  18116. * @description
  18117. * Commit all form controls pending updates to the `$modelValue`.
  18118. *
  18119. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18120. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  18121. * usually handles calling this in response to input events.
  18122. */
  18123. form.$commitViewValue = function() {
  18124. forEach(controls, function(control) {
  18125. control.$commitViewValue();
  18126. });
  18127. };
  18128. /**
  18129. * @ngdoc method
  18130. * @name form.FormController#$addControl
  18131. *
  18132. * @description
  18133. * Register a control with the form.
  18134. *
  18135. * Input elements using ngModelController do this automatically when they are linked.
  18136. */
  18137. form.$addControl = function(control) {
  18138. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  18139. // and not added to the scope. Now we throw an error.
  18140. assertNotHasOwnProperty(control.$name, 'input');
  18141. controls.push(control);
  18142. if (control.$name) {
  18143. form[control.$name] = control;
  18144. }
  18145. };
  18146. // Private API: rename a form control
  18147. form.$$renameControl = function(control, newName) {
  18148. var oldName = control.$name;
  18149. if (form[oldName] === control) {
  18150. delete form[oldName];
  18151. }
  18152. form[newName] = control;
  18153. control.$name = newName;
  18154. };
  18155. /**
  18156. * @ngdoc method
  18157. * @name form.FormController#$removeControl
  18158. *
  18159. * @description
  18160. * Deregister a control from the form.
  18161. *
  18162. * Input elements using ngModelController do this automatically when they are destroyed.
  18163. */
  18164. form.$removeControl = function(control) {
  18165. if (control.$name && form[control.$name] === control) {
  18166. delete form[control.$name];
  18167. }
  18168. forEach(form.$pending, function(value, name) {
  18169. form.$setValidity(name, null, control);
  18170. });
  18171. forEach(form.$error, function(value, name) {
  18172. form.$setValidity(name, null, control);
  18173. });
  18174. forEach(form.$$success, function(value, name) {
  18175. form.$setValidity(name, null, control);
  18176. });
  18177. arrayRemove(controls, control);
  18178. };
  18179. /**
  18180. * @ngdoc method
  18181. * @name form.FormController#$setValidity
  18182. *
  18183. * @description
  18184. * Sets the validity of a form control.
  18185. *
  18186. * This method will also propagate to parent forms.
  18187. */
  18188. addSetValidityMethod({
  18189. ctrl: this,
  18190. $element: element,
  18191. set: function(object, property, controller) {
  18192. var list = object[property];
  18193. if (!list) {
  18194. object[property] = [controller];
  18195. } else {
  18196. var index = list.indexOf(controller);
  18197. if (index === -1) {
  18198. list.push(controller);
  18199. }
  18200. }
  18201. },
  18202. unset: function(object, property, controller) {
  18203. var list = object[property];
  18204. if (!list) {
  18205. return;
  18206. }
  18207. arrayRemove(list, controller);
  18208. if (list.length === 0) {
  18209. delete object[property];
  18210. }
  18211. },
  18212. parentForm: parentForm,
  18213. $animate: $animate
  18214. });
  18215. /**
  18216. * @ngdoc method
  18217. * @name form.FormController#$setDirty
  18218. *
  18219. * @description
  18220. * Sets the form to a dirty state.
  18221. *
  18222. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  18223. * state (ng-dirty class). This method will also propagate to parent forms.
  18224. */
  18225. form.$setDirty = function() {
  18226. $animate.removeClass(element, PRISTINE_CLASS);
  18227. $animate.addClass(element, DIRTY_CLASS);
  18228. form.$dirty = true;
  18229. form.$pristine = false;
  18230. parentForm.$setDirty();
  18231. };
  18232. /**
  18233. * @ngdoc method
  18234. * @name form.FormController#$setPristine
  18235. *
  18236. * @description
  18237. * Sets the form to its pristine state.
  18238. *
  18239. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  18240. * state (ng-pristine class). This method will also propagate to all the controls contained
  18241. * in this form.
  18242. *
  18243. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  18244. * saving or resetting it.
  18245. */
  18246. form.$setPristine = function() {
  18247. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  18248. form.$dirty = false;
  18249. form.$pristine = true;
  18250. form.$submitted = false;
  18251. forEach(controls, function(control) {
  18252. control.$setPristine();
  18253. });
  18254. };
  18255. /**
  18256. * @ngdoc method
  18257. * @name form.FormController#$setUntouched
  18258. *
  18259. * @description
  18260. * Sets the form to its untouched state.
  18261. *
  18262. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  18263. * untouched state (ng-untouched class).
  18264. *
  18265. * Setting a form controls back to their untouched state is often useful when setting the form
  18266. * back to its pristine state.
  18267. */
  18268. form.$setUntouched = function() {
  18269. forEach(controls, function(control) {
  18270. control.$setUntouched();
  18271. });
  18272. };
  18273. /**
  18274. * @ngdoc method
  18275. * @name form.FormController#$setSubmitted
  18276. *
  18277. * @description
  18278. * Sets the form to its submitted state.
  18279. */
  18280. form.$setSubmitted = function() {
  18281. $animate.addClass(element, SUBMITTED_CLASS);
  18282. form.$submitted = true;
  18283. parentForm.$setSubmitted();
  18284. };
  18285. }
  18286. /**
  18287. * @ngdoc directive
  18288. * @name ngForm
  18289. * @restrict EAC
  18290. *
  18291. * @description
  18292. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  18293. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  18294. * sub-group of controls needs to be determined.
  18295. *
  18296. * Note: the purpose of `ngForm` is to group controls,
  18297. * but not to be a replacement for the `<form>` tag with all of its capabilities
  18298. * (e.g. posting to the server, ...).
  18299. *
  18300. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  18301. * related scope, under this name.
  18302. *
  18303. */
  18304. /**
  18305. * @ngdoc directive
  18306. * @name form
  18307. * @restrict E
  18308. *
  18309. * @description
  18310. * Directive that instantiates
  18311. * {@link form.FormController FormController}.
  18312. *
  18313. * If the `name` attribute is specified, the form controller is published onto the current scope under
  18314. * this name.
  18315. *
  18316. * # Alias: {@link ng.directive:ngForm `ngForm`}
  18317. *
  18318. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  18319. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  18320. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  18321. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  18322. * using Angular validation directives in forms that are dynamically generated using the
  18323. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  18324. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  18325. * `ngForm` directive and nest these in an outer `form` element.
  18326. *
  18327. *
  18328. * # CSS classes
  18329. * - `ng-valid` is set if the form is valid.
  18330. * - `ng-invalid` is set if the form is invalid.
  18331. * - `ng-pristine` is set if the form is pristine.
  18332. * - `ng-dirty` is set if the form is dirty.
  18333. * - `ng-submitted` is set if the form was submitted.
  18334. *
  18335. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  18336. *
  18337. *
  18338. * # Submitting a form and preventing the default action
  18339. *
  18340. * Since the role of forms in client-side Angular applications is different than in classical
  18341. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  18342. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  18343. * to handle the form submission in an application-specific way.
  18344. *
  18345. * For this reason, Angular prevents the default action (form submission to the server) unless the
  18346. * `<form>` element has an `action` attribute specified.
  18347. *
  18348. * You can use one of the following two ways to specify what javascript method should be called when
  18349. * a form is submitted:
  18350. *
  18351. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  18352. * - {@link ng.directive:ngClick ngClick} directive on the first
  18353. * button or input field of type submit (input[type=submit])
  18354. *
  18355. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  18356. * or {@link ng.directive:ngClick ngClick} directives.
  18357. * This is because of the following form submission rules in the HTML specification:
  18358. *
  18359. * - If a form has only one input field then hitting enter in this field triggers form submit
  18360. * (`ngSubmit`)
  18361. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  18362. * doesn't trigger submit
  18363. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  18364. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  18365. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  18366. *
  18367. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  18368. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  18369. * to have access to the updated model.
  18370. *
  18371. * ## Animation Hooks
  18372. *
  18373. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  18374. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  18375. * other validations that are performed within the form. Animations in ngForm are similar to how
  18376. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  18377. * as JS animations.
  18378. *
  18379. * The following example shows a simple way to utilize CSS transitions to style a form element
  18380. * that has been rendered as invalid after it has been validated:
  18381. *
  18382. * <pre>
  18383. * //be sure to include ngAnimate as a module to hook into more
  18384. * //advanced animations
  18385. * .my-form {
  18386. * transition:0.5s linear all;
  18387. * background: white;
  18388. * }
  18389. * .my-form.ng-invalid {
  18390. * background: red;
  18391. * color:white;
  18392. * }
  18393. * </pre>
  18394. *
  18395. * @example
  18396. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  18397. <file name="index.html">
  18398. <script>
  18399. angular.module('formExample', [])
  18400. .controller('FormController', ['$scope', function($scope) {
  18401. $scope.userType = 'guest';
  18402. }]);
  18403. </script>
  18404. <style>
  18405. .my-form {
  18406. -webkit-transition:all linear 0.5s;
  18407. transition:all linear 0.5s;
  18408. background: transparent;
  18409. }
  18410. .my-form.ng-invalid {
  18411. background: red;
  18412. }
  18413. </style>
  18414. <form name="myForm" ng-controller="FormController" class="my-form">
  18415. userType: <input name="input" ng-model="userType" required>
  18416. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  18417. <code>userType = {{userType}}</code><br>
  18418. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  18419. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  18420. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  18421. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  18422. </form>
  18423. </file>
  18424. <file name="protractor.js" type="protractor">
  18425. it('should initialize to model', function() {
  18426. var userType = element(by.binding('userType'));
  18427. var valid = element(by.binding('myForm.input.$valid'));
  18428. expect(userType.getText()).toContain('guest');
  18429. expect(valid.getText()).toContain('true');
  18430. });
  18431. it('should be invalid if empty', function() {
  18432. var userType = element(by.binding('userType'));
  18433. var valid = element(by.binding('myForm.input.$valid'));
  18434. var userInput = element(by.model('userType'));
  18435. userInput.clear();
  18436. userInput.sendKeys('');
  18437. expect(userType.getText()).toEqual('userType =');
  18438. expect(valid.getText()).toContain('false');
  18439. });
  18440. </file>
  18441. </example>
  18442. *
  18443. * @param {string=} name Name of the form. If specified, the form controller will be published into
  18444. * related scope, under this name.
  18445. */
  18446. var formDirectiveFactory = function(isNgForm) {
  18447. return ['$timeout', function($timeout) {
  18448. var formDirective = {
  18449. name: 'form',
  18450. restrict: isNgForm ? 'EAC' : 'E',
  18451. controller: FormController,
  18452. compile: function ngFormCompile(formElement, attr) {
  18453. // Setup initial state of the control
  18454. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  18455. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  18456. return {
  18457. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  18458. // if `action` attr is not present on the form, prevent the default action (submission)
  18459. if (!('action' in attr)) {
  18460. // we can't use jq events because if a form is destroyed during submission the default
  18461. // action is not prevented. see #1238
  18462. //
  18463. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  18464. // page reload if the form was destroyed by submission of the form via a click handler
  18465. // on a button in the form. Looks like an IE9 specific bug.
  18466. var handleFormSubmission = function(event) {
  18467. scope.$apply(function() {
  18468. controller.$commitViewValue();
  18469. controller.$setSubmitted();
  18470. });
  18471. event.preventDefault();
  18472. };
  18473. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18474. // unregister the preventDefault listener so that we don't not leak memory but in a
  18475. // way that will achieve the prevention of the default action.
  18476. formElement.on('$destroy', function() {
  18477. $timeout(function() {
  18478. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18479. }, 0, false);
  18480. });
  18481. }
  18482. var parentFormCtrl = controller.$$parentForm;
  18483. if (nameAttr) {
  18484. setter(scope, controller.$name, controller, controller.$name);
  18485. attr.$observe(nameAttr, function(newValue) {
  18486. if (controller.$name === newValue) return;
  18487. setter(scope, controller.$name, undefined, controller.$name);
  18488. parentFormCtrl.$$renameControl(controller, newValue);
  18489. setter(scope, controller.$name, controller, controller.$name);
  18490. });
  18491. }
  18492. formElement.on('$destroy', function() {
  18493. parentFormCtrl.$removeControl(controller);
  18494. if (nameAttr) {
  18495. setter(scope, attr[nameAttr], undefined, controller.$name);
  18496. }
  18497. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  18498. });
  18499. }
  18500. };
  18501. }
  18502. };
  18503. return formDirective;
  18504. }];
  18505. };
  18506. var formDirective = formDirectiveFactory();
  18507. var ngFormDirective = formDirectiveFactory(true);
  18508. /* global VALID_CLASS: false,
  18509. INVALID_CLASS: false,
  18510. PRISTINE_CLASS: false,
  18511. DIRTY_CLASS: false,
  18512. UNTOUCHED_CLASS: false,
  18513. TOUCHED_CLASS: false,
  18514. $ngModelMinErr: false,
  18515. */
  18516. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  18517. 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)/;
  18518. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  18519. var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
  18520. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  18521. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  18522. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18523. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  18524. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  18525. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18526. var inputType = {
  18527. /**
  18528. * @ngdoc input
  18529. * @name input[text]
  18530. *
  18531. * @description
  18532. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  18533. *
  18534. *
  18535. * @param {string} ngModel Assignable angular expression to data-bind to.
  18536. * @param {string=} name Property name of the form under which the control is published.
  18537. * @param {string=} required Adds `required` validation error key if the value is not entered.
  18538. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18539. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18540. * `required` when you want to data-bind to the `required` attribute.
  18541. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18542. * minlength.
  18543. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18544. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  18545. * any length.
  18546. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  18547. * that contains the regular expression body that will be converted to a regular expression
  18548. * as in the ngPattern directive.
  18549. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  18550. * a RegExp found by evaluating the Angular expression given in the attribute value.
  18551. * If the expression evaluates to a RegExp object, then this is used directly.
  18552. * If the expression evaluates to a string, then it will be converted to a RegExp
  18553. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  18554. * `new RegExp('^abc$')`.<br />
  18555. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  18556. * start at the index of the last search's match, thus not taking the whole input value into
  18557. * account.
  18558. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18559. * interaction with the input element.
  18560. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18561. * This parameter is ignored for input[type=password] controls, which will never trim the
  18562. * input.
  18563. *
  18564. * @example
  18565. <example name="text-input-directive" module="textInputExample">
  18566. <file name="index.html">
  18567. <script>
  18568. angular.module('textInputExample', [])
  18569. .controller('ExampleController', ['$scope', function($scope) {
  18570. $scope.example = {
  18571. text: 'guest',
  18572. word: /^\s*\w*\s*$/
  18573. };
  18574. }]);
  18575. </script>
  18576. <form name="myForm" ng-controller="ExampleController">
  18577. <label>Single word:
  18578. <input type="text" name="input" ng-model="example.text"
  18579. ng-pattern="example.word" required ng-trim="false">
  18580. </label>
  18581. <div role="alert">
  18582. <span class="error" ng-show="myForm.input.$error.required">
  18583. Required!</span>
  18584. <span class="error" ng-show="myForm.input.$error.pattern">
  18585. Single word only!</span>
  18586. </div>
  18587. <tt>text = {{example.text}}</tt><br/>
  18588. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18589. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18590. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18591. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18592. </form>
  18593. </file>
  18594. <file name="protractor.js" type="protractor">
  18595. var text = element(by.binding('example.text'));
  18596. var valid = element(by.binding('myForm.input.$valid'));
  18597. var input = element(by.model('example.text'));
  18598. it('should initialize to model', function() {
  18599. expect(text.getText()).toContain('guest');
  18600. expect(valid.getText()).toContain('true');
  18601. });
  18602. it('should be invalid if empty', function() {
  18603. input.clear();
  18604. input.sendKeys('');
  18605. expect(text.getText()).toEqual('text =');
  18606. expect(valid.getText()).toContain('false');
  18607. });
  18608. it('should be invalid if multi word', function() {
  18609. input.clear();
  18610. input.sendKeys('hello world');
  18611. expect(valid.getText()).toContain('false');
  18612. });
  18613. </file>
  18614. </example>
  18615. */
  18616. 'text': textInputType,
  18617. /**
  18618. * @ngdoc input
  18619. * @name input[date]
  18620. *
  18621. * @description
  18622. * Input with date validation and transformation. In browsers that do not yet support
  18623. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  18624. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  18625. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  18626. * expected input format via a placeholder or label.
  18627. *
  18628. * The model must always be a Date object, otherwise Angular will throw an error.
  18629. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18630. *
  18631. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18632. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18633. *
  18634. * @param {string} ngModel Assignable angular expression to data-bind to.
  18635. * @param {string=} name Property name of the form under which the control is published.
  18636. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18637. * valid ISO date string (yyyy-MM-dd).
  18638. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18639. * a valid ISO date string (yyyy-MM-dd).
  18640. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18641. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18642. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18643. * `required` when you want to data-bind to the `required` attribute.
  18644. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18645. * interaction with the input element.
  18646. *
  18647. * @example
  18648. <example name="date-input-directive" module="dateInputExample">
  18649. <file name="index.html">
  18650. <script>
  18651. angular.module('dateInputExample', [])
  18652. .controller('DateController', ['$scope', function($scope) {
  18653. $scope.example = {
  18654. value: new Date(2013, 9, 22)
  18655. };
  18656. }]);
  18657. </script>
  18658. <form name="myForm" ng-controller="DateController as dateCtrl">
  18659. <label for="exampleInput">Pick a date in 2013:</label>
  18660. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  18661. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  18662. <div role="alert">
  18663. <span class="error" ng-show="myForm.input.$error.required">
  18664. Required!</span>
  18665. <span class="error" ng-show="myForm.input.$error.date">
  18666. Not a valid date!</span>
  18667. </div>
  18668. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  18669. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18670. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18671. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18672. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18673. </form>
  18674. </file>
  18675. <file name="protractor.js" type="protractor">
  18676. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  18677. var valid = element(by.binding('myForm.input.$valid'));
  18678. var input = element(by.model('example.value'));
  18679. // currently protractor/webdriver does not support
  18680. // sending keys to all known HTML5 input controls
  18681. // for various browsers (see https://github.com/angular/protractor/issues/562).
  18682. function setInput(val) {
  18683. // set the value of the element and force validation.
  18684. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18685. "ipt.value = '" + val + "';" +
  18686. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18687. browser.executeScript(scr);
  18688. }
  18689. it('should initialize to model', function() {
  18690. expect(value.getText()).toContain('2013-10-22');
  18691. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18692. });
  18693. it('should be invalid if empty', function() {
  18694. setInput('');
  18695. expect(value.getText()).toEqual('value =');
  18696. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18697. });
  18698. it('should be invalid if over max', function() {
  18699. setInput('2015-01-01');
  18700. expect(value.getText()).toContain('');
  18701. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18702. });
  18703. </file>
  18704. </example>
  18705. */
  18706. 'date': createDateInputType('date', DATE_REGEXP,
  18707. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  18708. 'yyyy-MM-dd'),
  18709. /**
  18710. * @ngdoc input
  18711. * @name input[datetime-local]
  18712. *
  18713. * @description
  18714. * Input with datetime validation and transformation. In browsers that do not yet support
  18715. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18716. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  18717. *
  18718. * The model must always be a Date object, otherwise Angular will throw an error.
  18719. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18720. *
  18721. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18722. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18723. *
  18724. * @param {string} ngModel Assignable angular expression to data-bind to.
  18725. * @param {string=} name Property name of the form under which the control is published.
  18726. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18727. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  18728. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18729. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  18730. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18731. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18732. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18733. * `required` when you want to data-bind to the `required` attribute.
  18734. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18735. * interaction with the input element.
  18736. *
  18737. * @example
  18738. <example name="datetimelocal-input-directive" module="dateExample">
  18739. <file name="index.html">
  18740. <script>
  18741. angular.module('dateExample', [])
  18742. .controller('DateController', ['$scope', function($scope) {
  18743. $scope.example = {
  18744. value: new Date(2010, 11, 28, 14, 57)
  18745. };
  18746. }]);
  18747. </script>
  18748. <form name="myForm" ng-controller="DateController as dateCtrl">
  18749. <label for="exampleInput">Pick a date between in 2013:</label>
  18750. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  18751. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  18752. <div role="alert">
  18753. <span class="error" ng-show="myForm.input.$error.required">
  18754. Required!</span>
  18755. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  18756. Not a valid date!</span>
  18757. </div>
  18758. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  18759. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18760. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18761. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18762. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18763. </form>
  18764. </file>
  18765. <file name="protractor.js" type="protractor">
  18766. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  18767. var valid = element(by.binding('myForm.input.$valid'));
  18768. var input = element(by.model('example.value'));
  18769. // currently protractor/webdriver does not support
  18770. // sending keys to all known HTML5 input controls
  18771. // for various browsers (https://github.com/angular/protractor/issues/562).
  18772. function setInput(val) {
  18773. // set the value of the element and force validation.
  18774. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18775. "ipt.value = '" + val + "';" +
  18776. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18777. browser.executeScript(scr);
  18778. }
  18779. it('should initialize to model', function() {
  18780. expect(value.getText()).toContain('2010-12-28T14:57:00');
  18781. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18782. });
  18783. it('should be invalid if empty', function() {
  18784. setInput('');
  18785. expect(value.getText()).toEqual('value =');
  18786. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18787. });
  18788. it('should be invalid if over max', function() {
  18789. setInput('2015-01-01T23:59:00');
  18790. expect(value.getText()).toContain('');
  18791. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18792. });
  18793. </file>
  18794. </example>
  18795. */
  18796. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  18797. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  18798. 'yyyy-MM-ddTHH:mm:ss.sss'),
  18799. /**
  18800. * @ngdoc input
  18801. * @name input[time]
  18802. *
  18803. * @description
  18804. * Input with time validation and transformation. In browsers that do not yet support
  18805. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18806. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  18807. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  18808. *
  18809. * The model must always be a Date object, otherwise Angular will throw an error.
  18810. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18811. *
  18812. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18813. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18814. *
  18815. * @param {string} ngModel Assignable angular expression to data-bind to.
  18816. * @param {string=} name Property name of the form under which the control is published.
  18817. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18818. * valid ISO time format (HH:mm:ss).
  18819. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  18820. * valid ISO time format (HH:mm:ss).
  18821. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18822. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18823. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18824. * `required` when you want to data-bind to the `required` attribute.
  18825. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18826. * interaction with the input element.
  18827. *
  18828. * @example
  18829. <example name="time-input-directive" module="timeExample">
  18830. <file name="index.html">
  18831. <script>
  18832. angular.module('timeExample', [])
  18833. .controller('DateController', ['$scope', function($scope) {
  18834. $scope.example = {
  18835. value: new Date(1970, 0, 1, 14, 57, 0)
  18836. };
  18837. }]);
  18838. </script>
  18839. <form name="myForm" ng-controller="DateController as dateCtrl">
  18840. <label for="exampleInput">Pick a between 8am and 5pm:</label>
  18841. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  18842. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  18843. <div role="alert">
  18844. <span class="error" ng-show="myForm.input.$error.required">
  18845. Required!</span>
  18846. <span class="error" ng-show="myForm.input.$error.time">
  18847. Not a valid date!</span>
  18848. </div>
  18849. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  18850. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18851. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18852. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18853. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18854. </form>
  18855. </file>
  18856. <file name="protractor.js" type="protractor">
  18857. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  18858. var valid = element(by.binding('myForm.input.$valid'));
  18859. var input = element(by.model('example.value'));
  18860. // currently protractor/webdriver does not support
  18861. // sending keys to all known HTML5 input controls
  18862. // for various browsers (https://github.com/angular/protractor/issues/562).
  18863. function setInput(val) {
  18864. // set the value of the element and force validation.
  18865. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18866. "ipt.value = '" + val + "';" +
  18867. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18868. browser.executeScript(scr);
  18869. }
  18870. it('should initialize to model', function() {
  18871. expect(value.getText()).toContain('14:57:00');
  18872. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18873. });
  18874. it('should be invalid if empty', function() {
  18875. setInput('');
  18876. expect(value.getText()).toEqual('value =');
  18877. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18878. });
  18879. it('should be invalid if over max', function() {
  18880. setInput('23:59:00');
  18881. expect(value.getText()).toContain('');
  18882. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18883. });
  18884. </file>
  18885. </example>
  18886. */
  18887. 'time': createDateInputType('time', TIME_REGEXP,
  18888. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  18889. 'HH:mm:ss.sss'),
  18890. /**
  18891. * @ngdoc input
  18892. * @name input[week]
  18893. *
  18894. * @description
  18895. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  18896. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18897. * week format (yyyy-W##), for example: `2013-W02`.
  18898. *
  18899. * The model must always be a Date object, otherwise Angular will throw an error.
  18900. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18901. *
  18902. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18903. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18904. *
  18905. * @param {string} ngModel Assignable angular expression to data-bind to.
  18906. * @param {string=} name Property name of the form under which the control is published.
  18907. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18908. * valid ISO week format (yyyy-W##).
  18909. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18910. * a valid ISO week format (yyyy-W##).
  18911. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18912. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18913. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18914. * `required` when you want to data-bind to the `required` attribute.
  18915. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18916. * interaction with the input element.
  18917. *
  18918. * @example
  18919. <example name="week-input-directive" module="weekExample">
  18920. <file name="index.html">
  18921. <script>
  18922. angular.module('weekExample', [])
  18923. .controller('DateController', ['$scope', function($scope) {
  18924. $scope.example = {
  18925. value: new Date(2013, 0, 3)
  18926. };
  18927. }]);
  18928. </script>
  18929. <form name="myForm" ng-controller="DateController as dateCtrl">
  18930. <label>Pick a date between in 2013:
  18931. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  18932. placeholder="YYYY-W##" min="2012-W32"
  18933. max="2013-W52" required />
  18934. </label>
  18935. <div role="alert">
  18936. <span class="error" ng-show="myForm.input.$error.required">
  18937. Required!</span>
  18938. <span class="error" ng-show="myForm.input.$error.week">
  18939. Not a valid date!</span>
  18940. </div>
  18941. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  18942. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18943. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18944. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18945. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18946. </form>
  18947. </file>
  18948. <file name="protractor.js" type="protractor">
  18949. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  18950. var valid = element(by.binding('myForm.input.$valid'));
  18951. var input = element(by.model('example.value'));
  18952. // currently protractor/webdriver does not support
  18953. // sending keys to all known HTML5 input controls
  18954. // for various browsers (https://github.com/angular/protractor/issues/562).
  18955. function setInput(val) {
  18956. // set the value of the element and force validation.
  18957. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18958. "ipt.value = '" + val + "';" +
  18959. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18960. browser.executeScript(scr);
  18961. }
  18962. it('should initialize to model', function() {
  18963. expect(value.getText()).toContain('2013-W01');
  18964. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18965. });
  18966. it('should be invalid if empty', function() {
  18967. setInput('');
  18968. expect(value.getText()).toEqual('value =');
  18969. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18970. });
  18971. it('should be invalid if over max', function() {
  18972. setInput('2015-W01');
  18973. expect(value.getText()).toContain('');
  18974. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18975. });
  18976. </file>
  18977. </example>
  18978. */
  18979. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  18980. /**
  18981. * @ngdoc input
  18982. * @name input[month]
  18983. *
  18984. * @description
  18985. * Input with month validation and transformation. In browsers that do not yet support
  18986. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18987. * month format (yyyy-MM), for example: `2009-01`.
  18988. *
  18989. * The model must always be a Date object, otherwise Angular will throw an error.
  18990. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18991. * If the model is not set to the first of the month, the next view to model update will set it
  18992. * to the first of the month.
  18993. *
  18994. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18995. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18996. *
  18997. * @param {string} ngModel Assignable angular expression to data-bind to.
  18998. * @param {string=} name Property name of the form under which the control is published.
  18999. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  19000. * a valid ISO month format (yyyy-MM).
  19001. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  19002. * be a valid ISO month format (yyyy-MM).
  19003. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19004. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19005. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19006. * `required` when you want to data-bind to the `required` attribute.
  19007. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19008. * interaction with the input element.
  19009. *
  19010. * @example
  19011. <example name="month-input-directive" module="monthExample">
  19012. <file name="index.html">
  19013. <script>
  19014. angular.module('monthExample', [])
  19015. .controller('DateController', ['$scope', function($scope) {
  19016. $scope.example = {
  19017. value: new Date(2013, 9, 1)
  19018. };
  19019. }]);
  19020. </script>
  19021. <form name="myForm" ng-controller="DateController as dateCtrl">
  19022. <label for="exampleInput">Pick a month in 2013:</label>
  19023. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  19024. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  19025. <div role="alert">
  19026. <span class="error" ng-show="myForm.input.$error.required">
  19027. Required!</span>
  19028. <span class="error" ng-show="myForm.input.$error.month">
  19029. Not a valid month!</span>
  19030. </div>
  19031. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  19032. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19033. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19034. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19035. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19036. </form>
  19037. </file>
  19038. <file name="protractor.js" type="protractor">
  19039. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  19040. var valid = element(by.binding('myForm.input.$valid'));
  19041. var input = element(by.model('example.value'));
  19042. // currently protractor/webdriver does not support
  19043. // sending keys to all known HTML5 input controls
  19044. // for various browsers (https://github.com/angular/protractor/issues/562).
  19045. function setInput(val) {
  19046. // set the value of the element and force validation.
  19047. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19048. "ipt.value = '" + val + "';" +
  19049. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19050. browser.executeScript(scr);
  19051. }
  19052. it('should initialize to model', function() {
  19053. expect(value.getText()).toContain('2013-10');
  19054. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19055. });
  19056. it('should be invalid if empty', function() {
  19057. setInput('');
  19058. expect(value.getText()).toEqual('value =');
  19059. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19060. });
  19061. it('should be invalid if over max', function() {
  19062. setInput('2015-01');
  19063. expect(value.getText()).toContain('');
  19064. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19065. });
  19066. </file>
  19067. </example>
  19068. */
  19069. 'month': createDateInputType('month', MONTH_REGEXP,
  19070. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  19071. 'yyyy-MM'),
  19072. /**
  19073. * @ngdoc input
  19074. * @name input[number]
  19075. *
  19076. * @description
  19077. * Text input with number validation and transformation. Sets the `number` validation
  19078. * error if not a valid number.
  19079. *
  19080. * <div class="alert alert-warning">
  19081. * The model must always be of type `number` otherwise Angular will throw an error.
  19082. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  19083. * error docs for more information and an example of how to convert your model if necessary.
  19084. * </div>
  19085. *
  19086. * ## Issues with HTML5 constraint validation
  19087. *
  19088. * In browsers that follow the
  19089. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  19090. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  19091. * If a non-number is entered in the input, the browser will report the value as an empty string,
  19092. * which means the view / model values in `ngModel` and subsequently the scope value
  19093. * will also be an empty string.
  19094. *
  19095. *
  19096. * @param {string} ngModel Assignable angular expression to data-bind to.
  19097. * @param {string=} name Property name of the form under which the control is published.
  19098. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19099. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19100. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19101. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19102. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19103. * `required` when you want to data-bind to the `required` attribute.
  19104. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19105. * minlength.
  19106. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19107. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19108. * any length.
  19109. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19110. * that contains the regular expression body that will be converted to a regular expression
  19111. * as in the ngPattern directive.
  19112. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19113. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19114. * If the expression evaluates to a RegExp object, then this is used directly.
  19115. * If the expression evaluates to a string, then it will be converted to a RegExp
  19116. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19117. * `new RegExp('^abc$')`.<br />
  19118. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19119. * start at the index of the last search's match, thus not taking the whole input value into
  19120. * account.
  19121. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19122. * interaction with the input element.
  19123. *
  19124. * @example
  19125. <example name="number-input-directive" module="numberExample">
  19126. <file name="index.html">
  19127. <script>
  19128. angular.module('numberExample', [])
  19129. .controller('ExampleController', ['$scope', function($scope) {
  19130. $scope.example = {
  19131. value: 12
  19132. };
  19133. }]);
  19134. </script>
  19135. <form name="myForm" ng-controller="ExampleController">
  19136. <label>Number:
  19137. <input type="number" name="input" ng-model="example.value"
  19138. min="0" max="99" required>
  19139. </label>
  19140. <div role="alert">
  19141. <span class="error" ng-show="myForm.input.$error.required">
  19142. Required!</span>
  19143. <span class="error" ng-show="myForm.input.$error.number">
  19144. Not valid number!</span>
  19145. </div>
  19146. <tt>value = {{example.value}}</tt><br/>
  19147. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19148. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19149. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19150. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19151. </form>
  19152. </file>
  19153. <file name="protractor.js" type="protractor">
  19154. var value = element(by.binding('example.value'));
  19155. var valid = element(by.binding('myForm.input.$valid'));
  19156. var input = element(by.model('example.value'));
  19157. it('should initialize to model', function() {
  19158. expect(value.getText()).toContain('12');
  19159. expect(valid.getText()).toContain('true');
  19160. });
  19161. it('should be invalid if empty', function() {
  19162. input.clear();
  19163. input.sendKeys('');
  19164. expect(value.getText()).toEqual('value =');
  19165. expect(valid.getText()).toContain('false');
  19166. });
  19167. it('should be invalid if over max', function() {
  19168. input.clear();
  19169. input.sendKeys('123');
  19170. expect(value.getText()).toEqual('value =');
  19171. expect(valid.getText()).toContain('false');
  19172. });
  19173. </file>
  19174. </example>
  19175. */
  19176. 'number': numberInputType,
  19177. /**
  19178. * @ngdoc input
  19179. * @name input[url]
  19180. *
  19181. * @description
  19182. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  19183. * valid URL.
  19184. *
  19185. * <div class="alert alert-warning">
  19186. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  19187. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  19188. * the built-in validators (see the {@link guide/forms Forms guide})
  19189. * </div>
  19190. *
  19191. * @param {string} ngModel Assignable angular expression to data-bind to.
  19192. * @param {string=} name Property name of the form under which the control is published.
  19193. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19194. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19195. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19196. * `required` when you want to data-bind to the `required` attribute.
  19197. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19198. * minlength.
  19199. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19200. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19201. * any length.
  19202. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19203. * that contains the regular expression body that will be converted to a regular expression
  19204. * as in the ngPattern directive.
  19205. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19206. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19207. * If the expression evaluates to a RegExp object, then this is used directly.
  19208. * If the expression evaluates to a string, then it will be converted to a RegExp
  19209. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19210. * `new RegExp('^abc$')`.<br />
  19211. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19212. * start at the index of the last search's match, thus not taking the whole input value into
  19213. * account.
  19214. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19215. * interaction with the input element.
  19216. *
  19217. * @example
  19218. <example name="url-input-directive" module="urlExample">
  19219. <file name="index.html">
  19220. <script>
  19221. angular.module('urlExample', [])
  19222. .controller('ExampleController', ['$scope', function($scope) {
  19223. $scope.url = {
  19224. text: 'http://google.com'
  19225. };
  19226. }]);
  19227. </script>
  19228. <form name="myForm" ng-controller="ExampleController">
  19229. <label>URL:
  19230. <input type="url" name="input" ng-model="url.text" required>
  19231. <label>
  19232. <div role="alert">
  19233. <span class="error" ng-show="myForm.input.$error.required">
  19234. Required!</span>
  19235. <span class="error" ng-show="myForm.input.$error.url">
  19236. Not valid url!</span>
  19237. </div>
  19238. <tt>text = {{url.text}}</tt><br/>
  19239. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19240. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19241. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19242. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19243. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  19244. </form>
  19245. </file>
  19246. <file name="protractor.js" type="protractor">
  19247. var text = element(by.binding('url.text'));
  19248. var valid = element(by.binding('myForm.input.$valid'));
  19249. var input = element(by.model('url.text'));
  19250. it('should initialize to model', function() {
  19251. expect(text.getText()).toContain('http://google.com');
  19252. expect(valid.getText()).toContain('true');
  19253. });
  19254. it('should be invalid if empty', function() {
  19255. input.clear();
  19256. input.sendKeys('');
  19257. expect(text.getText()).toEqual('text =');
  19258. expect(valid.getText()).toContain('false');
  19259. });
  19260. it('should be invalid if not url', function() {
  19261. input.clear();
  19262. input.sendKeys('box');
  19263. expect(valid.getText()).toContain('false');
  19264. });
  19265. </file>
  19266. </example>
  19267. */
  19268. 'url': urlInputType,
  19269. /**
  19270. * @ngdoc input
  19271. * @name input[email]
  19272. *
  19273. * @description
  19274. * Text input with email validation. Sets the `email` validation error key if not a valid email
  19275. * address.
  19276. *
  19277. * <div class="alert alert-warning">
  19278. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  19279. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  19280. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  19281. * </div>
  19282. *
  19283. * @param {string} ngModel Assignable angular expression to data-bind to.
  19284. * @param {string=} name Property name of the form under which the control is published.
  19285. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19286. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19287. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19288. * `required` when you want to data-bind to the `required` attribute.
  19289. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19290. * minlength.
  19291. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19292. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19293. * any length.
  19294. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19295. * that contains the regular expression body that will be converted to a regular expression
  19296. * as in the ngPattern directive.
  19297. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19298. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19299. * If the expression evaluates to a RegExp object, then this is used directly.
  19300. * If the expression evaluates to a string, then it will be converted to a RegExp
  19301. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19302. * `new RegExp('^abc$')`.<br />
  19303. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19304. * start at the index of the last search's match, thus not taking the whole input value into
  19305. * account.
  19306. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19307. * interaction with the input element.
  19308. *
  19309. * @example
  19310. <example name="email-input-directive" module="emailExample">
  19311. <file name="index.html">
  19312. <script>
  19313. angular.module('emailExample', [])
  19314. .controller('ExampleController', ['$scope', function($scope) {
  19315. $scope.email = {
  19316. text: 'me@example.com'
  19317. };
  19318. }]);
  19319. </script>
  19320. <form name="myForm" ng-controller="ExampleController">
  19321. <label>Email:
  19322. <input type="email" name="input" ng-model="email.text" required>
  19323. </label>
  19324. <div role="alert">
  19325. <span class="error" ng-show="myForm.input.$error.required">
  19326. Required!</span>
  19327. <span class="error" ng-show="myForm.input.$error.email">
  19328. Not valid email!</span>
  19329. </div>
  19330. <tt>text = {{email.text}}</tt><br/>
  19331. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19332. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19333. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19334. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19335. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  19336. </form>
  19337. </file>
  19338. <file name="protractor.js" type="protractor">
  19339. var text = element(by.binding('email.text'));
  19340. var valid = element(by.binding('myForm.input.$valid'));
  19341. var input = element(by.model('email.text'));
  19342. it('should initialize to model', function() {
  19343. expect(text.getText()).toContain('me@example.com');
  19344. expect(valid.getText()).toContain('true');
  19345. });
  19346. it('should be invalid if empty', function() {
  19347. input.clear();
  19348. input.sendKeys('');
  19349. expect(text.getText()).toEqual('text =');
  19350. expect(valid.getText()).toContain('false');
  19351. });
  19352. it('should be invalid if not email', function() {
  19353. input.clear();
  19354. input.sendKeys('xxx');
  19355. expect(valid.getText()).toContain('false');
  19356. });
  19357. </file>
  19358. </example>
  19359. */
  19360. 'email': emailInputType,
  19361. /**
  19362. * @ngdoc input
  19363. * @name input[radio]
  19364. *
  19365. * @description
  19366. * HTML radio button.
  19367. *
  19368. * @param {string} ngModel Assignable angular expression to data-bind to.
  19369. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  19370. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  19371. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  19372. * @param {string=} name Property name of the form under which the control is published.
  19373. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19374. * interaction with the input element.
  19375. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  19376. * is selected. Should be used instead of the `value` attribute if you need
  19377. * a non-string `ngModel` (`boolean`, `array`, ...).
  19378. *
  19379. * @example
  19380. <example name="radio-input-directive" module="radioExample">
  19381. <file name="index.html">
  19382. <script>
  19383. angular.module('radioExample', [])
  19384. .controller('ExampleController', ['$scope', function($scope) {
  19385. $scope.color = {
  19386. name: 'blue'
  19387. };
  19388. $scope.specialValue = {
  19389. "id": "12345",
  19390. "value": "green"
  19391. };
  19392. }]);
  19393. </script>
  19394. <form name="myForm" ng-controller="ExampleController">
  19395. <label>
  19396. <input type="radio" ng-model="color.name" value="red">
  19397. Red
  19398. </label><br/>
  19399. <label>
  19400. <input type="radio" ng-model="color.name" ng-value="specialValue">
  19401. Green
  19402. </label><br/>
  19403. <label>
  19404. <input type="radio" ng-model="color.name" value="blue">
  19405. Blue
  19406. </label><br/>
  19407. <tt>color = {{color.name | json}}</tt><br/>
  19408. </form>
  19409. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  19410. </file>
  19411. <file name="protractor.js" type="protractor">
  19412. it('should change state', function() {
  19413. var color = element(by.binding('color.name'));
  19414. expect(color.getText()).toContain('blue');
  19415. element.all(by.model('color.name')).get(0).click();
  19416. expect(color.getText()).toContain('red');
  19417. });
  19418. </file>
  19419. </example>
  19420. */
  19421. 'radio': radioInputType,
  19422. /**
  19423. * @ngdoc input
  19424. * @name input[checkbox]
  19425. *
  19426. * @description
  19427. * HTML checkbox.
  19428. *
  19429. * @param {string} ngModel Assignable angular expression to data-bind to.
  19430. * @param {string=} name Property name of the form under which the control is published.
  19431. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  19432. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  19433. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19434. * interaction with the input element.
  19435. *
  19436. * @example
  19437. <example name="checkbox-input-directive" module="checkboxExample">
  19438. <file name="index.html">
  19439. <script>
  19440. angular.module('checkboxExample', [])
  19441. .controller('ExampleController', ['$scope', function($scope) {
  19442. $scope.checkboxModel = {
  19443. value1 : true,
  19444. value2 : 'YES'
  19445. };
  19446. }]);
  19447. </script>
  19448. <form name="myForm" ng-controller="ExampleController">
  19449. <label>Value1:
  19450. <input type="checkbox" ng-model="checkboxModel.value1">
  19451. </label><br/>
  19452. <label>Value2:
  19453. <input type="checkbox" ng-model="checkboxModel.value2"
  19454. ng-true-value="'YES'" ng-false-value="'NO'">
  19455. </label><br/>
  19456. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  19457. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  19458. </form>
  19459. </file>
  19460. <file name="protractor.js" type="protractor">
  19461. it('should change state', function() {
  19462. var value1 = element(by.binding('checkboxModel.value1'));
  19463. var value2 = element(by.binding('checkboxModel.value2'));
  19464. expect(value1.getText()).toContain('true');
  19465. expect(value2.getText()).toContain('YES');
  19466. element(by.model('checkboxModel.value1')).click();
  19467. element(by.model('checkboxModel.value2')).click();
  19468. expect(value1.getText()).toContain('false');
  19469. expect(value2.getText()).toContain('NO');
  19470. });
  19471. </file>
  19472. </example>
  19473. */
  19474. 'checkbox': checkboxInputType,
  19475. 'hidden': noop,
  19476. 'button': noop,
  19477. 'submit': noop,
  19478. 'reset': noop,
  19479. 'file': noop
  19480. };
  19481. function stringBasedInputType(ctrl) {
  19482. ctrl.$formatters.push(function(value) {
  19483. return ctrl.$isEmpty(value) ? value : value.toString();
  19484. });
  19485. }
  19486. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19487. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19488. stringBasedInputType(ctrl);
  19489. }
  19490. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19491. var type = lowercase(element[0].type);
  19492. // In composition mode, users are still inputing intermediate text buffer,
  19493. // hold the listener until composition is done.
  19494. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  19495. if (!$sniffer.android) {
  19496. var composing = false;
  19497. element.on('compositionstart', function(data) {
  19498. composing = true;
  19499. });
  19500. element.on('compositionend', function() {
  19501. composing = false;
  19502. listener();
  19503. });
  19504. }
  19505. var listener = function(ev) {
  19506. if (timeout) {
  19507. $browser.defer.cancel(timeout);
  19508. timeout = null;
  19509. }
  19510. if (composing) return;
  19511. var value = element.val(),
  19512. event = ev && ev.type;
  19513. // By default we will trim the value
  19514. // If the attribute ng-trim exists we will avoid trimming
  19515. // If input type is 'password', the value is never trimmed
  19516. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  19517. value = trim(value);
  19518. }
  19519. // If a control is suffering from bad input (due to native validators), browsers discard its
  19520. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  19521. // control's value is the same empty value twice in a row.
  19522. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  19523. ctrl.$setViewValue(value, event);
  19524. }
  19525. };
  19526. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  19527. // input event on backspace, delete or cut
  19528. if ($sniffer.hasEvent('input')) {
  19529. element.on('input', listener);
  19530. } else {
  19531. var timeout;
  19532. var deferListener = function(ev, input, origValue) {
  19533. if (!timeout) {
  19534. timeout = $browser.defer(function() {
  19535. timeout = null;
  19536. if (!input || input.value !== origValue) {
  19537. listener(ev);
  19538. }
  19539. });
  19540. }
  19541. };
  19542. element.on('keydown', function(event) {
  19543. var key = event.keyCode;
  19544. // ignore
  19545. // command modifiers arrows
  19546. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  19547. deferListener(event, this, this.value);
  19548. });
  19549. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  19550. if ($sniffer.hasEvent('paste')) {
  19551. element.on('paste cut', deferListener);
  19552. }
  19553. }
  19554. // if user paste into input using mouse on older browser
  19555. // or form autocomplete on newer browser, we need "change" event to catch it
  19556. element.on('change', listener);
  19557. ctrl.$render = function() {
  19558. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  19559. };
  19560. }
  19561. function weekParser(isoWeek, existingDate) {
  19562. if (isDate(isoWeek)) {
  19563. return isoWeek;
  19564. }
  19565. if (isString(isoWeek)) {
  19566. WEEK_REGEXP.lastIndex = 0;
  19567. var parts = WEEK_REGEXP.exec(isoWeek);
  19568. if (parts) {
  19569. var year = +parts[1],
  19570. week = +parts[2],
  19571. hours = 0,
  19572. minutes = 0,
  19573. seconds = 0,
  19574. milliseconds = 0,
  19575. firstThurs = getFirstThursdayOfYear(year),
  19576. addDays = (week - 1) * 7;
  19577. if (existingDate) {
  19578. hours = existingDate.getHours();
  19579. minutes = existingDate.getMinutes();
  19580. seconds = existingDate.getSeconds();
  19581. milliseconds = existingDate.getMilliseconds();
  19582. }
  19583. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  19584. }
  19585. }
  19586. return NaN;
  19587. }
  19588. function createDateParser(regexp, mapping) {
  19589. return function(iso, date) {
  19590. var parts, map;
  19591. if (isDate(iso)) {
  19592. return iso;
  19593. }
  19594. if (isString(iso)) {
  19595. // When a date is JSON'ified to wraps itself inside of an extra
  19596. // set of double quotes. This makes the date parsing code unable
  19597. // to match the date string and parse it as a date.
  19598. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  19599. iso = iso.substring(1, iso.length - 1);
  19600. }
  19601. if (ISO_DATE_REGEXP.test(iso)) {
  19602. return new Date(iso);
  19603. }
  19604. regexp.lastIndex = 0;
  19605. parts = regexp.exec(iso);
  19606. if (parts) {
  19607. parts.shift();
  19608. if (date) {
  19609. map = {
  19610. yyyy: date.getFullYear(),
  19611. MM: date.getMonth() + 1,
  19612. dd: date.getDate(),
  19613. HH: date.getHours(),
  19614. mm: date.getMinutes(),
  19615. ss: date.getSeconds(),
  19616. sss: date.getMilliseconds() / 1000
  19617. };
  19618. } else {
  19619. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  19620. }
  19621. forEach(parts, function(part, index) {
  19622. if (index < mapping.length) {
  19623. map[mapping[index]] = +part;
  19624. }
  19625. });
  19626. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  19627. }
  19628. }
  19629. return NaN;
  19630. };
  19631. }
  19632. function createDateInputType(type, regexp, parseDate, format) {
  19633. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  19634. badInputChecker(scope, element, attr, ctrl);
  19635. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19636. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  19637. var previousDate;
  19638. ctrl.$$parserName = type;
  19639. ctrl.$parsers.push(function(value) {
  19640. if (ctrl.$isEmpty(value)) return null;
  19641. if (regexp.test(value)) {
  19642. // Note: We cannot read ctrl.$modelValue, as there might be a different
  19643. // parser/formatter in the processing chain so that the model
  19644. // contains some different data format!
  19645. var parsedDate = parseDate(value, previousDate);
  19646. if (timezone) {
  19647. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  19648. }
  19649. return parsedDate;
  19650. }
  19651. return undefined;
  19652. });
  19653. ctrl.$formatters.push(function(value) {
  19654. if (value && !isDate(value)) {
  19655. throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  19656. }
  19657. if (isValidDate(value)) {
  19658. previousDate = value;
  19659. if (previousDate && timezone) {
  19660. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  19661. }
  19662. return $filter('date')(value, format, timezone);
  19663. } else {
  19664. previousDate = null;
  19665. return '';
  19666. }
  19667. });
  19668. if (isDefined(attr.min) || attr.ngMin) {
  19669. var minVal;
  19670. ctrl.$validators.min = function(value) {
  19671. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  19672. };
  19673. attr.$observe('min', function(val) {
  19674. minVal = parseObservedDateValue(val);
  19675. ctrl.$validate();
  19676. });
  19677. }
  19678. if (isDefined(attr.max) || attr.ngMax) {
  19679. var maxVal;
  19680. ctrl.$validators.max = function(value) {
  19681. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  19682. };
  19683. attr.$observe('max', function(val) {
  19684. maxVal = parseObservedDateValue(val);
  19685. ctrl.$validate();
  19686. });
  19687. }
  19688. function isValidDate(value) {
  19689. // Invalid Date: getTime() returns NaN
  19690. return value && !(value.getTime && value.getTime() !== value.getTime());
  19691. }
  19692. function parseObservedDateValue(val) {
  19693. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  19694. }
  19695. };
  19696. }
  19697. function badInputChecker(scope, element, attr, ctrl) {
  19698. var node = element[0];
  19699. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  19700. if (nativeValidation) {
  19701. ctrl.$parsers.push(function(value) {
  19702. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  19703. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  19704. // - also sets validity.badInput (should only be validity.typeMismatch).
  19705. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  19706. // - can ignore this case as we can still read out the erroneous email...
  19707. return validity.badInput && !validity.typeMismatch ? undefined : value;
  19708. });
  19709. }
  19710. }
  19711. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19712. badInputChecker(scope, element, attr, ctrl);
  19713. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19714. ctrl.$$parserName = 'number';
  19715. ctrl.$parsers.push(function(value) {
  19716. if (ctrl.$isEmpty(value)) return null;
  19717. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  19718. return undefined;
  19719. });
  19720. ctrl.$formatters.push(function(value) {
  19721. if (!ctrl.$isEmpty(value)) {
  19722. if (!isNumber(value)) {
  19723. throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  19724. }
  19725. value = value.toString();
  19726. }
  19727. return value;
  19728. });
  19729. if (isDefined(attr.min) || attr.ngMin) {
  19730. var minVal;
  19731. ctrl.$validators.min = function(value) {
  19732. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  19733. };
  19734. attr.$observe('min', function(val) {
  19735. if (isDefined(val) && !isNumber(val)) {
  19736. val = parseFloat(val, 10);
  19737. }
  19738. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19739. // TODO(matsko): implement validateLater to reduce number of validations
  19740. ctrl.$validate();
  19741. });
  19742. }
  19743. if (isDefined(attr.max) || attr.ngMax) {
  19744. var maxVal;
  19745. ctrl.$validators.max = function(value) {
  19746. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  19747. };
  19748. attr.$observe('max', function(val) {
  19749. if (isDefined(val) && !isNumber(val)) {
  19750. val = parseFloat(val, 10);
  19751. }
  19752. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19753. // TODO(matsko): implement validateLater to reduce number of validations
  19754. ctrl.$validate();
  19755. });
  19756. }
  19757. }
  19758. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19759. // Note: no badInputChecker here by purpose as `url` is only a validation
  19760. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19761. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19762. stringBasedInputType(ctrl);
  19763. ctrl.$$parserName = 'url';
  19764. ctrl.$validators.url = function(modelValue, viewValue) {
  19765. var value = modelValue || viewValue;
  19766. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  19767. };
  19768. }
  19769. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19770. // Note: no badInputChecker here by purpose as `url` is only a validation
  19771. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19772. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19773. stringBasedInputType(ctrl);
  19774. ctrl.$$parserName = 'email';
  19775. ctrl.$validators.email = function(modelValue, viewValue) {
  19776. var value = modelValue || viewValue;
  19777. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  19778. };
  19779. }
  19780. function radioInputType(scope, element, attr, ctrl) {
  19781. // make the name unique, if not defined
  19782. if (isUndefined(attr.name)) {
  19783. element.attr('name', nextUid());
  19784. }
  19785. var listener = function(ev) {
  19786. if (element[0].checked) {
  19787. ctrl.$setViewValue(attr.value, ev && ev.type);
  19788. }
  19789. };
  19790. element.on('click', listener);
  19791. ctrl.$render = function() {
  19792. var value = attr.value;
  19793. element[0].checked = (value == ctrl.$viewValue);
  19794. };
  19795. attr.$observe('value', ctrl.$render);
  19796. }
  19797. function parseConstantExpr($parse, context, name, expression, fallback) {
  19798. var parseFn;
  19799. if (isDefined(expression)) {
  19800. parseFn = $parse(expression);
  19801. if (!parseFn.constant) {
  19802. throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  19803. '`{1}`.', name, expression);
  19804. }
  19805. return parseFn(context);
  19806. }
  19807. return fallback;
  19808. }
  19809. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  19810. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  19811. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  19812. var listener = function(ev) {
  19813. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  19814. };
  19815. element.on('click', listener);
  19816. ctrl.$render = function() {
  19817. element[0].checked = ctrl.$viewValue;
  19818. };
  19819. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  19820. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  19821. // it to a boolean.
  19822. ctrl.$isEmpty = function(value) {
  19823. return value === false;
  19824. };
  19825. ctrl.$formatters.push(function(value) {
  19826. return equals(value, trueValue);
  19827. });
  19828. ctrl.$parsers.push(function(value) {
  19829. return value ? trueValue : falseValue;
  19830. });
  19831. }
  19832. /**
  19833. * @ngdoc directive
  19834. * @name textarea
  19835. * @restrict E
  19836. *
  19837. * @description
  19838. * HTML textarea element control with angular data-binding. The data-binding and validation
  19839. * properties of this element are exactly the same as those of the
  19840. * {@link ng.directive:input input element}.
  19841. *
  19842. * @param {string} ngModel Assignable angular expression to data-bind to.
  19843. * @param {string=} name Property name of the form under which the control is published.
  19844. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19845. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19846. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19847. * `required` when you want to data-bind to the `required` attribute.
  19848. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19849. * minlength.
  19850. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19851. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  19852. * length.
  19853. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19854. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19855. * If the expression evaluates to a RegExp object, then this is used directly.
  19856. * If the expression evaluates to a string, then it will be converted to a RegExp
  19857. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19858. * `new RegExp('^abc$')`.<br />
  19859. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19860. * start at the index of the last search's match, thus not taking the whole input value into
  19861. * account.
  19862. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19863. * interaction with the input element.
  19864. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19865. */
  19866. /**
  19867. * @ngdoc directive
  19868. * @name input
  19869. * @restrict E
  19870. *
  19871. * @description
  19872. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  19873. * input state control, and validation.
  19874. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  19875. *
  19876. * <div class="alert alert-warning">
  19877. * **Note:** Not every feature offered is available for all input types.
  19878. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  19879. * </div>
  19880. *
  19881. * @param {string} ngModel Assignable angular expression to data-bind to.
  19882. * @param {string=} name Property name of the form under which the control is published.
  19883. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19884. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  19885. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19886. * minlength.
  19887. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19888. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  19889. * length.
  19890. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19891. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19892. * If the expression evaluates to a RegExp object, then this is used directly.
  19893. * If the expression evaluates to a string, then it will be converted to a RegExp
  19894. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19895. * `new RegExp('^abc$')`.<br />
  19896. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19897. * start at the index of the last search's match, thus not taking the whole input value into
  19898. * account.
  19899. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19900. * interaction with the input element.
  19901. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19902. * This parameter is ignored for input[type=password] controls, which will never trim the
  19903. * input.
  19904. *
  19905. * @example
  19906. <example name="input-directive" module="inputExample">
  19907. <file name="index.html">
  19908. <script>
  19909. angular.module('inputExample', [])
  19910. .controller('ExampleController', ['$scope', function($scope) {
  19911. $scope.user = {name: 'guest', last: 'visitor'};
  19912. }]);
  19913. </script>
  19914. <div ng-controller="ExampleController">
  19915. <form name="myForm">
  19916. <label>
  19917. User name:
  19918. <input type="text" name="userName" ng-model="user.name" required>
  19919. </label>
  19920. <div role="alert">
  19921. <span class="error" ng-show="myForm.userName.$error.required">
  19922. Required!</span>
  19923. </div>
  19924. <label>
  19925. Last name:
  19926. <input type="text" name="lastName" ng-model="user.last"
  19927. ng-minlength="3" ng-maxlength="10">
  19928. </label>
  19929. <div role="alert">
  19930. <span class="error" ng-show="myForm.lastName.$error.minlength">
  19931. Too short!</span>
  19932. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  19933. Too long!</span>
  19934. </div>
  19935. </form>
  19936. <hr>
  19937. <tt>user = {{user}}</tt><br/>
  19938. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  19939. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  19940. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  19941. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  19942. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19943. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19944. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  19945. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  19946. </div>
  19947. </file>
  19948. <file name="protractor.js" type="protractor">
  19949. var user = element(by.exactBinding('user'));
  19950. var userNameValid = element(by.binding('myForm.userName.$valid'));
  19951. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  19952. var lastNameError = element(by.binding('myForm.lastName.$error'));
  19953. var formValid = element(by.binding('myForm.$valid'));
  19954. var userNameInput = element(by.model('user.name'));
  19955. var userLastInput = element(by.model('user.last'));
  19956. it('should initialize to model', function() {
  19957. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  19958. expect(userNameValid.getText()).toContain('true');
  19959. expect(formValid.getText()).toContain('true');
  19960. });
  19961. it('should be invalid if empty when required', function() {
  19962. userNameInput.clear();
  19963. userNameInput.sendKeys('');
  19964. expect(user.getText()).toContain('{"last":"visitor"}');
  19965. expect(userNameValid.getText()).toContain('false');
  19966. expect(formValid.getText()).toContain('false');
  19967. });
  19968. it('should be valid if empty when min length is set', function() {
  19969. userLastInput.clear();
  19970. userLastInput.sendKeys('');
  19971. expect(user.getText()).toContain('{"name":"guest","last":""}');
  19972. expect(lastNameValid.getText()).toContain('true');
  19973. expect(formValid.getText()).toContain('true');
  19974. });
  19975. it('should be invalid if less than required min length', function() {
  19976. userLastInput.clear();
  19977. userLastInput.sendKeys('xx');
  19978. expect(user.getText()).toContain('{"name":"guest"}');
  19979. expect(lastNameValid.getText()).toContain('false');
  19980. expect(lastNameError.getText()).toContain('minlength');
  19981. expect(formValid.getText()).toContain('false');
  19982. });
  19983. it('should be invalid if longer than max length', function() {
  19984. userLastInput.clear();
  19985. userLastInput.sendKeys('some ridiculously long name');
  19986. expect(user.getText()).toContain('{"name":"guest"}');
  19987. expect(lastNameValid.getText()).toContain('false');
  19988. expect(lastNameError.getText()).toContain('maxlength');
  19989. expect(formValid.getText()).toContain('false');
  19990. });
  19991. </file>
  19992. </example>
  19993. */
  19994. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  19995. function($browser, $sniffer, $filter, $parse) {
  19996. return {
  19997. restrict: 'E',
  19998. require: ['?ngModel'],
  19999. link: {
  20000. pre: function(scope, element, attr, ctrls) {
  20001. if (ctrls[0]) {
  20002. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  20003. $browser, $filter, $parse);
  20004. }
  20005. }
  20006. }
  20007. };
  20008. }];
  20009. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  20010. /**
  20011. * @ngdoc directive
  20012. * @name ngValue
  20013. *
  20014. * @description
  20015. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  20016. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  20017. * the bound value.
  20018. *
  20019. * `ngValue` is useful when dynamically generating lists of radio buttons using
  20020. * {@link ngRepeat `ngRepeat`}, as shown below.
  20021. *
  20022. * Likewise, `ngValue` can be used to generate `<option>` elements for
  20023. * the {@link select `select`} element. In that case however, only strings are supported
  20024. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  20025. * Support for `select` models with non-string values is available via `ngOptions`.
  20026. *
  20027. * @element input
  20028. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  20029. * of the `input` element
  20030. *
  20031. * @example
  20032. <example name="ngValue-directive" module="valueExample">
  20033. <file name="index.html">
  20034. <script>
  20035. angular.module('valueExample', [])
  20036. .controller('ExampleController', ['$scope', function($scope) {
  20037. $scope.names = ['pizza', 'unicorns', 'robots'];
  20038. $scope.my = { favorite: 'unicorns' };
  20039. }]);
  20040. </script>
  20041. <form ng-controller="ExampleController">
  20042. <h2>Which is your favorite?</h2>
  20043. <label ng-repeat="name in names" for="{{name}}">
  20044. {{name}}
  20045. <input type="radio"
  20046. ng-model="my.favorite"
  20047. ng-value="name"
  20048. id="{{name}}"
  20049. name="favorite">
  20050. </label>
  20051. <div>You chose {{my.favorite}}</div>
  20052. </form>
  20053. </file>
  20054. <file name="protractor.js" type="protractor">
  20055. var favorite = element(by.binding('my.favorite'));
  20056. it('should initialize to model', function() {
  20057. expect(favorite.getText()).toContain('unicorns');
  20058. });
  20059. it('should bind the values to the inputs', function() {
  20060. element.all(by.model('my.favorite')).get(0).click();
  20061. expect(favorite.getText()).toContain('pizza');
  20062. });
  20063. </file>
  20064. </example>
  20065. */
  20066. var ngValueDirective = function() {
  20067. return {
  20068. restrict: 'A',
  20069. priority: 100,
  20070. compile: function(tpl, tplAttr) {
  20071. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  20072. return function ngValueConstantLink(scope, elm, attr) {
  20073. attr.$set('value', scope.$eval(attr.ngValue));
  20074. };
  20075. } else {
  20076. return function ngValueLink(scope, elm, attr) {
  20077. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  20078. attr.$set('value', value);
  20079. });
  20080. };
  20081. }
  20082. }
  20083. };
  20084. };
  20085. /**
  20086. * @ngdoc directive
  20087. * @name ngBind
  20088. * @restrict AC
  20089. *
  20090. * @description
  20091. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  20092. * with the value of a given expression, and to update the text content when the value of that
  20093. * expression changes.
  20094. *
  20095. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  20096. * `{{ expression }}` which is similar but less verbose.
  20097. *
  20098. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  20099. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  20100. * element attribute, it makes the bindings invisible to the user while the page is loading.
  20101. *
  20102. * An alternative solution to this problem would be using the
  20103. * {@link ng.directive:ngCloak ngCloak} directive.
  20104. *
  20105. *
  20106. * @element ANY
  20107. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  20108. *
  20109. * @example
  20110. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  20111. <example module="bindExample">
  20112. <file name="index.html">
  20113. <script>
  20114. angular.module('bindExample', [])
  20115. .controller('ExampleController', ['$scope', function($scope) {
  20116. $scope.name = 'Whirled';
  20117. }]);
  20118. </script>
  20119. <div ng-controller="ExampleController">
  20120. <label>Enter name: <input type="text" ng-model="name"></label><br>
  20121. Hello <span ng-bind="name"></span>!
  20122. </div>
  20123. </file>
  20124. <file name="protractor.js" type="protractor">
  20125. it('should check ng-bind', function() {
  20126. var nameInput = element(by.model('name'));
  20127. expect(element(by.binding('name')).getText()).toBe('Whirled');
  20128. nameInput.clear();
  20129. nameInput.sendKeys('world');
  20130. expect(element(by.binding('name')).getText()).toBe('world');
  20131. });
  20132. </file>
  20133. </example>
  20134. */
  20135. var ngBindDirective = ['$compile', function($compile) {
  20136. return {
  20137. restrict: 'AC',
  20138. compile: function ngBindCompile(templateElement) {
  20139. $compile.$$addBindingClass(templateElement);
  20140. return function ngBindLink(scope, element, attr) {
  20141. $compile.$$addBindingInfo(element, attr.ngBind);
  20142. element = element[0];
  20143. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  20144. element.textContent = value === undefined ? '' : value;
  20145. });
  20146. };
  20147. }
  20148. };
  20149. }];
  20150. /**
  20151. * @ngdoc directive
  20152. * @name ngBindTemplate
  20153. *
  20154. * @description
  20155. * The `ngBindTemplate` directive specifies that the element
  20156. * text content should be replaced with the interpolation of the template
  20157. * in the `ngBindTemplate` attribute.
  20158. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  20159. * expressions. This directive is needed since some HTML elements
  20160. * (such as TITLE and OPTION) cannot contain SPAN elements.
  20161. *
  20162. * @element ANY
  20163. * @param {string} ngBindTemplate template of form
  20164. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  20165. *
  20166. * @example
  20167. * Try it here: enter text in text box and watch the greeting change.
  20168. <example module="bindExample">
  20169. <file name="index.html">
  20170. <script>
  20171. angular.module('bindExample', [])
  20172. .controller('ExampleController', ['$scope', function($scope) {
  20173. $scope.salutation = 'Hello';
  20174. $scope.name = 'World';
  20175. }]);
  20176. </script>
  20177. <div ng-controller="ExampleController">
  20178. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  20179. <label>Name: <input type="text" ng-model="name"></label><br>
  20180. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  20181. </div>
  20182. </file>
  20183. <file name="protractor.js" type="protractor">
  20184. it('should check ng-bind', function() {
  20185. var salutationElem = element(by.binding('salutation'));
  20186. var salutationInput = element(by.model('salutation'));
  20187. var nameInput = element(by.model('name'));
  20188. expect(salutationElem.getText()).toBe('Hello World!');
  20189. salutationInput.clear();
  20190. salutationInput.sendKeys('Greetings');
  20191. nameInput.clear();
  20192. nameInput.sendKeys('user');
  20193. expect(salutationElem.getText()).toBe('Greetings user!');
  20194. });
  20195. </file>
  20196. </example>
  20197. */
  20198. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  20199. return {
  20200. compile: function ngBindTemplateCompile(templateElement) {
  20201. $compile.$$addBindingClass(templateElement);
  20202. return function ngBindTemplateLink(scope, element, attr) {
  20203. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  20204. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  20205. element = element[0];
  20206. attr.$observe('ngBindTemplate', function(value) {
  20207. element.textContent = value === undefined ? '' : value;
  20208. });
  20209. };
  20210. }
  20211. };
  20212. }];
  20213. /**
  20214. * @ngdoc directive
  20215. * @name ngBindHtml
  20216. *
  20217. * @description
  20218. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  20219. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  20220. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  20221. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  20222. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  20223. *
  20224. * You may also bypass sanitization for values you know are safe. To do so, bind to
  20225. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  20226. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  20227. *
  20228. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  20229. * will have an exception (instead of an exploit.)
  20230. *
  20231. * @element ANY
  20232. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  20233. *
  20234. * @example
  20235. <example module="bindHtmlExample" deps="angular-sanitize.js">
  20236. <file name="index.html">
  20237. <div ng-controller="ExampleController">
  20238. <p ng-bind-html="myHTML"></p>
  20239. </div>
  20240. </file>
  20241. <file name="script.js">
  20242. angular.module('bindHtmlExample', ['ngSanitize'])
  20243. .controller('ExampleController', ['$scope', function($scope) {
  20244. $scope.myHTML =
  20245. 'I am an <code>HTML</code>string with ' +
  20246. '<a href="#">links!</a> and other <em>stuff</em>';
  20247. }]);
  20248. </file>
  20249. <file name="protractor.js" type="protractor">
  20250. it('should check ng-bind-html', function() {
  20251. expect(element(by.binding('myHTML')).getText()).toBe(
  20252. 'I am an HTMLstring with links! and other stuff');
  20253. });
  20254. </file>
  20255. </example>
  20256. */
  20257. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  20258. return {
  20259. restrict: 'A',
  20260. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  20261. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  20262. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  20263. return (value || '').toString();
  20264. });
  20265. $compile.$$addBindingClass(tElement);
  20266. return function ngBindHtmlLink(scope, element, attr) {
  20267. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  20268. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  20269. // we re-evaluate the expr because we want a TrustedValueHolderType
  20270. // for $sce, not a string
  20271. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  20272. });
  20273. };
  20274. }
  20275. };
  20276. }];
  20277. /**
  20278. * @ngdoc directive
  20279. * @name ngChange
  20280. *
  20281. * @description
  20282. * Evaluate the given expression when the user changes the input.
  20283. * The expression is evaluated immediately, unlike the JavaScript onchange event
  20284. * which only triggers at the end of a change (usually, when the user leaves the
  20285. * form element or presses the return key).
  20286. *
  20287. * The `ngChange` expression is only evaluated when a change in the input value causes
  20288. * a new value to be committed to the model.
  20289. *
  20290. * It will not be evaluated:
  20291. * * if the value returned from the `$parsers` transformation pipeline has not changed
  20292. * * if the input has continued to be invalid since the model will stay `null`
  20293. * * if the model is changed programmatically and not by a change to the input value
  20294. *
  20295. *
  20296. * Note, this directive requires `ngModel` to be present.
  20297. *
  20298. * @element input
  20299. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  20300. * in input value.
  20301. *
  20302. * @example
  20303. * <example name="ngChange-directive" module="changeExample">
  20304. * <file name="index.html">
  20305. * <script>
  20306. * angular.module('changeExample', [])
  20307. * .controller('ExampleController', ['$scope', function($scope) {
  20308. * $scope.counter = 0;
  20309. * $scope.change = function() {
  20310. * $scope.counter++;
  20311. * };
  20312. * }]);
  20313. * </script>
  20314. * <div ng-controller="ExampleController">
  20315. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  20316. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  20317. * <label for="ng-change-example2">Confirmed</label><br />
  20318. * <tt>debug = {{confirmed}}</tt><br/>
  20319. * <tt>counter = {{counter}}</tt><br/>
  20320. * </div>
  20321. * </file>
  20322. * <file name="protractor.js" type="protractor">
  20323. * var counter = element(by.binding('counter'));
  20324. * var debug = element(by.binding('confirmed'));
  20325. *
  20326. * it('should evaluate the expression if changing from view', function() {
  20327. * expect(counter.getText()).toContain('0');
  20328. *
  20329. * element(by.id('ng-change-example1')).click();
  20330. *
  20331. * expect(counter.getText()).toContain('1');
  20332. * expect(debug.getText()).toContain('true');
  20333. * });
  20334. *
  20335. * it('should not evaluate the expression if changing from model', function() {
  20336. * element(by.id('ng-change-example2')).click();
  20337. * expect(counter.getText()).toContain('0');
  20338. * expect(debug.getText()).toContain('true');
  20339. * });
  20340. * </file>
  20341. * </example>
  20342. */
  20343. var ngChangeDirective = valueFn({
  20344. restrict: 'A',
  20345. require: 'ngModel',
  20346. link: function(scope, element, attr, ctrl) {
  20347. ctrl.$viewChangeListeners.push(function() {
  20348. scope.$eval(attr.ngChange);
  20349. });
  20350. }
  20351. });
  20352. function classDirective(name, selector) {
  20353. name = 'ngClass' + name;
  20354. return ['$animate', function($animate) {
  20355. return {
  20356. restrict: 'AC',
  20357. link: function(scope, element, attr) {
  20358. var oldVal;
  20359. scope.$watch(attr[name], ngClassWatchAction, true);
  20360. attr.$observe('class', function(value) {
  20361. ngClassWatchAction(scope.$eval(attr[name]));
  20362. });
  20363. if (name !== 'ngClass') {
  20364. scope.$watch('$index', function($index, old$index) {
  20365. // jshint bitwise: false
  20366. var mod = $index & 1;
  20367. if (mod !== (old$index & 1)) {
  20368. var classes = arrayClasses(scope.$eval(attr[name]));
  20369. mod === selector ?
  20370. addClasses(classes) :
  20371. removeClasses(classes);
  20372. }
  20373. });
  20374. }
  20375. function addClasses(classes) {
  20376. var newClasses = digestClassCounts(classes, 1);
  20377. attr.$addClass(newClasses);
  20378. }
  20379. function removeClasses(classes) {
  20380. var newClasses = digestClassCounts(classes, -1);
  20381. attr.$removeClass(newClasses);
  20382. }
  20383. function digestClassCounts(classes, count) {
  20384. // Use createMap() to prevent class assumptions involving property
  20385. // names in Object.prototype
  20386. var classCounts = element.data('$classCounts') || createMap();
  20387. var classesToUpdate = [];
  20388. forEach(classes, function(className) {
  20389. if (count > 0 || classCounts[className]) {
  20390. classCounts[className] = (classCounts[className] || 0) + count;
  20391. if (classCounts[className] === +(count > 0)) {
  20392. classesToUpdate.push(className);
  20393. }
  20394. }
  20395. });
  20396. element.data('$classCounts', classCounts);
  20397. return classesToUpdate.join(' ');
  20398. }
  20399. function updateClasses(oldClasses, newClasses) {
  20400. var toAdd = arrayDifference(newClasses, oldClasses);
  20401. var toRemove = arrayDifference(oldClasses, newClasses);
  20402. toAdd = digestClassCounts(toAdd, 1);
  20403. toRemove = digestClassCounts(toRemove, -1);
  20404. if (toAdd && toAdd.length) {
  20405. $animate.addClass(element, toAdd);
  20406. }
  20407. if (toRemove && toRemove.length) {
  20408. $animate.removeClass(element, toRemove);
  20409. }
  20410. }
  20411. function ngClassWatchAction(newVal) {
  20412. if (selector === true || scope.$index % 2 === selector) {
  20413. var newClasses = arrayClasses(newVal || []);
  20414. if (!oldVal) {
  20415. addClasses(newClasses);
  20416. } else if (!equals(newVal,oldVal)) {
  20417. var oldClasses = arrayClasses(oldVal);
  20418. updateClasses(oldClasses, newClasses);
  20419. }
  20420. }
  20421. oldVal = shallowCopy(newVal);
  20422. }
  20423. }
  20424. };
  20425. function arrayDifference(tokens1, tokens2) {
  20426. var values = [];
  20427. outer:
  20428. for (var i = 0; i < tokens1.length; i++) {
  20429. var token = tokens1[i];
  20430. for (var j = 0; j < tokens2.length; j++) {
  20431. if (token == tokens2[j]) continue outer;
  20432. }
  20433. values.push(token);
  20434. }
  20435. return values;
  20436. }
  20437. function arrayClasses(classVal) {
  20438. var classes = [];
  20439. if (isArray(classVal)) {
  20440. forEach(classVal, function(v) {
  20441. classes = classes.concat(arrayClasses(v));
  20442. });
  20443. return classes;
  20444. } else if (isString(classVal)) {
  20445. return classVal.split(' ');
  20446. } else if (isObject(classVal)) {
  20447. forEach(classVal, function(v, k) {
  20448. if (v) {
  20449. classes = classes.concat(k.split(' '));
  20450. }
  20451. });
  20452. return classes;
  20453. }
  20454. return classVal;
  20455. }
  20456. }];
  20457. }
  20458. /**
  20459. * @ngdoc directive
  20460. * @name ngClass
  20461. * @restrict AC
  20462. *
  20463. * @description
  20464. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  20465. * an expression that represents all classes to be added.
  20466. *
  20467. * The directive operates in three different ways, depending on which of three types the expression
  20468. * evaluates to:
  20469. *
  20470. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  20471. * names.
  20472. *
  20473. * 2. If the expression evaluates to an object, then for each key-value pair of the
  20474. * object with a truthy value the corresponding key is used as a class name.
  20475. *
  20476. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  20477. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  20478. * to give you more control over what CSS classes appear. See the code below for an example of this.
  20479. *
  20480. *
  20481. * The directive won't add duplicate classes if a particular class was already set.
  20482. *
  20483. * When the expression changes, the previously added classes are removed and only then are the
  20484. * new classes added.
  20485. *
  20486. * @animations
  20487. * **add** - happens just before the class is applied to the elements
  20488. *
  20489. * **remove** - happens just before the class is removed from the element
  20490. *
  20491. * @element ANY
  20492. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  20493. * of the evaluation can be a string representing space delimited class
  20494. * names, an array, or a map of class names to boolean values. In the case of a map, the
  20495. * names of the properties whose values are truthy will be added as css classes to the
  20496. * element.
  20497. *
  20498. * @example Example that demonstrates basic bindings via ngClass directive.
  20499. <example>
  20500. <file name="index.html">
  20501. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  20502. <label>
  20503. <input type="checkbox" ng-model="deleted">
  20504. deleted (apply "strike" class)
  20505. </label><br>
  20506. <label>
  20507. <input type="checkbox" ng-model="important">
  20508. important (apply "bold" class)
  20509. </label><br>
  20510. <label>
  20511. <input type="checkbox" ng-model="error">
  20512. error (apply "has-error" class)
  20513. </label>
  20514. <hr>
  20515. <p ng-class="style">Using String Syntax</p>
  20516. <input type="text" ng-model="style"
  20517. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  20518. <hr>
  20519. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  20520. <input ng-model="style1"
  20521. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  20522. <input ng-model="style2"
  20523. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  20524. <input ng-model="style3"
  20525. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  20526. <hr>
  20527. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  20528. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  20529. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  20530. </file>
  20531. <file name="style.css">
  20532. .strike {
  20533. text-decoration: line-through;
  20534. }
  20535. .bold {
  20536. font-weight: bold;
  20537. }
  20538. .red {
  20539. color: red;
  20540. }
  20541. .has-error {
  20542. color: red;
  20543. background-color: yellow;
  20544. }
  20545. .orange {
  20546. color: orange;
  20547. }
  20548. </file>
  20549. <file name="protractor.js" type="protractor">
  20550. var ps = element.all(by.css('p'));
  20551. it('should let you toggle the class', function() {
  20552. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  20553. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  20554. element(by.model('important')).click();
  20555. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  20556. element(by.model('error')).click();
  20557. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  20558. });
  20559. it('should let you toggle string example', function() {
  20560. expect(ps.get(1).getAttribute('class')).toBe('');
  20561. element(by.model('style')).clear();
  20562. element(by.model('style')).sendKeys('red');
  20563. expect(ps.get(1).getAttribute('class')).toBe('red');
  20564. });
  20565. it('array example should have 3 classes', function() {
  20566. expect(ps.get(2).getAttribute('class')).toBe('');
  20567. element(by.model('style1')).sendKeys('bold');
  20568. element(by.model('style2')).sendKeys('strike');
  20569. element(by.model('style3')).sendKeys('red');
  20570. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  20571. });
  20572. it('array with map example should have 2 classes', function() {
  20573. expect(ps.last().getAttribute('class')).toBe('');
  20574. element(by.model('style4')).sendKeys('bold');
  20575. element(by.model('warning')).click();
  20576. expect(ps.last().getAttribute('class')).toBe('bold orange');
  20577. });
  20578. </file>
  20579. </example>
  20580. ## Animations
  20581. The example below demonstrates how to perform animations using ngClass.
  20582. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20583. <file name="index.html">
  20584. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  20585. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  20586. <br>
  20587. <span class="base-class" ng-class="myVar">Sample Text</span>
  20588. </file>
  20589. <file name="style.css">
  20590. .base-class {
  20591. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20592. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20593. }
  20594. .base-class.my-class {
  20595. color: red;
  20596. font-size:3em;
  20597. }
  20598. </file>
  20599. <file name="protractor.js" type="protractor">
  20600. it('should check ng-class', function() {
  20601. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20602. toMatch(/my-class/);
  20603. element(by.id('setbtn')).click();
  20604. expect(element(by.css('.base-class')).getAttribute('class')).
  20605. toMatch(/my-class/);
  20606. element(by.id('clearbtn')).click();
  20607. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20608. toMatch(/my-class/);
  20609. });
  20610. </file>
  20611. </example>
  20612. ## ngClass and pre-existing CSS3 Transitions/Animations
  20613. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  20614. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  20615. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  20616. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  20617. {@link $animate#removeClass $animate.removeClass}.
  20618. */
  20619. var ngClassDirective = classDirective('', true);
  20620. /**
  20621. * @ngdoc directive
  20622. * @name ngClassOdd
  20623. * @restrict AC
  20624. *
  20625. * @description
  20626. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20627. * {@link ng.directive:ngClass ngClass}, except they work in
  20628. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20629. *
  20630. * This directive can be applied only within the scope of an
  20631. * {@link ng.directive:ngRepeat ngRepeat}.
  20632. *
  20633. * @element ANY
  20634. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  20635. * of the evaluation can be a string representing space delimited class names or an array.
  20636. *
  20637. * @example
  20638. <example>
  20639. <file name="index.html">
  20640. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20641. <li ng-repeat="name in names">
  20642. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20643. {{name}}
  20644. </span>
  20645. </li>
  20646. </ol>
  20647. </file>
  20648. <file name="style.css">
  20649. .odd {
  20650. color: red;
  20651. }
  20652. .even {
  20653. color: blue;
  20654. }
  20655. </file>
  20656. <file name="protractor.js" type="protractor">
  20657. it('should check ng-class-odd and ng-class-even', function() {
  20658. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20659. toMatch(/odd/);
  20660. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20661. toMatch(/even/);
  20662. });
  20663. </file>
  20664. </example>
  20665. */
  20666. var ngClassOddDirective = classDirective('Odd', 0);
  20667. /**
  20668. * @ngdoc directive
  20669. * @name ngClassEven
  20670. * @restrict AC
  20671. *
  20672. * @description
  20673. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20674. * {@link ng.directive:ngClass ngClass}, except they work in
  20675. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20676. *
  20677. * This directive can be applied only within the scope of an
  20678. * {@link ng.directive:ngRepeat ngRepeat}.
  20679. *
  20680. * @element ANY
  20681. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  20682. * result of the evaluation can be a string representing space delimited class names or an array.
  20683. *
  20684. * @example
  20685. <example>
  20686. <file name="index.html">
  20687. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20688. <li ng-repeat="name in names">
  20689. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20690. {{name}} &nbsp; &nbsp; &nbsp;
  20691. </span>
  20692. </li>
  20693. </ol>
  20694. </file>
  20695. <file name="style.css">
  20696. .odd {
  20697. color: red;
  20698. }
  20699. .even {
  20700. color: blue;
  20701. }
  20702. </file>
  20703. <file name="protractor.js" type="protractor">
  20704. it('should check ng-class-odd and ng-class-even', function() {
  20705. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20706. toMatch(/odd/);
  20707. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20708. toMatch(/even/);
  20709. });
  20710. </file>
  20711. </example>
  20712. */
  20713. var ngClassEvenDirective = classDirective('Even', 1);
  20714. /**
  20715. * @ngdoc directive
  20716. * @name ngCloak
  20717. * @restrict AC
  20718. *
  20719. * @description
  20720. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  20721. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  20722. * directive to avoid the undesirable flicker effect caused by the html template display.
  20723. *
  20724. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  20725. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  20726. * of the browser view.
  20727. *
  20728. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  20729. * `angular.min.js`.
  20730. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  20731. *
  20732. * ```css
  20733. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  20734. * display: none !important;
  20735. * }
  20736. * ```
  20737. *
  20738. * When this css rule is loaded by the browser, all html elements (including their children) that
  20739. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  20740. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  20741. * the compiled element visible.
  20742. *
  20743. * For the best result, the `angular.js` script must be loaded in the head section of the html
  20744. * document; alternatively, the css rule above must be included in the external stylesheet of the
  20745. * application.
  20746. *
  20747. * @element ANY
  20748. *
  20749. * @example
  20750. <example>
  20751. <file name="index.html">
  20752. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  20753. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  20754. </file>
  20755. <file name="protractor.js" type="protractor">
  20756. it('should remove the template directive and css class', function() {
  20757. expect($('#template1').getAttribute('ng-cloak')).
  20758. toBeNull();
  20759. expect($('#template2').getAttribute('ng-cloak')).
  20760. toBeNull();
  20761. });
  20762. </file>
  20763. </example>
  20764. *
  20765. */
  20766. var ngCloakDirective = ngDirective({
  20767. compile: function(element, attr) {
  20768. attr.$set('ngCloak', undefined);
  20769. element.removeClass('ng-cloak');
  20770. }
  20771. });
  20772. /**
  20773. * @ngdoc directive
  20774. * @name ngController
  20775. *
  20776. * @description
  20777. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  20778. * supports the principles behind the Model-View-Controller design pattern.
  20779. *
  20780. * MVC components in angular:
  20781. *
  20782. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  20783. * are accessed through bindings.
  20784. * * View — The template (HTML with data bindings) that is rendered into the View.
  20785. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  20786. * logic behind the application to decorate the scope with functions and values
  20787. *
  20788. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  20789. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  20790. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  20791. * and executed twice.
  20792. *
  20793. * @element ANY
  20794. * @scope
  20795. * @priority 500
  20796. * @param {expression} ngController Name of a constructor function registered with the current
  20797. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  20798. * that on the current scope evaluates to a constructor function.
  20799. *
  20800. * The controller instance can be published into a scope property by specifying
  20801. * `ng-controller="as propertyName"`.
  20802. *
  20803. * If the current `$controllerProvider` is configured to use globals (via
  20804. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  20805. * also be the name of a globally accessible constructor function (not recommended).
  20806. *
  20807. * @example
  20808. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  20809. * greeting are methods declared on the controller (see source tab). These methods can
  20810. * easily be called from the angular markup. Any changes to the data are automatically reflected
  20811. * in the View without the need for a manual update.
  20812. *
  20813. * Two different declaration styles are included below:
  20814. *
  20815. * * one binds methods and properties directly onto the controller using `this`:
  20816. * `ng-controller="SettingsController1 as settings"`
  20817. * * one injects `$scope` into the controller:
  20818. * `ng-controller="SettingsController2"`
  20819. *
  20820. * The second option is more common in the Angular community, and is generally used in boilerplates
  20821. * and in this guide. However, there are advantages to binding properties directly to the controller
  20822. * and avoiding scope.
  20823. *
  20824. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  20825. * multiple controllers apply to an element.
  20826. * * If you are writing your controllers as classes you have easier access to the properties and
  20827. * methods, which will appear on the scope, from inside the controller code.
  20828. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  20829. * inheritance masking primitives.
  20830. *
  20831. * This example demonstrates the `controller as` syntax.
  20832. *
  20833. * <example name="ngControllerAs" module="controllerAsExample">
  20834. * <file name="index.html">
  20835. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  20836. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  20837. * <button ng-click="settings.greet()">greet</button><br/>
  20838. * Contact:
  20839. * <ul>
  20840. * <li ng-repeat="contact in settings.contacts">
  20841. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  20842. * <option>phone</option>
  20843. * <option>email</option>
  20844. * </select>
  20845. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  20846. * <button ng-click="settings.clearContact(contact)">clear</button>
  20847. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  20848. * </li>
  20849. * <li><button ng-click="settings.addContact()">add</button></li>
  20850. * </ul>
  20851. * </div>
  20852. * </file>
  20853. * <file name="app.js">
  20854. * angular.module('controllerAsExample', [])
  20855. * .controller('SettingsController1', SettingsController1);
  20856. *
  20857. * function SettingsController1() {
  20858. * this.name = "John Smith";
  20859. * this.contacts = [
  20860. * {type: 'phone', value: '408 555 1212'},
  20861. * {type: 'email', value: 'john.smith@example.org'} ];
  20862. * }
  20863. *
  20864. * SettingsController1.prototype.greet = function() {
  20865. * alert(this.name);
  20866. * };
  20867. *
  20868. * SettingsController1.prototype.addContact = function() {
  20869. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  20870. * };
  20871. *
  20872. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  20873. * var index = this.contacts.indexOf(contactToRemove);
  20874. * this.contacts.splice(index, 1);
  20875. * };
  20876. *
  20877. * SettingsController1.prototype.clearContact = function(contact) {
  20878. * contact.type = 'phone';
  20879. * contact.value = '';
  20880. * };
  20881. * </file>
  20882. * <file name="protractor.js" type="protractor">
  20883. * it('should check controller as', function() {
  20884. * var container = element(by.id('ctrl-as-exmpl'));
  20885. * expect(container.element(by.model('settings.name'))
  20886. * .getAttribute('value')).toBe('John Smith');
  20887. *
  20888. * var firstRepeat =
  20889. * container.element(by.repeater('contact in settings.contacts').row(0));
  20890. * var secondRepeat =
  20891. * container.element(by.repeater('contact in settings.contacts').row(1));
  20892. *
  20893. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20894. * .toBe('408 555 1212');
  20895. *
  20896. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20897. * .toBe('john.smith@example.org');
  20898. *
  20899. * firstRepeat.element(by.buttonText('clear')).click();
  20900. *
  20901. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20902. * .toBe('');
  20903. *
  20904. * container.element(by.buttonText('add')).click();
  20905. *
  20906. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  20907. * .element(by.model('contact.value'))
  20908. * .getAttribute('value'))
  20909. * .toBe('yourname@example.org');
  20910. * });
  20911. * </file>
  20912. * </example>
  20913. *
  20914. * This example demonstrates the "attach to `$scope`" style of controller.
  20915. *
  20916. * <example name="ngController" module="controllerExample">
  20917. * <file name="index.html">
  20918. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  20919. * <label>Name: <input type="text" ng-model="name"/></label>
  20920. * <button ng-click="greet()">greet</button><br/>
  20921. * Contact:
  20922. * <ul>
  20923. * <li ng-repeat="contact in contacts">
  20924. * <select ng-model="contact.type" id="select_{{$index}}">
  20925. * <option>phone</option>
  20926. * <option>email</option>
  20927. * </select>
  20928. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  20929. * <button ng-click="clearContact(contact)">clear</button>
  20930. * <button ng-click="removeContact(contact)">X</button>
  20931. * </li>
  20932. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  20933. * </ul>
  20934. * </div>
  20935. * </file>
  20936. * <file name="app.js">
  20937. * angular.module('controllerExample', [])
  20938. * .controller('SettingsController2', ['$scope', SettingsController2]);
  20939. *
  20940. * function SettingsController2($scope) {
  20941. * $scope.name = "John Smith";
  20942. * $scope.contacts = [
  20943. * {type:'phone', value:'408 555 1212'},
  20944. * {type:'email', value:'john.smith@example.org'} ];
  20945. *
  20946. * $scope.greet = function() {
  20947. * alert($scope.name);
  20948. * };
  20949. *
  20950. * $scope.addContact = function() {
  20951. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  20952. * };
  20953. *
  20954. * $scope.removeContact = function(contactToRemove) {
  20955. * var index = $scope.contacts.indexOf(contactToRemove);
  20956. * $scope.contacts.splice(index, 1);
  20957. * };
  20958. *
  20959. * $scope.clearContact = function(contact) {
  20960. * contact.type = 'phone';
  20961. * contact.value = '';
  20962. * };
  20963. * }
  20964. * </file>
  20965. * <file name="protractor.js" type="protractor">
  20966. * it('should check controller', function() {
  20967. * var container = element(by.id('ctrl-exmpl'));
  20968. *
  20969. * expect(container.element(by.model('name'))
  20970. * .getAttribute('value')).toBe('John Smith');
  20971. *
  20972. * var firstRepeat =
  20973. * container.element(by.repeater('contact in contacts').row(0));
  20974. * var secondRepeat =
  20975. * container.element(by.repeater('contact in contacts').row(1));
  20976. *
  20977. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20978. * .toBe('408 555 1212');
  20979. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20980. * .toBe('john.smith@example.org');
  20981. *
  20982. * firstRepeat.element(by.buttonText('clear')).click();
  20983. *
  20984. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20985. * .toBe('');
  20986. *
  20987. * container.element(by.buttonText('add')).click();
  20988. *
  20989. * expect(container.element(by.repeater('contact in contacts').row(2))
  20990. * .element(by.model('contact.value'))
  20991. * .getAttribute('value'))
  20992. * .toBe('yourname@example.org');
  20993. * });
  20994. * </file>
  20995. *</example>
  20996. */
  20997. var ngControllerDirective = [function() {
  20998. return {
  20999. restrict: 'A',
  21000. scope: true,
  21001. controller: '@',
  21002. priority: 500
  21003. };
  21004. }];
  21005. /**
  21006. * @ngdoc directive
  21007. * @name ngCsp
  21008. *
  21009. * @element html
  21010. * @description
  21011. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  21012. *
  21013. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  21014. *
  21015. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  21016. * For Angular to be CSP compatible there are only two things that we need to do differently:
  21017. *
  21018. * - don't use `Function` constructor to generate optimized value getters
  21019. * - don't inject custom stylesheet into the document
  21020. *
  21021. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  21022. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  21023. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  21024. * be raised.
  21025. *
  21026. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  21027. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  21028. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  21029. *
  21030. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  21031. * autodetection however triggers a CSP error to be logged in the console:
  21032. *
  21033. * ```
  21034. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  21035. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  21036. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  21037. * ```
  21038. *
  21039. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  21040. * directive on the root element of the application or on the `angular.js` script tag, whichever
  21041. * appears first in the html document.
  21042. *
  21043. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  21044. *
  21045. * @example
  21046. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  21047. ```html
  21048. <!doctype html>
  21049. <html ng-app ng-csp>
  21050. ...
  21051. ...
  21052. </html>
  21053. ```
  21054. * @example
  21055. // Note: the suffix `.csp` in the example name triggers
  21056. // csp mode in our http server!
  21057. <example name="example.csp" module="cspExample" ng-csp="true">
  21058. <file name="index.html">
  21059. <div ng-controller="MainController as ctrl">
  21060. <div>
  21061. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  21062. <span id="counter">
  21063. {{ctrl.counter}}
  21064. </span>
  21065. </div>
  21066. <div>
  21067. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  21068. <span id="evilError">
  21069. {{ctrl.evilError}}
  21070. </span>
  21071. </div>
  21072. </div>
  21073. </file>
  21074. <file name="script.js">
  21075. angular.module('cspExample', [])
  21076. .controller('MainController', function() {
  21077. this.counter = 0;
  21078. this.inc = function() {
  21079. this.counter++;
  21080. };
  21081. this.evil = function() {
  21082. // jshint evil:true
  21083. try {
  21084. eval('1+2');
  21085. } catch (e) {
  21086. this.evilError = e.message;
  21087. }
  21088. };
  21089. });
  21090. </file>
  21091. <file name="protractor.js" type="protractor">
  21092. var util, webdriver;
  21093. var incBtn = element(by.id('inc'));
  21094. var counter = element(by.id('counter'));
  21095. var evilBtn = element(by.id('evil'));
  21096. var evilError = element(by.id('evilError'));
  21097. function getAndClearSevereErrors() {
  21098. return browser.manage().logs().get('browser').then(function(browserLog) {
  21099. return browserLog.filter(function(logEntry) {
  21100. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  21101. });
  21102. });
  21103. }
  21104. function clearErrors() {
  21105. getAndClearSevereErrors();
  21106. }
  21107. function expectNoErrors() {
  21108. getAndClearSevereErrors().then(function(filteredLog) {
  21109. expect(filteredLog.length).toEqual(0);
  21110. if (filteredLog.length) {
  21111. console.log('browser console errors: ' + util.inspect(filteredLog));
  21112. }
  21113. });
  21114. }
  21115. function expectError(regex) {
  21116. getAndClearSevereErrors().then(function(filteredLog) {
  21117. var found = false;
  21118. filteredLog.forEach(function(log) {
  21119. if (log.message.match(regex)) {
  21120. found = true;
  21121. }
  21122. });
  21123. if (!found) {
  21124. throw new Error('expected an error that matches ' + regex);
  21125. }
  21126. });
  21127. }
  21128. beforeEach(function() {
  21129. util = require('util');
  21130. webdriver = require('protractor/node_modules/selenium-webdriver');
  21131. });
  21132. // For now, we only test on Chrome,
  21133. // as Safari does not load the page with Protractor's injected scripts,
  21134. // and Firefox webdriver always disables content security policy (#6358)
  21135. if (browser.params.browser !== 'chrome') {
  21136. return;
  21137. }
  21138. it('should not report errors when the page is loaded', function() {
  21139. // clear errors so we are not dependent on previous tests
  21140. clearErrors();
  21141. // Need to reload the page as the page is already loaded when
  21142. // we come here
  21143. browser.driver.getCurrentUrl().then(function(url) {
  21144. browser.get(url);
  21145. });
  21146. expectNoErrors();
  21147. });
  21148. it('should evaluate expressions', function() {
  21149. expect(counter.getText()).toEqual('0');
  21150. incBtn.click();
  21151. expect(counter.getText()).toEqual('1');
  21152. expectNoErrors();
  21153. });
  21154. it('should throw and report an error when using "eval"', function() {
  21155. evilBtn.click();
  21156. expect(evilError.getText()).toMatch(/Content Security Policy/);
  21157. expectError(/Content Security Policy/);
  21158. });
  21159. </file>
  21160. </example>
  21161. */
  21162. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  21163. // bootstrap the system (before $parse is instantiated), for this reason we just have
  21164. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  21165. /**
  21166. * @ngdoc directive
  21167. * @name ngClick
  21168. *
  21169. * @description
  21170. * The ngClick directive allows you to specify custom behavior when
  21171. * an element is clicked.
  21172. *
  21173. * @element ANY
  21174. * @priority 0
  21175. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  21176. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  21177. *
  21178. * @example
  21179. <example>
  21180. <file name="index.html">
  21181. <button ng-click="count = count + 1" ng-init="count=0">
  21182. Increment
  21183. </button>
  21184. <span>
  21185. count: {{count}}
  21186. </span>
  21187. </file>
  21188. <file name="protractor.js" type="protractor">
  21189. it('should check ng-click', function() {
  21190. expect(element(by.binding('count')).getText()).toMatch('0');
  21191. element(by.css('button')).click();
  21192. expect(element(by.binding('count')).getText()).toMatch('1');
  21193. });
  21194. </file>
  21195. </example>
  21196. */
  21197. /*
  21198. * A collection of directives that allows creation of custom event handlers that are defined as
  21199. * angular expressions and are compiled and executed within the current scope.
  21200. */
  21201. var ngEventDirectives = {};
  21202. // For events that might fire synchronously during DOM manipulation
  21203. // we need to execute their event handlers asynchronously using $evalAsync,
  21204. // so that they are not executed in an inconsistent state.
  21205. var forceAsyncEvents = {
  21206. 'blur': true,
  21207. 'focus': true
  21208. };
  21209. forEach(
  21210. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  21211. function(eventName) {
  21212. var directiveName = directiveNormalize('ng-' + eventName);
  21213. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  21214. return {
  21215. restrict: 'A',
  21216. compile: function($element, attr) {
  21217. // We expose the powerful $event object on the scope that provides access to the Window,
  21218. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  21219. // checks at the cost of speed since event handler expressions are not executed as
  21220. // frequently as regular change detection.
  21221. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  21222. return function ngEventHandler(scope, element) {
  21223. element.on(eventName, function(event) {
  21224. var callback = function() {
  21225. fn(scope, {$event:event});
  21226. };
  21227. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  21228. scope.$evalAsync(callback);
  21229. } else {
  21230. scope.$apply(callback);
  21231. }
  21232. });
  21233. };
  21234. }
  21235. };
  21236. }];
  21237. }
  21238. );
  21239. /**
  21240. * @ngdoc directive
  21241. * @name ngDblclick
  21242. *
  21243. * @description
  21244. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  21245. *
  21246. * @element ANY
  21247. * @priority 0
  21248. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  21249. * a dblclick. (The Event object is available as `$event`)
  21250. *
  21251. * @example
  21252. <example>
  21253. <file name="index.html">
  21254. <button ng-dblclick="count = count + 1" ng-init="count=0">
  21255. Increment (on double click)
  21256. </button>
  21257. count: {{count}}
  21258. </file>
  21259. </example>
  21260. */
  21261. /**
  21262. * @ngdoc directive
  21263. * @name ngMousedown
  21264. *
  21265. * @description
  21266. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  21267. *
  21268. * @element ANY
  21269. * @priority 0
  21270. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  21271. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  21272. *
  21273. * @example
  21274. <example>
  21275. <file name="index.html">
  21276. <button ng-mousedown="count = count + 1" ng-init="count=0">
  21277. Increment (on mouse down)
  21278. </button>
  21279. count: {{count}}
  21280. </file>
  21281. </example>
  21282. */
  21283. /**
  21284. * @ngdoc directive
  21285. * @name ngMouseup
  21286. *
  21287. * @description
  21288. * Specify custom behavior on mouseup event.
  21289. *
  21290. * @element ANY
  21291. * @priority 0
  21292. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  21293. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  21294. *
  21295. * @example
  21296. <example>
  21297. <file name="index.html">
  21298. <button ng-mouseup="count = count + 1" ng-init="count=0">
  21299. Increment (on mouse up)
  21300. </button>
  21301. count: {{count}}
  21302. </file>
  21303. </example>
  21304. */
  21305. /**
  21306. * @ngdoc directive
  21307. * @name ngMouseover
  21308. *
  21309. * @description
  21310. * Specify custom behavior on mouseover event.
  21311. *
  21312. * @element ANY
  21313. * @priority 0
  21314. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  21315. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  21316. *
  21317. * @example
  21318. <example>
  21319. <file name="index.html">
  21320. <button ng-mouseover="count = count + 1" ng-init="count=0">
  21321. Increment (when mouse is over)
  21322. </button>
  21323. count: {{count}}
  21324. </file>
  21325. </example>
  21326. */
  21327. /**
  21328. * @ngdoc directive
  21329. * @name ngMouseenter
  21330. *
  21331. * @description
  21332. * Specify custom behavior on mouseenter event.
  21333. *
  21334. * @element ANY
  21335. * @priority 0
  21336. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  21337. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  21338. *
  21339. * @example
  21340. <example>
  21341. <file name="index.html">
  21342. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  21343. Increment (when mouse enters)
  21344. </button>
  21345. count: {{count}}
  21346. </file>
  21347. </example>
  21348. */
  21349. /**
  21350. * @ngdoc directive
  21351. * @name ngMouseleave
  21352. *
  21353. * @description
  21354. * Specify custom behavior on mouseleave event.
  21355. *
  21356. * @element ANY
  21357. * @priority 0
  21358. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  21359. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  21360. *
  21361. * @example
  21362. <example>
  21363. <file name="index.html">
  21364. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  21365. Increment (when mouse leaves)
  21366. </button>
  21367. count: {{count}}
  21368. </file>
  21369. </example>
  21370. */
  21371. /**
  21372. * @ngdoc directive
  21373. * @name ngMousemove
  21374. *
  21375. * @description
  21376. * Specify custom behavior on mousemove event.
  21377. *
  21378. * @element ANY
  21379. * @priority 0
  21380. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  21381. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  21382. *
  21383. * @example
  21384. <example>
  21385. <file name="index.html">
  21386. <button ng-mousemove="count = count + 1" ng-init="count=0">
  21387. Increment (when mouse moves)
  21388. </button>
  21389. count: {{count}}
  21390. </file>
  21391. </example>
  21392. */
  21393. /**
  21394. * @ngdoc directive
  21395. * @name ngKeydown
  21396. *
  21397. * @description
  21398. * Specify custom behavior on keydown event.
  21399. *
  21400. * @element ANY
  21401. * @priority 0
  21402. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  21403. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21404. *
  21405. * @example
  21406. <example>
  21407. <file name="index.html">
  21408. <input ng-keydown="count = count + 1" ng-init="count=0">
  21409. key down count: {{count}}
  21410. </file>
  21411. </example>
  21412. */
  21413. /**
  21414. * @ngdoc directive
  21415. * @name ngKeyup
  21416. *
  21417. * @description
  21418. * Specify custom behavior on keyup event.
  21419. *
  21420. * @element ANY
  21421. * @priority 0
  21422. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  21423. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21424. *
  21425. * @example
  21426. <example>
  21427. <file name="index.html">
  21428. <p>Typing in the input box below updates the key count</p>
  21429. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  21430. <p>Typing in the input box below updates the keycode</p>
  21431. <input ng-keyup="event=$event">
  21432. <p>event keyCode: {{ event.keyCode }}</p>
  21433. <p>event altKey: {{ event.altKey }}</p>
  21434. </file>
  21435. </example>
  21436. */
  21437. /**
  21438. * @ngdoc directive
  21439. * @name ngKeypress
  21440. *
  21441. * @description
  21442. * Specify custom behavior on keypress event.
  21443. *
  21444. * @element ANY
  21445. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  21446. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  21447. * and can be interrogated for keyCode, altKey, etc.)
  21448. *
  21449. * @example
  21450. <example>
  21451. <file name="index.html">
  21452. <input ng-keypress="count = count + 1" ng-init="count=0">
  21453. key press count: {{count}}
  21454. </file>
  21455. </example>
  21456. */
  21457. /**
  21458. * @ngdoc directive
  21459. * @name ngSubmit
  21460. *
  21461. * @description
  21462. * Enables binding angular expressions to onsubmit events.
  21463. *
  21464. * Additionally it prevents the default action (which for form means sending the request to the
  21465. * server and reloading the current page), but only if the form does not contain `action`,
  21466. * `data-action`, or `x-action` attributes.
  21467. *
  21468. * <div class="alert alert-warning">
  21469. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  21470. * `ngSubmit` handlers together. See the
  21471. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  21472. * for a detailed discussion of when `ngSubmit` may be triggered.
  21473. * </div>
  21474. *
  21475. * @element form
  21476. * @priority 0
  21477. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  21478. * ({@link guide/expression#-event- Event object is available as `$event`})
  21479. *
  21480. * @example
  21481. <example module="submitExample">
  21482. <file name="index.html">
  21483. <script>
  21484. angular.module('submitExample', [])
  21485. .controller('ExampleController', ['$scope', function($scope) {
  21486. $scope.list = [];
  21487. $scope.text = 'hello';
  21488. $scope.submit = function() {
  21489. if ($scope.text) {
  21490. $scope.list.push(this.text);
  21491. $scope.text = '';
  21492. }
  21493. };
  21494. }]);
  21495. </script>
  21496. <form ng-submit="submit()" ng-controller="ExampleController">
  21497. Enter text and hit enter:
  21498. <input type="text" ng-model="text" name="text" />
  21499. <input type="submit" id="submit" value="Submit" />
  21500. <pre>list={{list}}</pre>
  21501. </form>
  21502. </file>
  21503. <file name="protractor.js" type="protractor">
  21504. it('should check ng-submit', function() {
  21505. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21506. element(by.css('#submit')).click();
  21507. expect(element(by.binding('list')).getText()).toContain('hello');
  21508. expect(element(by.model('text')).getAttribute('value')).toBe('');
  21509. });
  21510. it('should ignore empty strings', function() {
  21511. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21512. element(by.css('#submit')).click();
  21513. element(by.css('#submit')).click();
  21514. expect(element(by.binding('list')).getText()).toContain('hello');
  21515. });
  21516. </file>
  21517. </example>
  21518. */
  21519. /**
  21520. * @ngdoc directive
  21521. * @name ngFocus
  21522. *
  21523. * @description
  21524. * Specify custom behavior on focus event.
  21525. *
  21526. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  21527. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21528. * during an `$apply` to ensure a consistent state.
  21529. *
  21530. * @element window, input, select, textarea, a
  21531. * @priority 0
  21532. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  21533. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  21534. *
  21535. * @example
  21536. * See {@link ng.directive:ngClick ngClick}
  21537. */
  21538. /**
  21539. * @ngdoc directive
  21540. * @name ngBlur
  21541. *
  21542. * @description
  21543. * Specify custom behavior on blur event.
  21544. *
  21545. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  21546. * an element has lost focus.
  21547. *
  21548. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  21549. * (e.g. removing a focussed input),
  21550. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21551. * during an `$apply` to ensure a consistent state.
  21552. *
  21553. * @element window, input, select, textarea, a
  21554. * @priority 0
  21555. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  21556. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  21557. *
  21558. * @example
  21559. * See {@link ng.directive:ngClick ngClick}
  21560. */
  21561. /**
  21562. * @ngdoc directive
  21563. * @name ngCopy
  21564. *
  21565. * @description
  21566. * Specify custom behavior on copy event.
  21567. *
  21568. * @element window, input, select, textarea, a
  21569. * @priority 0
  21570. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  21571. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  21572. *
  21573. * @example
  21574. <example>
  21575. <file name="index.html">
  21576. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  21577. copied: {{copied}}
  21578. </file>
  21579. </example>
  21580. */
  21581. /**
  21582. * @ngdoc directive
  21583. * @name ngCut
  21584. *
  21585. * @description
  21586. * Specify custom behavior on cut event.
  21587. *
  21588. * @element window, input, select, textarea, a
  21589. * @priority 0
  21590. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  21591. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  21592. *
  21593. * @example
  21594. <example>
  21595. <file name="index.html">
  21596. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  21597. cut: {{cut}}
  21598. </file>
  21599. </example>
  21600. */
  21601. /**
  21602. * @ngdoc directive
  21603. * @name ngPaste
  21604. *
  21605. * @description
  21606. * Specify custom behavior on paste event.
  21607. *
  21608. * @element window, input, select, textarea, a
  21609. * @priority 0
  21610. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  21611. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  21612. *
  21613. * @example
  21614. <example>
  21615. <file name="index.html">
  21616. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  21617. pasted: {{paste}}
  21618. </file>
  21619. </example>
  21620. */
  21621. /**
  21622. * @ngdoc directive
  21623. * @name ngIf
  21624. * @restrict A
  21625. * @multiElement
  21626. *
  21627. * @description
  21628. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  21629. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  21630. * value then the element is removed from the DOM, otherwise a clone of the
  21631. * element is reinserted into the DOM.
  21632. *
  21633. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  21634. * element in the DOM rather than changing its visibility via the `display` css property. A common
  21635. * case when this difference is significant is when using css selectors that rely on an element's
  21636. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  21637. *
  21638. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  21639. * is created when the element is restored. The scope created within `ngIf` inherits from
  21640. * its parent scope using
  21641. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  21642. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  21643. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  21644. * variable within the child scope will override (hide) the value in the parent scope.
  21645. *
  21646. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  21647. * is if an element's class attribute is directly modified after it's compiled, using something like
  21648. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  21649. * the added class will be lost because the original compiled state is used to regenerate the element.
  21650. *
  21651. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  21652. * and `leave` effects.
  21653. *
  21654. * @animations
  21655. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  21656. * leave - happens just before the `ngIf` contents are removed from the DOM
  21657. *
  21658. * @element ANY
  21659. * @scope
  21660. * @priority 600
  21661. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  21662. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  21663. * element is added to the DOM tree.
  21664. *
  21665. * @example
  21666. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21667. <file name="index.html">
  21668. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  21669. Show when checked:
  21670. <span ng-if="checked" class="animate-if">
  21671. This is removed when the checkbox is unchecked.
  21672. </span>
  21673. </file>
  21674. <file name="animations.css">
  21675. .animate-if {
  21676. background:white;
  21677. border:1px solid black;
  21678. padding:10px;
  21679. }
  21680. .animate-if.ng-enter, .animate-if.ng-leave {
  21681. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21682. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21683. }
  21684. .animate-if.ng-enter,
  21685. .animate-if.ng-leave.ng-leave-active {
  21686. opacity:0;
  21687. }
  21688. .animate-if.ng-leave,
  21689. .animate-if.ng-enter.ng-enter-active {
  21690. opacity:1;
  21691. }
  21692. </file>
  21693. </example>
  21694. */
  21695. var ngIfDirective = ['$animate', function($animate) {
  21696. return {
  21697. multiElement: true,
  21698. transclude: 'element',
  21699. priority: 600,
  21700. terminal: true,
  21701. restrict: 'A',
  21702. $$tlb: true,
  21703. link: function($scope, $element, $attr, ctrl, $transclude) {
  21704. var block, childScope, previousElements;
  21705. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  21706. if (value) {
  21707. if (!childScope) {
  21708. $transclude(function(clone, newScope) {
  21709. childScope = newScope;
  21710. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  21711. // Note: We only need the first/last node of the cloned nodes.
  21712. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  21713. // by a directive with templateUrl when its template arrives.
  21714. block = {
  21715. clone: clone
  21716. };
  21717. $animate.enter(clone, $element.parent(), $element);
  21718. });
  21719. }
  21720. } else {
  21721. if (previousElements) {
  21722. previousElements.remove();
  21723. previousElements = null;
  21724. }
  21725. if (childScope) {
  21726. childScope.$destroy();
  21727. childScope = null;
  21728. }
  21729. if (block) {
  21730. previousElements = getBlockNodes(block.clone);
  21731. $animate.leave(previousElements).then(function() {
  21732. previousElements = null;
  21733. });
  21734. block = null;
  21735. }
  21736. }
  21737. });
  21738. }
  21739. };
  21740. }];
  21741. /**
  21742. * @ngdoc directive
  21743. * @name ngInclude
  21744. * @restrict ECA
  21745. *
  21746. * @description
  21747. * Fetches, compiles and includes an external HTML fragment.
  21748. *
  21749. * By default, the template URL is restricted to the same domain and protocol as the
  21750. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  21751. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  21752. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  21753. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  21754. * ng.$sce Strict Contextual Escaping}.
  21755. *
  21756. * In addition, the browser's
  21757. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  21758. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  21759. * policy may further restrict whether the template is successfully loaded.
  21760. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  21761. * access on some browsers.
  21762. *
  21763. * @animations
  21764. * enter - animation is used to bring new content into the browser.
  21765. * leave - animation is used to animate existing content away.
  21766. *
  21767. * The enter and leave animation occur concurrently.
  21768. *
  21769. * @scope
  21770. * @priority 400
  21771. *
  21772. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  21773. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  21774. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  21775. *
  21776. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  21777. * $anchorScroll} to scroll the viewport after the content is loaded.
  21778. *
  21779. * - If the attribute is not set, disable scrolling.
  21780. * - If the attribute is set without value, enable scrolling.
  21781. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  21782. *
  21783. * @example
  21784. <example module="includeExample" deps="angular-animate.js" animations="true">
  21785. <file name="index.html">
  21786. <div ng-controller="ExampleController">
  21787. <select ng-model="template" ng-options="t.name for t in templates">
  21788. <option value="">(blank)</option>
  21789. </select>
  21790. url of the template: <code>{{template.url}}</code>
  21791. <hr/>
  21792. <div class="slide-animate-container">
  21793. <div class="slide-animate" ng-include="template.url"></div>
  21794. </div>
  21795. </div>
  21796. </file>
  21797. <file name="script.js">
  21798. angular.module('includeExample', ['ngAnimate'])
  21799. .controller('ExampleController', ['$scope', function($scope) {
  21800. $scope.templates =
  21801. [ { name: 'template1.html', url: 'template1.html'},
  21802. { name: 'template2.html', url: 'template2.html'} ];
  21803. $scope.template = $scope.templates[0];
  21804. }]);
  21805. </file>
  21806. <file name="template1.html">
  21807. Content of template1.html
  21808. </file>
  21809. <file name="template2.html">
  21810. Content of template2.html
  21811. </file>
  21812. <file name="animations.css">
  21813. .slide-animate-container {
  21814. position:relative;
  21815. background:white;
  21816. border:1px solid black;
  21817. height:40px;
  21818. overflow:hidden;
  21819. }
  21820. .slide-animate {
  21821. padding:10px;
  21822. }
  21823. .slide-animate.ng-enter, .slide-animate.ng-leave {
  21824. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21825. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21826. position:absolute;
  21827. top:0;
  21828. left:0;
  21829. right:0;
  21830. bottom:0;
  21831. display:block;
  21832. padding:10px;
  21833. }
  21834. .slide-animate.ng-enter {
  21835. top:-50px;
  21836. }
  21837. .slide-animate.ng-enter.ng-enter-active {
  21838. top:0;
  21839. }
  21840. .slide-animate.ng-leave {
  21841. top:0;
  21842. }
  21843. .slide-animate.ng-leave.ng-leave-active {
  21844. top:50px;
  21845. }
  21846. </file>
  21847. <file name="protractor.js" type="protractor">
  21848. var templateSelect = element(by.model('template'));
  21849. var includeElem = element(by.css('[ng-include]'));
  21850. it('should load template1.html', function() {
  21851. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  21852. });
  21853. it('should load template2.html', function() {
  21854. if (browser.params.browser == 'firefox') {
  21855. // Firefox can't handle using selects
  21856. // See https://github.com/angular/protractor/issues/480
  21857. return;
  21858. }
  21859. templateSelect.click();
  21860. templateSelect.all(by.css('option')).get(2).click();
  21861. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  21862. });
  21863. it('should change to blank', function() {
  21864. if (browser.params.browser == 'firefox') {
  21865. // Firefox can't handle using selects
  21866. return;
  21867. }
  21868. templateSelect.click();
  21869. templateSelect.all(by.css('option')).get(0).click();
  21870. expect(includeElem.isPresent()).toBe(false);
  21871. });
  21872. </file>
  21873. </example>
  21874. */
  21875. /**
  21876. * @ngdoc event
  21877. * @name ngInclude#$includeContentRequested
  21878. * @eventType emit on the scope ngInclude was declared in
  21879. * @description
  21880. * Emitted every time the ngInclude content is requested.
  21881. *
  21882. * @param {Object} angularEvent Synthetic event object.
  21883. * @param {String} src URL of content to load.
  21884. */
  21885. /**
  21886. * @ngdoc event
  21887. * @name ngInclude#$includeContentLoaded
  21888. * @eventType emit on the current ngInclude scope
  21889. * @description
  21890. * Emitted every time the ngInclude content is reloaded.
  21891. *
  21892. * @param {Object} angularEvent Synthetic event object.
  21893. * @param {String} src URL of content to load.
  21894. */
  21895. /**
  21896. * @ngdoc event
  21897. * @name ngInclude#$includeContentError
  21898. * @eventType emit on the scope ngInclude was declared in
  21899. * @description
  21900. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  21901. *
  21902. * @param {Object} angularEvent Synthetic event object.
  21903. * @param {String} src URL of content to load.
  21904. */
  21905. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  21906. function($templateRequest, $anchorScroll, $animate) {
  21907. return {
  21908. restrict: 'ECA',
  21909. priority: 400,
  21910. terminal: true,
  21911. transclude: 'element',
  21912. controller: angular.noop,
  21913. compile: function(element, attr) {
  21914. var srcExp = attr.ngInclude || attr.src,
  21915. onloadExp = attr.onload || '',
  21916. autoScrollExp = attr.autoscroll;
  21917. return function(scope, $element, $attr, ctrl, $transclude) {
  21918. var changeCounter = 0,
  21919. currentScope,
  21920. previousElement,
  21921. currentElement;
  21922. var cleanupLastIncludeContent = function() {
  21923. if (previousElement) {
  21924. previousElement.remove();
  21925. previousElement = null;
  21926. }
  21927. if (currentScope) {
  21928. currentScope.$destroy();
  21929. currentScope = null;
  21930. }
  21931. if (currentElement) {
  21932. $animate.leave(currentElement).then(function() {
  21933. previousElement = null;
  21934. });
  21935. previousElement = currentElement;
  21936. currentElement = null;
  21937. }
  21938. };
  21939. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  21940. var afterAnimation = function() {
  21941. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  21942. $anchorScroll();
  21943. }
  21944. };
  21945. var thisChangeId = ++changeCounter;
  21946. if (src) {
  21947. //set the 2nd param to true to ignore the template request error so that the inner
  21948. //contents and scope can be cleaned up.
  21949. $templateRequest(src, true).then(function(response) {
  21950. if (thisChangeId !== changeCounter) return;
  21951. var newScope = scope.$new();
  21952. ctrl.template = response;
  21953. // Note: This will also link all children of ng-include that were contained in the original
  21954. // html. If that content contains controllers, ... they could pollute/change the scope.
  21955. // However, using ng-include on an element with additional content does not make sense...
  21956. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  21957. // function is called before linking the content, which would apply child
  21958. // directives to non existing elements.
  21959. var clone = $transclude(newScope, function(clone) {
  21960. cleanupLastIncludeContent();
  21961. $animate.enter(clone, null, $element).then(afterAnimation);
  21962. });
  21963. currentScope = newScope;
  21964. currentElement = clone;
  21965. currentScope.$emit('$includeContentLoaded', src);
  21966. scope.$eval(onloadExp);
  21967. }, function() {
  21968. if (thisChangeId === changeCounter) {
  21969. cleanupLastIncludeContent();
  21970. scope.$emit('$includeContentError', src);
  21971. }
  21972. });
  21973. scope.$emit('$includeContentRequested', src);
  21974. } else {
  21975. cleanupLastIncludeContent();
  21976. ctrl.template = null;
  21977. }
  21978. });
  21979. };
  21980. }
  21981. };
  21982. }];
  21983. // This directive is called during the $transclude call of the first `ngInclude` directive.
  21984. // It will replace and compile the content of the element with the loaded template.
  21985. // We need this directive so that the element content is already filled when
  21986. // the link function of another directive on the same element as ngInclude
  21987. // is called.
  21988. var ngIncludeFillContentDirective = ['$compile',
  21989. function($compile) {
  21990. return {
  21991. restrict: 'ECA',
  21992. priority: -400,
  21993. require: 'ngInclude',
  21994. link: function(scope, $element, $attr, ctrl) {
  21995. if (/SVG/.test($element[0].toString())) {
  21996. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  21997. // support innerHTML, so detect this here and try to generate the contents
  21998. // specially.
  21999. $element.empty();
  22000. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  22001. function namespaceAdaptedClone(clone) {
  22002. $element.append(clone);
  22003. }, {futureParentElement: $element});
  22004. return;
  22005. }
  22006. $element.html(ctrl.template);
  22007. $compile($element.contents())(scope);
  22008. }
  22009. };
  22010. }];
  22011. /**
  22012. * @ngdoc directive
  22013. * @name ngInit
  22014. * @restrict AC
  22015. *
  22016. * @description
  22017. * The `ngInit` directive allows you to evaluate an expression in the
  22018. * current scope.
  22019. *
  22020. * <div class="alert alert-danger">
  22021. * The only appropriate use of `ngInit` is for aliasing special properties of
  22022. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  22023. * should use {@link guide/controller controllers} rather than `ngInit`
  22024. * to initialize values on a scope.
  22025. * </div>
  22026. * <div class="alert alert-warning">
  22027. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  22028. * sure you have parenthesis for correct precedence:
  22029. * <pre class="prettyprint">
  22030. * `<div ng-init="test1 = (data | orderBy:'name')"></div>`
  22031. * </pre>
  22032. * </div>
  22033. *
  22034. * @priority 450
  22035. *
  22036. * @element ANY
  22037. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  22038. *
  22039. * @example
  22040. <example module="initExample">
  22041. <file name="index.html">
  22042. <script>
  22043. angular.module('initExample', [])
  22044. .controller('ExampleController', ['$scope', function($scope) {
  22045. $scope.list = [['a', 'b'], ['c', 'd']];
  22046. }]);
  22047. </script>
  22048. <div ng-controller="ExampleController">
  22049. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  22050. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  22051. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  22052. </div>
  22053. </div>
  22054. </div>
  22055. </file>
  22056. <file name="protractor.js" type="protractor">
  22057. it('should alias index positions', function() {
  22058. var elements = element.all(by.css('.example-init'));
  22059. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  22060. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  22061. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  22062. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  22063. });
  22064. </file>
  22065. </example>
  22066. */
  22067. var ngInitDirective = ngDirective({
  22068. priority: 450,
  22069. compile: function() {
  22070. return {
  22071. pre: function(scope, element, attrs) {
  22072. scope.$eval(attrs.ngInit);
  22073. }
  22074. };
  22075. }
  22076. });
  22077. /**
  22078. * @ngdoc directive
  22079. * @name ngList
  22080. *
  22081. * @description
  22082. * Text input that converts between a delimited string and an array of strings. The default
  22083. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  22084. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  22085. *
  22086. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  22087. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  22088. * list item is respected. This implies that the user of the directive is responsible for
  22089. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  22090. * tab or newline character.
  22091. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  22092. * when joining the list items back together) and whitespace around each list item is stripped
  22093. * before it is added to the model.
  22094. *
  22095. * ### Example with Validation
  22096. *
  22097. * <example name="ngList-directive" module="listExample">
  22098. * <file name="app.js">
  22099. * angular.module('listExample', [])
  22100. * .controller('ExampleController', ['$scope', function($scope) {
  22101. * $scope.names = ['morpheus', 'neo', 'trinity'];
  22102. * }]);
  22103. * </file>
  22104. * <file name="index.html">
  22105. * <form name="myForm" ng-controller="ExampleController">
  22106. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  22107. * <span role="alert">
  22108. * <span class="error" ng-show="myForm.namesInput.$error.required">
  22109. * Required!</span>
  22110. * </span>
  22111. * <br>
  22112. * <tt>names = {{names}}</tt><br/>
  22113. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  22114. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  22115. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22116. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22117. * </form>
  22118. * </file>
  22119. * <file name="protractor.js" type="protractor">
  22120. * var listInput = element(by.model('names'));
  22121. * var names = element(by.exactBinding('names'));
  22122. * var valid = element(by.binding('myForm.namesInput.$valid'));
  22123. * var error = element(by.css('span.error'));
  22124. *
  22125. * it('should initialize to model', function() {
  22126. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  22127. * expect(valid.getText()).toContain('true');
  22128. * expect(error.getCssValue('display')).toBe('none');
  22129. * });
  22130. *
  22131. * it('should be invalid if empty', function() {
  22132. * listInput.clear();
  22133. * listInput.sendKeys('');
  22134. *
  22135. * expect(names.getText()).toContain('');
  22136. * expect(valid.getText()).toContain('false');
  22137. * expect(error.getCssValue('display')).not.toBe('none');
  22138. * });
  22139. * </file>
  22140. * </example>
  22141. *
  22142. * ### Example - splitting on whitespace
  22143. * <example name="ngList-directive-newlines">
  22144. * <file name="index.html">
  22145. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  22146. * <pre>{{ list | json }}</pre>
  22147. * </file>
  22148. * <file name="protractor.js" type="protractor">
  22149. * it("should split the text by newlines", function() {
  22150. * var listInput = element(by.model('list'));
  22151. * var output = element(by.binding('list | json'));
  22152. * listInput.sendKeys('abc\ndef\nghi');
  22153. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  22154. * });
  22155. * </file>
  22156. * </example>
  22157. *
  22158. * @element input
  22159. * @param {string=} ngList optional delimiter that should be used to split the value.
  22160. */
  22161. var ngListDirective = function() {
  22162. return {
  22163. restrict: 'A',
  22164. priority: 100,
  22165. require: 'ngModel',
  22166. link: function(scope, element, attr, ctrl) {
  22167. // We want to control whitespace trimming so we use this convoluted approach
  22168. // to access the ngList attribute, which doesn't pre-trim the attribute
  22169. var ngList = element.attr(attr.$attr.ngList) || ', ';
  22170. var trimValues = attr.ngTrim !== 'false';
  22171. var separator = trimValues ? trim(ngList) : ngList;
  22172. var parse = function(viewValue) {
  22173. // If the viewValue is invalid (say required but empty) it will be `undefined`
  22174. if (isUndefined(viewValue)) return;
  22175. var list = [];
  22176. if (viewValue) {
  22177. forEach(viewValue.split(separator), function(value) {
  22178. if (value) list.push(trimValues ? trim(value) : value);
  22179. });
  22180. }
  22181. return list;
  22182. };
  22183. ctrl.$parsers.push(parse);
  22184. ctrl.$formatters.push(function(value) {
  22185. if (isArray(value)) {
  22186. return value.join(ngList);
  22187. }
  22188. return undefined;
  22189. });
  22190. // Override the standard $isEmpty because an empty array means the input is empty.
  22191. ctrl.$isEmpty = function(value) {
  22192. return !value || !value.length;
  22193. };
  22194. }
  22195. };
  22196. };
  22197. /* global VALID_CLASS: true,
  22198. INVALID_CLASS: true,
  22199. PRISTINE_CLASS: true,
  22200. DIRTY_CLASS: true,
  22201. UNTOUCHED_CLASS: true,
  22202. TOUCHED_CLASS: true,
  22203. */
  22204. var VALID_CLASS = 'ng-valid',
  22205. INVALID_CLASS = 'ng-invalid',
  22206. PRISTINE_CLASS = 'ng-pristine',
  22207. DIRTY_CLASS = 'ng-dirty',
  22208. UNTOUCHED_CLASS = 'ng-untouched',
  22209. TOUCHED_CLASS = 'ng-touched',
  22210. PENDING_CLASS = 'ng-pending';
  22211. var $ngModelMinErr = new minErr('ngModel');
  22212. /**
  22213. * @ngdoc type
  22214. * @name ngModel.NgModelController
  22215. *
  22216. * @property {string} $viewValue Actual string value in the view.
  22217. * @property {*} $modelValue The value in the model that the control is bound to.
  22218. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  22219. the control reads value from the DOM. The functions are called in array order, each passing
  22220. its return value through to the next. The last return value is forwarded to the
  22221. {@link ngModel.NgModelController#$validators `$validators`} collection.
  22222. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  22223. `$viewValue`}.
  22224. Returning `undefined` from a parser means a parse error occurred. In that case,
  22225. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  22226. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  22227. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  22228. *
  22229. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  22230. the model value changes. The functions are called in reverse array order, each passing the value through to the
  22231. next. The last return value is used as the actual DOM value.
  22232. Used to format / convert values for display in the control.
  22233. * ```js
  22234. * function formatter(value) {
  22235. * if (value) {
  22236. * return value.toUpperCase();
  22237. * }
  22238. * }
  22239. * ngModel.$formatters.push(formatter);
  22240. * ```
  22241. *
  22242. * @property {Object.<string, function>} $validators A collection of validators that are applied
  22243. * whenever the model value changes. The key value within the object refers to the name of the
  22244. * validator while the function refers to the validation operation. The validation operation is
  22245. * provided with the model value as an argument and must return a true or false value depending
  22246. * on the response of that validation.
  22247. *
  22248. * ```js
  22249. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  22250. * var value = modelValue || viewValue;
  22251. * return /[0-9]+/.test(value) &&
  22252. * /[a-z]+/.test(value) &&
  22253. * /[A-Z]+/.test(value) &&
  22254. * /\W+/.test(value);
  22255. * };
  22256. * ```
  22257. *
  22258. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  22259. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  22260. * is expected to return a promise when it is run during the model validation process. Once the promise
  22261. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  22262. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  22263. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  22264. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  22265. * will only run once all synchronous validators have passed.
  22266. *
  22267. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  22268. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  22269. *
  22270. * ```js
  22271. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  22272. * var value = modelValue || viewValue;
  22273. *
  22274. * // Lookup user by username
  22275. * return $http.get('/api/users/' + value).
  22276. * then(function resolved() {
  22277. * //username exists, this means validation fails
  22278. * return $q.reject('exists');
  22279. * }, function rejected() {
  22280. * //username does not exist, therefore this validation passes
  22281. * return true;
  22282. * });
  22283. * };
  22284. * ```
  22285. *
  22286. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  22287. * view value has changed. It is called with no arguments, and its return value is ignored.
  22288. * This can be used in place of additional $watches against the model value.
  22289. *
  22290. * @property {Object} $error An object hash with all failing validator ids as keys.
  22291. * @property {Object} $pending An object hash with all pending validator ids as keys.
  22292. *
  22293. * @property {boolean} $untouched True if control has not lost focus yet.
  22294. * @property {boolean} $touched True if control has lost focus.
  22295. * @property {boolean} $pristine True if user has not interacted with the control yet.
  22296. * @property {boolean} $dirty True if user has already interacted with the control.
  22297. * @property {boolean} $valid True if there is no error.
  22298. * @property {boolean} $invalid True if at least one error on the control.
  22299. * @property {string} $name The name attribute of the control.
  22300. *
  22301. * @description
  22302. *
  22303. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  22304. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  22305. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  22306. * listening to DOM events.
  22307. * Such DOM related logic should be provided by other directives which make use of
  22308. * `NgModelController` for data-binding to control elements.
  22309. * Angular provides this DOM logic for most {@link input `input`} elements.
  22310. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  22311. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  22312. *
  22313. * @example
  22314. * ### Custom Control Example
  22315. * This example shows how to use `NgModelController` with a custom control to achieve
  22316. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  22317. * collaborate together to achieve the desired result.
  22318. *
  22319. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  22320. * contents be edited in place by the user.
  22321. *
  22322. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  22323. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  22324. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  22325. * that content using the `$sce` service.
  22326. *
  22327. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  22328. <file name="style.css">
  22329. [contenteditable] {
  22330. border: 1px solid black;
  22331. background-color: white;
  22332. min-height: 20px;
  22333. }
  22334. .ng-invalid {
  22335. border: 1px solid red;
  22336. }
  22337. </file>
  22338. <file name="script.js">
  22339. angular.module('customControl', ['ngSanitize']).
  22340. directive('contenteditable', ['$sce', function($sce) {
  22341. return {
  22342. restrict: 'A', // only activate on element attribute
  22343. require: '?ngModel', // get a hold of NgModelController
  22344. link: function(scope, element, attrs, ngModel) {
  22345. if (!ngModel) return; // do nothing if no ng-model
  22346. // Specify how UI should be updated
  22347. ngModel.$render = function() {
  22348. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  22349. };
  22350. // Listen for change events to enable binding
  22351. element.on('blur keyup change', function() {
  22352. scope.$evalAsync(read);
  22353. });
  22354. read(); // initialize
  22355. // Write data to the model
  22356. function read() {
  22357. var html = element.html();
  22358. // When we clear the content editable the browser leaves a <br> behind
  22359. // If strip-br attribute is provided then we strip this out
  22360. if ( attrs.stripBr && html == '<br>' ) {
  22361. html = '';
  22362. }
  22363. ngModel.$setViewValue(html);
  22364. }
  22365. }
  22366. };
  22367. }]);
  22368. </file>
  22369. <file name="index.html">
  22370. <form name="myForm">
  22371. <div contenteditable
  22372. name="myWidget" ng-model="userContent"
  22373. strip-br="true"
  22374. required>Change me!</div>
  22375. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  22376. <hr>
  22377. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  22378. </form>
  22379. </file>
  22380. <file name="protractor.js" type="protractor">
  22381. it('should data-bind and become invalid', function() {
  22382. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  22383. // SafariDriver can't handle contenteditable
  22384. // and Firefox driver can't clear contenteditables very well
  22385. return;
  22386. }
  22387. var contentEditable = element(by.css('[contenteditable]'));
  22388. var content = 'Change me!';
  22389. expect(contentEditable.getText()).toEqual(content);
  22390. contentEditable.clear();
  22391. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  22392. expect(contentEditable.getText()).toEqual('');
  22393. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  22394. });
  22395. </file>
  22396. * </example>
  22397. *
  22398. *
  22399. */
  22400. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  22401. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  22402. this.$viewValue = Number.NaN;
  22403. this.$modelValue = Number.NaN;
  22404. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  22405. this.$validators = {};
  22406. this.$asyncValidators = {};
  22407. this.$parsers = [];
  22408. this.$formatters = [];
  22409. this.$viewChangeListeners = [];
  22410. this.$untouched = true;
  22411. this.$touched = false;
  22412. this.$pristine = true;
  22413. this.$dirty = false;
  22414. this.$valid = true;
  22415. this.$invalid = false;
  22416. this.$error = {}; // keep invalid keys here
  22417. this.$$success = {}; // keep valid keys here
  22418. this.$pending = undefined; // keep pending keys here
  22419. this.$name = $interpolate($attr.name || '', false)($scope);
  22420. var parsedNgModel = $parse($attr.ngModel),
  22421. parsedNgModelAssign = parsedNgModel.assign,
  22422. ngModelGet = parsedNgModel,
  22423. ngModelSet = parsedNgModelAssign,
  22424. pendingDebounce = null,
  22425. parserValid,
  22426. ctrl = this;
  22427. this.$$setOptions = function(options) {
  22428. ctrl.$options = options;
  22429. if (options && options.getterSetter) {
  22430. var invokeModelGetter = $parse($attr.ngModel + '()'),
  22431. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  22432. ngModelGet = function($scope) {
  22433. var modelValue = parsedNgModel($scope);
  22434. if (isFunction(modelValue)) {
  22435. modelValue = invokeModelGetter($scope);
  22436. }
  22437. return modelValue;
  22438. };
  22439. ngModelSet = function($scope, newValue) {
  22440. if (isFunction(parsedNgModel($scope))) {
  22441. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  22442. } else {
  22443. parsedNgModelAssign($scope, ctrl.$modelValue);
  22444. }
  22445. };
  22446. } else if (!parsedNgModel.assign) {
  22447. throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  22448. $attr.ngModel, startingTag($element));
  22449. }
  22450. };
  22451. /**
  22452. * @ngdoc method
  22453. * @name ngModel.NgModelController#$render
  22454. *
  22455. * @description
  22456. * Called when the view needs to be updated. It is expected that the user of the ng-model
  22457. * directive will implement this method.
  22458. *
  22459. * The `$render()` method is invoked in the following situations:
  22460. *
  22461. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  22462. * committed value then `$render()` is called to update the input control.
  22463. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  22464. * the `$viewValue` are different from last time.
  22465. *
  22466. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  22467. * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
  22468. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  22469. * invoked if you only change a property on the objects.
  22470. */
  22471. this.$render = noop;
  22472. /**
  22473. * @ngdoc method
  22474. * @name ngModel.NgModelController#$isEmpty
  22475. *
  22476. * @description
  22477. * This is called when we need to determine if the value of an input is empty.
  22478. *
  22479. * For instance, the required directive does this to work out if the input has data or not.
  22480. *
  22481. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  22482. *
  22483. * You can override this for input directives whose concept of being empty is different from the
  22484. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  22485. * implies empty.
  22486. *
  22487. * @param {*} value The value of the input to check for emptiness.
  22488. * @returns {boolean} True if `value` is "empty".
  22489. */
  22490. this.$isEmpty = function(value) {
  22491. return isUndefined(value) || value === '' || value === null || value !== value;
  22492. };
  22493. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  22494. currentValidationRunId = 0;
  22495. /**
  22496. * @ngdoc method
  22497. * @name ngModel.NgModelController#$setValidity
  22498. *
  22499. * @description
  22500. * Change the validity state, and notify the form.
  22501. *
  22502. * This method can be called within $parsers/$formatters or a custom validation implementation.
  22503. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  22504. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  22505. *
  22506. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  22507. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  22508. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  22509. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  22510. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  22511. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  22512. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  22513. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  22514. * Skipped is used by Angular when validators do not run because of parse errors and
  22515. * when `$asyncValidators` do not run because any of the `$validators` failed.
  22516. */
  22517. addSetValidityMethod({
  22518. ctrl: this,
  22519. $element: $element,
  22520. set: function(object, property) {
  22521. object[property] = true;
  22522. },
  22523. unset: function(object, property) {
  22524. delete object[property];
  22525. },
  22526. parentForm: parentForm,
  22527. $animate: $animate
  22528. });
  22529. /**
  22530. * @ngdoc method
  22531. * @name ngModel.NgModelController#$setPristine
  22532. *
  22533. * @description
  22534. * Sets the control to its pristine state.
  22535. *
  22536. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  22537. * state (`ng-pristine` class). A model is considered to be pristine when the control
  22538. * has not been changed from when first compiled.
  22539. */
  22540. this.$setPristine = function() {
  22541. ctrl.$dirty = false;
  22542. ctrl.$pristine = true;
  22543. $animate.removeClass($element, DIRTY_CLASS);
  22544. $animate.addClass($element, PRISTINE_CLASS);
  22545. };
  22546. /**
  22547. * @ngdoc method
  22548. * @name ngModel.NgModelController#$setDirty
  22549. *
  22550. * @description
  22551. * Sets the control to its dirty state.
  22552. *
  22553. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  22554. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  22555. * from when first compiled.
  22556. */
  22557. this.$setDirty = function() {
  22558. ctrl.$dirty = true;
  22559. ctrl.$pristine = false;
  22560. $animate.removeClass($element, PRISTINE_CLASS);
  22561. $animate.addClass($element, DIRTY_CLASS);
  22562. parentForm.$setDirty();
  22563. };
  22564. /**
  22565. * @ngdoc method
  22566. * @name ngModel.NgModelController#$setUntouched
  22567. *
  22568. * @description
  22569. * Sets the control to its untouched state.
  22570. *
  22571. * This method can be called to remove the `ng-touched` class and set the control to its
  22572. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  22573. * by default, however this function can be used to restore that state if the model has
  22574. * already been touched by the user.
  22575. */
  22576. this.$setUntouched = function() {
  22577. ctrl.$touched = false;
  22578. ctrl.$untouched = true;
  22579. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  22580. };
  22581. /**
  22582. * @ngdoc method
  22583. * @name ngModel.NgModelController#$setTouched
  22584. *
  22585. * @description
  22586. * Sets the control to its touched state.
  22587. *
  22588. * This method can be called to remove the `ng-untouched` class and set the control to its
  22589. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  22590. * first focused the control element and then shifted focus away from the control (blur event).
  22591. */
  22592. this.$setTouched = function() {
  22593. ctrl.$touched = true;
  22594. ctrl.$untouched = false;
  22595. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  22596. };
  22597. /**
  22598. * @ngdoc method
  22599. * @name ngModel.NgModelController#$rollbackViewValue
  22600. *
  22601. * @description
  22602. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  22603. * which may be caused by a pending debounced event or because the input is waiting for a some
  22604. * future event.
  22605. *
  22606. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  22607. * as blur you can have a situation where there is a period when the `$viewValue`
  22608. * is out of synch with the ngModel's `$modelValue`.
  22609. *
  22610. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  22611. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  22612. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  22613. *
  22614. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  22615. * input which may have such events pending. This is important in order to make sure that the
  22616. * input field will be updated with the new model value and any pending operations are cancelled.
  22617. *
  22618. * <example name="ng-model-cancel-update" module="cancel-update-example">
  22619. * <file name="app.js">
  22620. * angular.module('cancel-update-example', [])
  22621. *
  22622. * .controller('CancelUpdateController', ['$scope', function($scope) {
  22623. * $scope.resetWithCancel = function(e) {
  22624. * if (e.keyCode == 27) {
  22625. * $scope.myForm.myInput1.$rollbackViewValue();
  22626. * $scope.myValue = '';
  22627. * }
  22628. * };
  22629. * $scope.resetWithoutCancel = function(e) {
  22630. * if (e.keyCode == 27) {
  22631. * $scope.myValue = '';
  22632. * }
  22633. * };
  22634. * }]);
  22635. * </file>
  22636. * <file name="index.html">
  22637. * <div ng-controller="CancelUpdateController">
  22638. * <p>Try typing something in each input. See that the model only updates when you
  22639. * blur off the input.
  22640. * </p>
  22641. * <p>Now see what happens if you start typing then press the Escape key</p>
  22642. *
  22643. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  22644. * <p id="inputDescription1">With $rollbackViewValue()</p>
  22645. * <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
  22646. * ng-keydown="resetWithCancel($event)"><br/>
  22647. * myValue: "{{ myValue }}"
  22648. *
  22649. * <p id="inputDescription2">Without $rollbackViewValue()</p>
  22650. * <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
  22651. * ng-keydown="resetWithoutCancel($event)"><br/>
  22652. * myValue: "{{ myValue }}"
  22653. * </form>
  22654. * </div>
  22655. * </file>
  22656. * </example>
  22657. */
  22658. this.$rollbackViewValue = function() {
  22659. $timeout.cancel(pendingDebounce);
  22660. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  22661. ctrl.$render();
  22662. };
  22663. /**
  22664. * @ngdoc method
  22665. * @name ngModel.NgModelController#$validate
  22666. *
  22667. * @description
  22668. * Runs each of the registered validators (first synchronous validators and then
  22669. * asynchronous validators).
  22670. * If the validity changes to invalid, the model will be set to `undefined`,
  22671. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  22672. * If the validity changes to valid, it will set the model to the last available valid
  22673. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  22674. */
  22675. this.$validate = function() {
  22676. // ignore $validate before model is initialized
  22677. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22678. return;
  22679. }
  22680. var viewValue = ctrl.$$lastCommittedViewValue;
  22681. // Note: we use the $$rawModelValue as $modelValue might have been
  22682. // set to undefined during a view -> model update that found validation
  22683. // errors. We can't parse the view here, since that could change
  22684. // the model although neither viewValue nor the model on the scope changed
  22685. var modelValue = ctrl.$$rawModelValue;
  22686. var prevValid = ctrl.$valid;
  22687. var prevModelValue = ctrl.$modelValue;
  22688. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22689. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  22690. // If there was no change in validity, don't update the model
  22691. // This prevents changing an invalid modelValue to undefined
  22692. if (!allowInvalid && prevValid !== allValid) {
  22693. // Note: Don't check ctrl.$valid here, as we could have
  22694. // external validators (e.g. calculated on the server),
  22695. // that just call $setValidity and need the model value
  22696. // to calculate their validity.
  22697. ctrl.$modelValue = allValid ? modelValue : undefined;
  22698. if (ctrl.$modelValue !== prevModelValue) {
  22699. ctrl.$$writeModelToScope();
  22700. }
  22701. }
  22702. });
  22703. };
  22704. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  22705. currentValidationRunId++;
  22706. var localValidationRunId = currentValidationRunId;
  22707. // check parser error
  22708. if (!processParseErrors()) {
  22709. validationDone(false);
  22710. return;
  22711. }
  22712. if (!processSyncValidators()) {
  22713. validationDone(false);
  22714. return;
  22715. }
  22716. processAsyncValidators();
  22717. function processParseErrors() {
  22718. var errorKey = ctrl.$$parserName || 'parse';
  22719. if (parserValid === undefined) {
  22720. setValidity(errorKey, null);
  22721. } else {
  22722. if (!parserValid) {
  22723. forEach(ctrl.$validators, function(v, name) {
  22724. setValidity(name, null);
  22725. });
  22726. forEach(ctrl.$asyncValidators, function(v, name) {
  22727. setValidity(name, null);
  22728. });
  22729. }
  22730. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  22731. setValidity(errorKey, parserValid);
  22732. return parserValid;
  22733. }
  22734. return true;
  22735. }
  22736. function processSyncValidators() {
  22737. var syncValidatorsValid = true;
  22738. forEach(ctrl.$validators, function(validator, name) {
  22739. var result = validator(modelValue, viewValue);
  22740. syncValidatorsValid = syncValidatorsValid && result;
  22741. setValidity(name, result);
  22742. });
  22743. if (!syncValidatorsValid) {
  22744. forEach(ctrl.$asyncValidators, function(v, name) {
  22745. setValidity(name, null);
  22746. });
  22747. return false;
  22748. }
  22749. return true;
  22750. }
  22751. function processAsyncValidators() {
  22752. var validatorPromises = [];
  22753. var allValid = true;
  22754. forEach(ctrl.$asyncValidators, function(validator, name) {
  22755. var promise = validator(modelValue, viewValue);
  22756. if (!isPromiseLike(promise)) {
  22757. throw $ngModelMinErr("$asyncValidators",
  22758. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  22759. }
  22760. setValidity(name, undefined);
  22761. validatorPromises.push(promise.then(function() {
  22762. setValidity(name, true);
  22763. }, function(error) {
  22764. allValid = false;
  22765. setValidity(name, false);
  22766. }));
  22767. });
  22768. if (!validatorPromises.length) {
  22769. validationDone(true);
  22770. } else {
  22771. $q.all(validatorPromises).then(function() {
  22772. validationDone(allValid);
  22773. }, noop);
  22774. }
  22775. }
  22776. function setValidity(name, isValid) {
  22777. if (localValidationRunId === currentValidationRunId) {
  22778. ctrl.$setValidity(name, isValid);
  22779. }
  22780. }
  22781. function validationDone(allValid) {
  22782. if (localValidationRunId === currentValidationRunId) {
  22783. doneCallback(allValid);
  22784. }
  22785. }
  22786. };
  22787. /**
  22788. * @ngdoc method
  22789. * @name ngModel.NgModelController#$commitViewValue
  22790. *
  22791. * @description
  22792. * Commit a pending update to the `$modelValue`.
  22793. *
  22794. * Updates may be pending by a debounced event or because the input is waiting for a some future
  22795. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  22796. * usually handles calling this in response to input events.
  22797. */
  22798. this.$commitViewValue = function() {
  22799. var viewValue = ctrl.$viewValue;
  22800. $timeout.cancel(pendingDebounce);
  22801. // If the view value has not changed then we should just exit, except in the case where there is
  22802. // a native validator on the element. In this case the validation state may have changed even though
  22803. // the viewValue has stayed empty.
  22804. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  22805. return;
  22806. }
  22807. ctrl.$$lastCommittedViewValue = viewValue;
  22808. // change to dirty
  22809. if (ctrl.$pristine) {
  22810. this.$setDirty();
  22811. }
  22812. this.$$parseAndValidate();
  22813. };
  22814. this.$$parseAndValidate = function() {
  22815. var viewValue = ctrl.$$lastCommittedViewValue;
  22816. var modelValue = viewValue;
  22817. parserValid = isUndefined(modelValue) ? undefined : true;
  22818. if (parserValid) {
  22819. for (var i = 0; i < ctrl.$parsers.length; i++) {
  22820. modelValue = ctrl.$parsers[i](modelValue);
  22821. if (isUndefined(modelValue)) {
  22822. parserValid = false;
  22823. break;
  22824. }
  22825. }
  22826. }
  22827. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22828. // ctrl.$modelValue has not been touched yet...
  22829. ctrl.$modelValue = ngModelGet($scope);
  22830. }
  22831. var prevModelValue = ctrl.$modelValue;
  22832. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22833. ctrl.$$rawModelValue = modelValue;
  22834. if (allowInvalid) {
  22835. ctrl.$modelValue = modelValue;
  22836. writeToModelIfNeeded();
  22837. }
  22838. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  22839. // This can happen if e.g. $setViewValue is called from inside a parser
  22840. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  22841. if (!allowInvalid) {
  22842. // Note: Don't check ctrl.$valid here, as we could have
  22843. // external validators (e.g. calculated on the server),
  22844. // that just call $setValidity and need the model value
  22845. // to calculate their validity.
  22846. ctrl.$modelValue = allValid ? modelValue : undefined;
  22847. writeToModelIfNeeded();
  22848. }
  22849. });
  22850. function writeToModelIfNeeded() {
  22851. if (ctrl.$modelValue !== prevModelValue) {
  22852. ctrl.$$writeModelToScope();
  22853. }
  22854. }
  22855. };
  22856. this.$$writeModelToScope = function() {
  22857. ngModelSet($scope, ctrl.$modelValue);
  22858. forEach(ctrl.$viewChangeListeners, function(listener) {
  22859. try {
  22860. listener();
  22861. } catch (e) {
  22862. $exceptionHandler(e);
  22863. }
  22864. });
  22865. };
  22866. /**
  22867. * @ngdoc method
  22868. * @name ngModel.NgModelController#$setViewValue
  22869. *
  22870. * @description
  22871. * Update the view value.
  22872. *
  22873. * This method should be called when an input directive want to change the view value; typically,
  22874. * this is done from within a DOM event handler.
  22875. *
  22876. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  22877. * {@link ng.directive:select select} calls it when an option is selected.
  22878. *
  22879. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  22880. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  22881. * watch of objects, it only looks for a change of identity. If you only change the property of
  22882. * the object then ngModel will not realise that the object has changed and will not invoke the
  22883. * `$parsers` and `$validators` pipelines.
  22884. *
  22885. * For this reason, you should not change properties of the copy once it has been passed to
  22886. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  22887. *
  22888. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  22889. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  22890. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  22891. * **expression** specified in the `ng-model` attribute.
  22892. *
  22893. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  22894. *
  22895. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  22896. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  22897. * `updateOn` events is triggered on the DOM element.
  22898. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  22899. * directive is used with a custom debounce for this particular event.
  22900. *
  22901. * Note that calling this function does not trigger a `$digest`.
  22902. *
  22903. * @param {string} value Value from the view.
  22904. * @param {string} trigger Event that triggered the update.
  22905. */
  22906. this.$setViewValue = function(value, trigger) {
  22907. ctrl.$viewValue = value;
  22908. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  22909. ctrl.$$debounceViewValueCommit(trigger);
  22910. }
  22911. };
  22912. this.$$debounceViewValueCommit = function(trigger) {
  22913. var debounceDelay = 0,
  22914. options = ctrl.$options,
  22915. debounce;
  22916. if (options && isDefined(options.debounce)) {
  22917. debounce = options.debounce;
  22918. if (isNumber(debounce)) {
  22919. debounceDelay = debounce;
  22920. } else if (isNumber(debounce[trigger])) {
  22921. debounceDelay = debounce[trigger];
  22922. } else if (isNumber(debounce['default'])) {
  22923. debounceDelay = debounce['default'];
  22924. }
  22925. }
  22926. $timeout.cancel(pendingDebounce);
  22927. if (debounceDelay) {
  22928. pendingDebounce = $timeout(function() {
  22929. ctrl.$commitViewValue();
  22930. }, debounceDelay);
  22931. } else if ($rootScope.$$phase) {
  22932. ctrl.$commitViewValue();
  22933. } else {
  22934. $scope.$apply(function() {
  22935. ctrl.$commitViewValue();
  22936. });
  22937. }
  22938. };
  22939. // model -> value
  22940. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  22941. // 1. scope value is 'a'
  22942. // 2. user enters 'b'
  22943. // 3. ng-change kicks in and reverts scope value to 'a'
  22944. // -> scope value did not change since the last digest as
  22945. // ng-change executes in apply phase
  22946. // 4. view should be changed back to 'a'
  22947. $scope.$watch(function ngModelWatch() {
  22948. var modelValue = ngModelGet($scope);
  22949. // if scope model value and ngModel value are out of sync
  22950. // TODO(perf): why not move this to the action fn?
  22951. if (modelValue !== ctrl.$modelValue &&
  22952. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  22953. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  22954. ) {
  22955. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  22956. parserValid = undefined;
  22957. var formatters = ctrl.$formatters,
  22958. idx = formatters.length;
  22959. var viewValue = modelValue;
  22960. while (idx--) {
  22961. viewValue = formatters[idx](viewValue);
  22962. }
  22963. if (ctrl.$viewValue !== viewValue) {
  22964. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  22965. ctrl.$render();
  22966. ctrl.$$runValidators(modelValue, viewValue, noop);
  22967. }
  22968. }
  22969. return modelValue;
  22970. });
  22971. }];
  22972. /**
  22973. * @ngdoc directive
  22974. * @name ngModel
  22975. *
  22976. * @element input
  22977. * @priority 1
  22978. *
  22979. * @description
  22980. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  22981. * property on the scope using {@link ngModel.NgModelController NgModelController},
  22982. * which is created and exposed by this directive.
  22983. *
  22984. * `ngModel` is responsible for:
  22985. *
  22986. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  22987. * require.
  22988. * - Providing validation behavior (i.e. required, number, email, url).
  22989. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  22990. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  22991. * - Registering the control with its parent {@link ng.directive:form form}.
  22992. *
  22993. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  22994. * current scope. If the property doesn't already exist on this scope, it will be created
  22995. * implicitly and added to the scope.
  22996. *
  22997. * For best practices on using `ngModel`, see:
  22998. *
  22999. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  23000. *
  23001. * For basic examples, how to use `ngModel`, see:
  23002. *
  23003. * - {@link ng.directive:input input}
  23004. * - {@link input[text] text}
  23005. * - {@link input[checkbox] checkbox}
  23006. * - {@link input[radio] radio}
  23007. * - {@link input[number] number}
  23008. * - {@link input[email] email}
  23009. * - {@link input[url] url}
  23010. * - {@link input[date] date}
  23011. * - {@link input[datetime-local] datetime-local}
  23012. * - {@link input[time] time}
  23013. * - {@link input[month] month}
  23014. * - {@link input[week] week}
  23015. * - {@link ng.directive:select select}
  23016. * - {@link ng.directive:textarea textarea}
  23017. *
  23018. * # CSS classes
  23019. * The following CSS classes are added and removed on the associated input/select/textarea element
  23020. * depending on the validity of the model.
  23021. *
  23022. * - `ng-valid`: the model is valid
  23023. * - `ng-invalid`: the model is invalid
  23024. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  23025. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  23026. * - `ng-pristine`: the control hasn't been interacted with yet
  23027. * - `ng-dirty`: the control has been interacted with
  23028. * - `ng-touched`: the control has been blurred
  23029. * - `ng-untouched`: the control hasn't been blurred
  23030. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  23031. *
  23032. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  23033. *
  23034. * ## Animation Hooks
  23035. *
  23036. * Animations within models are triggered when any of the associated CSS classes are added and removed
  23037. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  23038. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  23039. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  23040. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  23041. *
  23042. * The following example shows a simple way to utilize CSS transitions to style an input element
  23043. * that has been rendered as invalid after it has been validated:
  23044. *
  23045. * <pre>
  23046. * //be sure to include ngAnimate as a module to hook into more
  23047. * //advanced animations
  23048. * .my-input {
  23049. * transition:0.5s linear all;
  23050. * background: white;
  23051. * }
  23052. * .my-input.ng-invalid {
  23053. * background: red;
  23054. * color:white;
  23055. * }
  23056. * </pre>
  23057. *
  23058. * @example
  23059. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  23060. <file name="index.html">
  23061. <script>
  23062. angular.module('inputExample', [])
  23063. .controller('ExampleController', ['$scope', function($scope) {
  23064. $scope.val = '1';
  23065. }]);
  23066. </script>
  23067. <style>
  23068. .my-input {
  23069. -webkit-transition:all linear 0.5s;
  23070. transition:all linear 0.5s;
  23071. background: transparent;
  23072. }
  23073. .my-input.ng-invalid {
  23074. color:white;
  23075. background: red;
  23076. }
  23077. </style>
  23078. <p id="inputDescription">
  23079. Update input to see transitions when valid/invalid.
  23080. Integer is a valid value.
  23081. </p>
  23082. <form name="testForm" ng-controller="ExampleController">
  23083. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  23084. aria-describedby="inputDescription" />
  23085. </form>
  23086. </file>
  23087. * </example>
  23088. *
  23089. * ## Binding to a getter/setter
  23090. *
  23091. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  23092. * function that returns a representation of the model when called with zero arguments, and sets
  23093. * the internal state of a model when called with an argument. It's sometimes useful to use this
  23094. * for models that have an internal representation that's different from what the model exposes
  23095. * to the view.
  23096. *
  23097. * <div class="alert alert-success">
  23098. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  23099. * frequently than other parts of your code.
  23100. * </div>
  23101. *
  23102. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  23103. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  23104. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  23105. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  23106. *
  23107. * The following example shows how to use `ngModel` with a getter/setter:
  23108. *
  23109. * @example
  23110. * <example name="ngModel-getter-setter" module="getterSetterExample">
  23111. <file name="index.html">
  23112. <div ng-controller="ExampleController">
  23113. <form name="userForm">
  23114. <label>Name:
  23115. <input type="text" name="userName"
  23116. ng-model="user.name"
  23117. ng-model-options="{ getterSetter: true }" />
  23118. </label>
  23119. </form>
  23120. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23121. </div>
  23122. </file>
  23123. <file name="app.js">
  23124. angular.module('getterSetterExample', [])
  23125. .controller('ExampleController', ['$scope', function($scope) {
  23126. var _name = 'Brian';
  23127. $scope.user = {
  23128. name: function(newName) {
  23129. // Note that newName can be undefined for two reasons:
  23130. // 1. Because it is called as a getter and thus called with no arguments
  23131. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23132. // input is invalid
  23133. return arguments.length ? (_name = newName) : _name;
  23134. }
  23135. };
  23136. }]);
  23137. </file>
  23138. * </example>
  23139. */
  23140. var ngModelDirective = ['$rootScope', function($rootScope) {
  23141. return {
  23142. restrict: 'A',
  23143. require: ['ngModel', '^?form', '^?ngModelOptions'],
  23144. controller: NgModelController,
  23145. // Prelink needs to run before any input directive
  23146. // so that we can set the NgModelOptions in NgModelController
  23147. // before anyone else uses it.
  23148. priority: 1,
  23149. compile: function ngModelCompile(element) {
  23150. // Setup initial state of the control
  23151. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  23152. return {
  23153. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  23154. var modelCtrl = ctrls[0],
  23155. formCtrl = ctrls[1] || nullFormCtrl;
  23156. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  23157. // notify others, especially parent forms
  23158. formCtrl.$addControl(modelCtrl);
  23159. attr.$observe('name', function(newValue) {
  23160. if (modelCtrl.$name !== newValue) {
  23161. formCtrl.$$renameControl(modelCtrl, newValue);
  23162. }
  23163. });
  23164. scope.$on('$destroy', function() {
  23165. formCtrl.$removeControl(modelCtrl);
  23166. });
  23167. },
  23168. post: function ngModelPostLink(scope, element, attr, ctrls) {
  23169. var modelCtrl = ctrls[0];
  23170. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  23171. element.on(modelCtrl.$options.updateOn, function(ev) {
  23172. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  23173. });
  23174. }
  23175. element.on('blur', function(ev) {
  23176. if (modelCtrl.$touched) return;
  23177. if ($rootScope.$$phase) {
  23178. scope.$evalAsync(modelCtrl.$setTouched);
  23179. } else {
  23180. scope.$apply(modelCtrl.$setTouched);
  23181. }
  23182. });
  23183. }
  23184. };
  23185. }
  23186. };
  23187. }];
  23188. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  23189. /**
  23190. * @ngdoc directive
  23191. * @name ngModelOptions
  23192. *
  23193. * @description
  23194. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  23195. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  23196. * takes place when a timer expires; this timer will be reset after another change takes place.
  23197. *
  23198. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  23199. * be different from the value in the actual model. This means that if you update the model you
  23200. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  23201. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  23202. *
  23203. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  23204. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  23205. * important because `form` controllers are published to the related scope under the name in their
  23206. * `name` attribute.
  23207. *
  23208. * Any pending changes will take place immediately when an enclosing form is submitted via the
  23209. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  23210. * to have access to the updated model.
  23211. *
  23212. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  23213. *
  23214. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  23215. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  23216. * events using an space delimited list. There is a special event called `default` that
  23217. * matches the default events belonging of the control.
  23218. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  23219. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  23220. * custom value for each event. For example:
  23221. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  23222. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  23223. * not validate correctly instead of the default behavior of setting the model to undefined.
  23224. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  23225. `ngModel` as getters/setters.
  23226. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  23227. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  23228. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  23229. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  23230. * If not specified, the timezone of the browser will be used.
  23231. *
  23232. * @example
  23233. The following example shows how to override immediate updates. Changes on the inputs within the
  23234. form will update the model only when the control loses focus (blur event). If `escape` key is
  23235. pressed while the input field is focused, the value is reset to the value in the current model.
  23236. <example name="ngModelOptions-directive-blur" module="optionsExample">
  23237. <file name="index.html">
  23238. <div ng-controller="ExampleController">
  23239. <form name="userForm">
  23240. <label>Name:
  23241. <input type="text" name="userName"
  23242. ng-model="user.name"
  23243. ng-model-options="{ updateOn: 'blur' }"
  23244. ng-keyup="cancel($event)" />
  23245. </label><br />
  23246. <label>Other data:
  23247. <input type="text" ng-model="user.data" />
  23248. </label><br />
  23249. </form>
  23250. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23251. </div>
  23252. </file>
  23253. <file name="app.js">
  23254. angular.module('optionsExample', [])
  23255. .controller('ExampleController', ['$scope', function($scope) {
  23256. $scope.user = { name: 'say', data: '' };
  23257. $scope.cancel = function(e) {
  23258. if (e.keyCode == 27) {
  23259. $scope.userForm.userName.$rollbackViewValue();
  23260. }
  23261. };
  23262. }]);
  23263. </file>
  23264. <file name="protractor.js" type="protractor">
  23265. var model = element(by.binding('user.name'));
  23266. var input = element(by.model('user.name'));
  23267. var other = element(by.model('user.data'));
  23268. it('should allow custom events', function() {
  23269. input.sendKeys(' hello');
  23270. input.click();
  23271. expect(model.getText()).toEqual('say');
  23272. other.click();
  23273. expect(model.getText()).toEqual('say hello');
  23274. });
  23275. it('should $rollbackViewValue when model changes', function() {
  23276. input.sendKeys(' hello');
  23277. expect(input.getAttribute('value')).toEqual('say hello');
  23278. input.sendKeys(protractor.Key.ESCAPE);
  23279. expect(input.getAttribute('value')).toEqual('say');
  23280. other.click();
  23281. expect(model.getText()).toEqual('say');
  23282. });
  23283. </file>
  23284. </example>
  23285. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  23286. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  23287. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  23288. <file name="index.html">
  23289. <div ng-controller="ExampleController">
  23290. <form name="userForm">
  23291. <label>Name:
  23292. <input type="text" name="userName"
  23293. ng-model="user.name"
  23294. ng-model-options="{ debounce: 1000 }" />
  23295. </label>
  23296. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  23297. <br />
  23298. </form>
  23299. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23300. </div>
  23301. </file>
  23302. <file name="app.js">
  23303. angular.module('optionsExample', [])
  23304. .controller('ExampleController', ['$scope', function($scope) {
  23305. $scope.user = { name: 'say' };
  23306. }]);
  23307. </file>
  23308. </example>
  23309. This one shows how to bind to getter/setters:
  23310. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  23311. <file name="index.html">
  23312. <div ng-controller="ExampleController">
  23313. <form name="userForm">
  23314. <label>Name:
  23315. <input type="text" name="userName"
  23316. ng-model="user.name"
  23317. ng-model-options="{ getterSetter: true }" />
  23318. </label>
  23319. </form>
  23320. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23321. </div>
  23322. </file>
  23323. <file name="app.js">
  23324. angular.module('getterSetterExample', [])
  23325. .controller('ExampleController', ['$scope', function($scope) {
  23326. var _name = 'Brian';
  23327. $scope.user = {
  23328. name: function(newName) {
  23329. // Note that newName can be undefined for two reasons:
  23330. // 1. Because it is called as a getter and thus called with no arguments
  23331. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23332. // input is invalid
  23333. return arguments.length ? (_name = newName) : _name;
  23334. }
  23335. };
  23336. }]);
  23337. </file>
  23338. </example>
  23339. */
  23340. var ngModelOptionsDirective = function() {
  23341. return {
  23342. restrict: 'A',
  23343. controller: ['$scope', '$attrs', function($scope, $attrs) {
  23344. var that = this;
  23345. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  23346. // Allow adding/overriding bound events
  23347. if (this.$options.updateOn !== undefined) {
  23348. this.$options.updateOnDefault = false;
  23349. // extract "default" pseudo-event from list of events that can trigger a model update
  23350. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  23351. that.$options.updateOnDefault = true;
  23352. return ' ';
  23353. }));
  23354. } else {
  23355. this.$options.updateOnDefault = true;
  23356. }
  23357. }]
  23358. };
  23359. };
  23360. // helper methods
  23361. function addSetValidityMethod(context) {
  23362. var ctrl = context.ctrl,
  23363. $element = context.$element,
  23364. classCache = {},
  23365. set = context.set,
  23366. unset = context.unset,
  23367. parentForm = context.parentForm,
  23368. $animate = context.$animate;
  23369. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  23370. ctrl.$setValidity = setValidity;
  23371. function setValidity(validationErrorKey, state, controller) {
  23372. if (state === undefined) {
  23373. createAndSet('$pending', validationErrorKey, controller);
  23374. } else {
  23375. unsetAndCleanup('$pending', validationErrorKey, controller);
  23376. }
  23377. if (!isBoolean(state)) {
  23378. unset(ctrl.$error, validationErrorKey, controller);
  23379. unset(ctrl.$$success, validationErrorKey, controller);
  23380. } else {
  23381. if (state) {
  23382. unset(ctrl.$error, validationErrorKey, controller);
  23383. set(ctrl.$$success, validationErrorKey, controller);
  23384. } else {
  23385. set(ctrl.$error, validationErrorKey, controller);
  23386. unset(ctrl.$$success, validationErrorKey, controller);
  23387. }
  23388. }
  23389. if (ctrl.$pending) {
  23390. cachedToggleClass(PENDING_CLASS, true);
  23391. ctrl.$valid = ctrl.$invalid = undefined;
  23392. toggleValidationCss('', null);
  23393. } else {
  23394. cachedToggleClass(PENDING_CLASS, false);
  23395. ctrl.$valid = isObjectEmpty(ctrl.$error);
  23396. ctrl.$invalid = !ctrl.$valid;
  23397. toggleValidationCss('', ctrl.$valid);
  23398. }
  23399. // re-read the state as the set/unset methods could have
  23400. // combined state in ctrl.$error[validationError] (used for forms),
  23401. // where setting/unsetting only increments/decrements the value,
  23402. // and does not replace it.
  23403. var combinedState;
  23404. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  23405. combinedState = undefined;
  23406. } else if (ctrl.$error[validationErrorKey]) {
  23407. combinedState = false;
  23408. } else if (ctrl.$$success[validationErrorKey]) {
  23409. combinedState = true;
  23410. } else {
  23411. combinedState = null;
  23412. }
  23413. toggleValidationCss(validationErrorKey, combinedState);
  23414. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  23415. }
  23416. function createAndSet(name, value, controller) {
  23417. if (!ctrl[name]) {
  23418. ctrl[name] = {};
  23419. }
  23420. set(ctrl[name], value, controller);
  23421. }
  23422. function unsetAndCleanup(name, value, controller) {
  23423. if (ctrl[name]) {
  23424. unset(ctrl[name], value, controller);
  23425. }
  23426. if (isObjectEmpty(ctrl[name])) {
  23427. ctrl[name] = undefined;
  23428. }
  23429. }
  23430. function cachedToggleClass(className, switchValue) {
  23431. if (switchValue && !classCache[className]) {
  23432. $animate.addClass($element, className);
  23433. classCache[className] = true;
  23434. } else if (!switchValue && classCache[className]) {
  23435. $animate.removeClass($element, className);
  23436. classCache[className] = false;
  23437. }
  23438. }
  23439. function toggleValidationCss(validationErrorKey, isValid) {
  23440. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  23441. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  23442. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  23443. }
  23444. }
  23445. function isObjectEmpty(obj) {
  23446. if (obj) {
  23447. for (var prop in obj) {
  23448. if (obj.hasOwnProperty(prop)) {
  23449. return false;
  23450. }
  23451. }
  23452. }
  23453. return true;
  23454. }
  23455. /**
  23456. * @ngdoc directive
  23457. * @name ngNonBindable
  23458. * @restrict AC
  23459. * @priority 1000
  23460. *
  23461. * @description
  23462. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  23463. * DOM element. This is useful if the element contains what appears to be Angular directives and
  23464. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  23465. * displays snippets of code, for instance.
  23466. *
  23467. * @element ANY
  23468. *
  23469. * @example
  23470. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  23471. * but the one wrapped in `ngNonBindable` is left alone.
  23472. *
  23473. * @example
  23474. <example>
  23475. <file name="index.html">
  23476. <div>Normal: {{1 + 2}}</div>
  23477. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  23478. </file>
  23479. <file name="protractor.js" type="protractor">
  23480. it('should check ng-non-bindable', function() {
  23481. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  23482. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  23483. });
  23484. </file>
  23485. </example>
  23486. */
  23487. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  23488. /* global jqLiteRemove */
  23489. var ngOptionsMinErr = minErr('ngOptions');
  23490. /**
  23491. * @ngdoc directive
  23492. * @name ngOptions
  23493. * @restrict A
  23494. *
  23495. * @description
  23496. *
  23497. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23498. * elements for the `<select>` element using the array or object obtained by evaluating the
  23499. * `ngOptions` comprehension expression.
  23500. *
  23501. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23502. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23503. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23504. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23505. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23506. * to a non-string value. This is because an option element can only be bound to string values at
  23507. * present.
  23508. *
  23509. * When an item in the `<select>` menu is selected, the array element or object property
  23510. * represented by the selected option will be bound to the model identified by the `ngModel`
  23511. * directive.
  23512. *
  23513. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23514. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23515. * option. See example below for demonstration.
  23516. *
  23517. * ## Complex Models (objects or collections)
  23518. *
  23519. * **Note:** By default, `ngModel` watches the model by reference, not value. This is important when
  23520. * binding any input directive to a model that is an object or a collection.
  23521. *
  23522. * Since this is a common situation for `ngOptions` the directive additionally watches the model using
  23523. * `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in
  23524. * the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual
  23525. * object/collection has not changed identity but only a property on the object or an item in the collection
  23526. * changes.
  23527. *
  23528. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  23529. * if the model is an array). This means that changing a property deeper inside the object/collection that the
  23530. * first level will not trigger a re-rendering.
  23531. *
  23532. *
  23533. * ## `select` **`as`**
  23534. *
  23535. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23536. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23537. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23538. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23539. *
  23540. *
  23541. * ### `select` **`as`** and **`track by`**
  23542. *
  23543. * <div class="alert alert-warning">
  23544. * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
  23545. * </div>
  23546. *
  23547. * Consider the following example:
  23548. *
  23549. * ```html
  23550. * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected">
  23551. * ```
  23552. *
  23553. * ```js
  23554. * $scope.values = [{
  23555. * id: 1,
  23556. * label: 'aLabel',
  23557. * subItem: { name: 'aSubItem' }
  23558. * }, {
  23559. * id: 2,
  23560. * label: 'bLabel',
  23561. * subItem: { name: 'bSubItem' }
  23562. * }];
  23563. *
  23564. * $scope.selected = { name: 'aSubItem' };
  23565. * ```
  23566. *
  23567. * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
  23568. * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
  23569. * following:
  23570. *
  23571. * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
  23572. * 2. Apply **`track by`** to the already selected value in `ngModel`.
  23573. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
  23574. * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
  23575. * a wrong object, the selected element can't be found, `<select>` is always reset to the "not
  23576. * selected" option.
  23577. *
  23578. *
  23579. * @param {string} ngModel Assignable angular expression to data-bind to.
  23580. * @param {string=} name Property name of the form under which the control is published.
  23581. * @param {string=} required The control is considered valid only if value is entered.
  23582. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23583. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23584. * `required` when you want to data-bind to the `required` attribute.
  23585. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23586. *
  23587. * * for array data sources:
  23588. * * `label` **`for`** `value` **`in`** `array`
  23589. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23590. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23591. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  23592. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23593. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23594. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23595. * (for including a filter with `track by`)
  23596. * * for object data sources:
  23597. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23598. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23599. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23600. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23601. * * `select` **`as`** `label` **`group by`** `group`
  23602. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23603. * * `select` **`as`** `label` **`disable when`** `disable`
  23604. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23605. *
  23606. * Where:
  23607. *
  23608. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23609. * * `value`: local variable which will refer to each item in the `array` or each property value
  23610. * of `object` during iteration.
  23611. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23612. * * `label`: The result of this expression will be the label for `<option>` element. The
  23613. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23614. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23615. * element. If not specified, `select` expression will default to `value`.
  23616. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23617. * DOM element.
  23618. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  23619. * element. Return `true` to disable.
  23620. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23621. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23622. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23623. * even when the options are recreated (e.g. reloaded from the server).
  23624. *
  23625. * @example
  23626. <example module="selectExample">
  23627. <file name="index.html">
  23628. <script>
  23629. angular.module('selectExample', [])
  23630. .controller('ExampleController', ['$scope', function($scope) {
  23631. $scope.colors = [
  23632. {name:'black', shade:'dark'},
  23633. {name:'white', shade:'light', notAnOption: true},
  23634. {name:'red', shade:'dark'},
  23635. {name:'blue', shade:'dark', notAnOption: true},
  23636. {name:'yellow', shade:'light', notAnOption: false}
  23637. ];
  23638. $scope.myColor = $scope.colors[2]; // red
  23639. }]);
  23640. </script>
  23641. <div ng-controller="ExampleController">
  23642. <ul>
  23643. <li ng-repeat="color in colors">
  23644. <label>Name: <input ng-model="color.name"></label>
  23645. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  23646. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  23647. </li>
  23648. <li>
  23649. <button ng-click="colors.push({})">add</button>
  23650. </li>
  23651. </ul>
  23652. <hr/>
  23653. <label>Color (null not allowed):
  23654. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  23655. </label><br/>
  23656. <label>Color (null allowed):
  23657. <span class="nullable">
  23658. <select ng-model="myColor" ng-options="color.name for color in colors">
  23659. <option value="">-- choose color --</option>
  23660. </select>
  23661. </span></label><br/>
  23662. <label>Color grouped by shade:
  23663. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23664. </select>
  23665. </label><br/>
  23666. <label>Color grouped by shade, with some disabled:
  23667. <select ng-model="myColor"
  23668. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  23669. </select>
  23670. </label><br/>
  23671. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  23672. <br/>
  23673. <hr/>
  23674. Currently selected: {{ {selected_color:myColor} }}
  23675. <div style="border:solid 1px black; height:20px"
  23676. ng-style="{'background-color':myColor.name}">
  23677. </div>
  23678. </div>
  23679. </file>
  23680. <file name="protractor.js" type="protractor">
  23681. it('should check ng-options', function() {
  23682. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23683. element.all(by.model('myColor')).first().click();
  23684. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23685. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23686. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23687. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23688. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23689. });
  23690. </file>
  23691. </example>
  23692. */
  23693. // jshint maxlen: false
  23694. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  23695. 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]+?))?$/;
  23696. // 1: value expression (valueFn)
  23697. // 2: label expression (displayFn)
  23698. // 3: group by expression (groupByFn)
  23699. // 4: disable when expression (disableWhenFn)
  23700. // 5: array item variable name
  23701. // 6: object item key variable name
  23702. // 7: object item value variable name
  23703. // 8: collection expression
  23704. // 9: track by expression
  23705. // jshint maxlen: 100
  23706. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  23707. function parseOptionsExpression(optionsExp, selectElement, scope) {
  23708. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  23709. if (!(match)) {
  23710. throw ngOptionsMinErr('iexp',
  23711. "Expected expression in form of " +
  23712. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23713. " but got '{0}'. Element: {1}",
  23714. optionsExp, startingTag(selectElement));
  23715. }
  23716. // Extract the parts from the ngOptions expression
  23717. // The variable name for the value of the item in the collection
  23718. var valueName = match[5] || match[7];
  23719. // The variable name for the key of the item in the collection
  23720. var keyName = match[6];
  23721. // An expression that generates the viewValue for an option if there is a label expression
  23722. var selectAs = / as /.test(match[0]) && match[1];
  23723. // An expression that is used to track the id of each object in the options collection
  23724. var trackBy = match[9];
  23725. // An expression that generates the viewValue for an option if there is no label expression
  23726. var valueFn = $parse(match[2] ? match[1] : valueName);
  23727. var selectAsFn = selectAs && $parse(selectAs);
  23728. var viewValueFn = selectAsFn || valueFn;
  23729. var trackByFn = trackBy && $parse(trackBy);
  23730. // Get the value by which we are going to track the option
  23731. // if we have a trackFn then use that (passing scope and locals)
  23732. // otherwise just hash the given viewValue
  23733. var getTrackByValueFn = trackBy ?
  23734. function(value, locals) { return trackByFn(scope, locals); } :
  23735. function getHashOfValue(value) { return hashKey(value); };
  23736. var getTrackByValue = function(value, key) {
  23737. return getTrackByValueFn(value, getLocals(value, key));
  23738. };
  23739. var displayFn = $parse(match[2] || match[1]);
  23740. var groupByFn = $parse(match[3] || '');
  23741. var disableWhenFn = $parse(match[4] || '');
  23742. var valuesFn = $parse(match[8]);
  23743. var locals = {};
  23744. var getLocals = keyName ? function(value, key) {
  23745. locals[keyName] = key;
  23746. locals[valueName] = value;
  23747. return locals;
  23748. } : function(value) {
  23749. locals[valueName] = value;
  23750. return locals;
  23751. };
  23752. function Option(selectValue, viewValue, label, group, disabled) {
  23753. this.selectValue = selectValue;
  23754. this.viewValue = viewValue;
  23755. this.label = label;
  23756. this.group = group;
  23757. this.disabled = disabled;
  23758. }
  23759. function getOptionValuesKeys(optionValues) {
  23760. var optionValuesKeys;
  23761. if (!keyName && isArrayLike(optionValues)) {
  23762. optionValuesKeys = optionValues;
  23763. } else {
  23764. // if object, extract keys, in enumeration order, unsorted
  23765. optionValuesKeys = [];
  23766. for (var itemKey in optionValues) {
  23767. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  23768. optionValuesKeys.push(itemKey);
  23769. }
  23770. }
  23771. }
  23772. return optionValuesKeys;
  23773. }
  23774. return {
  23775. trackBy: trackBy,
  23776. getTrackByValue: getTrackByValue,
  23777. getWatchables: $parse(valuesFn, function(optionValues) {
  23778. // Create a collection of things that we would like to watch (watchedArray)
  23779. // so that they can all be watched using a single $watchCollection
  23780. // that only runs the handler once if anything changes
  23781. var watchedArray = [];
  23782. optionValues = optionValues || [];
  23783. var optionValuesKeys = getOptionValuesKeys(optionValues);
  23784. var optionValuesLength = optionValuesKeys.length;
  23785. for (var index = 0; index < optionValuesLength; index++) {
  23786. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  23787. var value = optionValues[key];
  23788. var locals = getLocals(optionValues[key], key);
  23789. var selectValue = getTrackByValueFn(optionValues[key], locals);
  23790. watchedArray.push(selectValue);
  23791. // Only need to watch the displayFn if there is a specific label expression
  23792. if (match[2] || match[1]) {
  23793. var label = displayFn(scope, locals);
  23794. watchedArray.push(label);
  23795. }
  23796. // Only need to watch the disableWhenFn if there is a specific disable expression
  23797. if (match[4]) {
  23798. var disableWhen = disableWhenFn(scope, locals);
  23799. watchedArray.push(disableWhen);
  23800. }
  23801. }
  23802. return watchedArray;
  23803. }),
  23804. getOptions: function() {
  23805. var optionItems = [];
  23806. var selectValueMap = {};
  23807. // The option values were already computed in the `getWatchables` fn,
  23808. // which must have been called to trigger `getOptions`
  23809. var optionValues = valuesFn(scope) || [];
  23810. var optionValuesKeys = getOptionValuesKeys(optionValues);
  23811. var optionValuesLength = optionValuesKeys.length;
  23812. for (var index = 0; index < optionValuesLength; index++) {
  23813. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  23814. var value = optionValues[key];
  23815. var locals = getLocals(value, key);
  23816. var viewValue = viewValueFn(scope, locals);
  23817. var selectValue = getTrackByValueFn(viewValue, locals);
  23818. var label = displayFn(scope, locals);
  23819. var group = groupByFn(scope, locals);
  23820. var disabled = disableWhenFn(scope, locals);
  23821. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  23822. optionItems.push(optionItem);
  23823. selectValueMap[selectValue] = optionItem;
  23824. }
  23825. return {
  23826. items: optionItems,
  23827. selectValueMap: selectValueMap,
  23828. getOptionFromViewValue: function(value) {
  23829. return selectValueMap[getTrackByValue(value)];
  23830. },
  23831. getViewValueFromOption: function(option) {
  23832. // If the viewValue could be an object that may be mutated by the application,
  23833. // we need to make a copy and not return the reference to the value on the option.
  23834. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  23835. }
  23836. };
  23837. }
  23838. };
  23839. }
  23840. // we can't just jqLite('<option>') since jqLite is not smart enough
  23841. // to create it in <select> and IE barfs otherwise.
  23842. var optionTemplate = document.createElement('option'),
  23843. optGroupTemplate = document.createElement('optgroup');
  23844. return {
  23845. restrict: 'A',
  23846. terminal: true,
  23847. require: ['select', '?ngModel'],
  23848. link: function(scope, selectElement, attr, ctrls) {
  23849. // if ngModel is not defined, we don't need to do anything
  23850. var ngModelCtrl = ctrls[1];
  23851. if (!ngModelCtrl) return;
  23852. var selectCtrl = ctrls[0];
  23853. var multiple = attr.multiple;
  23854. // The emptyOption allows the application developer to provide their own custom "empty"
  23855. // option when the viewValue does not match any of the option values.
  23856. var emptyOption;
  23857. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  23858. if (children[i].value === '') {
  23859. emptyOption = children.eq(i);
  23860. break;
  23861. }
  23862. }
  23863. var providedEmptyOption = !!emptyOption;
  23864. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  23865. unknownOption.val('?');
  23866. var options;
  23867. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  23868. var renderEmptyOption = function() {
  23869. if (!providedEmptyOption) {
  23870. selectElement.prepend(emptyOption);
  23871. }
  23872. selectElement.val('');
  23873. emptyOption.prop('selected', true); // needed for IE
  23874. emptyOption.attr('selected', true);
  23875. };
  23876. var removeEmptyOption = function() {
  23877. if (!providedEmptyOption) {
  23878. emptyOption.remove();
  23879. }
  23880. };
  23881. var renderUnknownOption = function() {
  23882. selectElement.prepend(unknownOption);
  23883. selectElement.val('?');
  23884. unknownOption.prop('selected', true); // needed for IE
  23885. unknownOption.attr('selected', true);
  23886. };
  23887. var removeUnknownOption = function() {
  23888. unknownOption.remove();
  23889. };
  23890. // Update the controller methods for multiple selectable options
  23891. if (!multiple) {
  23892. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  23893. var option = options.getOptionFromViewValue(value);
  23894. if (option && !option.disabled) {
  23895. if (selectElement[0].value !== option.selectValue) {
  23896. removeUnknownOption();
  23897. removeEmptyOption();
  23898. selectElement[0].value = option.selectValue;
  23899. option.element.selected = true;
  23900. option.element.setAttribute('selected', 'selected');
  23901. }
  23902. } else {
  23903. if (value === null || providedEmptyOption) {
  23904. removeUnknownOption();
  23905. renderEmptyOption();
  23906. } else {
  23907. removeEmptyOption();
  23908. renderUnknownOption();
  23909. }
  23910. }
  23911. };
  23912. selectCtrl.readValue = function readNgOptionsValue() {
  23913. var selectedOption = options.selectValueMap[selectElement.val()];
  23914. if (selectedOption && !selectedOption.disabled) {
  23915. removeEmptyOption();
  23916. removeUnknownOption();
  23917. return options.getViewValueFromOption(selectedOption);
  23918. }
  23919. return null;
  23920. };
  23921. // If we are using `track by` then we must watch the tracked value on the model
  23922. // since ngModel only watches for object identity change
  23923. if (ngOptions.trackBy) {
  23924. scope.$watch(
  23925. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  23926. function() { ngModelCtrl.$render(); }
  23927. );
  23928. }
  23929. } else {
  23930. ngModelCtrl.$isEmpty = function(value) {
  23931. return !value || value.length === 0;
  23932. };
  23933. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  23934. options.items.forEach(function(option) {
  23935. option.element.selected = false;
  23936. });
  23937. if (value) {
  23938. value.forEach(function(item) {
  23939. var option = options.getOptionFromViewValue(item);
  23940. if (option && !option.disabled) option.element.selected = true;
  23941. });
  23942. }
  23943. };
  23944. selectCtrl.readValue = function readNgOptionsMultiple() {
  23945. var selectedValues = selectElement.val() || [],
  23946. selections = [];
  23947. forEach(selectedValues, function(value) {
  23948. var option = options.selectValueMap[value];
  23949. if (!option.disabled) selections.push(options.getViewValueFromOption(option));
  23950. });
  23951. return selections;
  23952. };
  23953. // If we are using `track by` then we must watch these tracked values on the model
  23954. // since ngModel only watches for object identity change
  23955. if (ngOptions.trackBy) {
  23956. scope.$watchCollection(function() {
  23957. if (isArray(ngModelCtrl.$viewValue)) {
  23958. return ngModelCtrl.$viewValue.map(function(value) {
  23959. return ngOptions.getTrackByValue(value);
  23960. });
  23961. }
  23962. }, function() {
  23963. ngModelCtrl.$render();
  23964. });
  23965. }
  23966. }
  23967. if (providedEmptyOption) {
  23968. // we need to remove it before calling selectElement.empty() because otherwise IE will
  23969. // remove the label from the element. wtf?
  23970. emptyOption.remove();
  23971. // compile the element since there might be bindings in it
  23972. $compile(emptyOption)(scope);
  23973. // remove the class, which is added automatically because we recompile the element and it
  23974. // becomes the compilation root
  23975. emptyOption.removeClass('ng-scope');
  23976. } else {
  23977. emptyOption = jqLite(optionTemplate.cloneNode(false));
  23978. }
  23979. // We need to do this here to ensure that the options object is defined
  23980. // when we first hit it in writeNgOptionsValue
  23981. updateOptions();
  23982. // We will re-render the option elements if the option values or labels change
  23983. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  23984. // ------------------------------------------------------------------ //
  23985. function updateOptionElement(option, element) {
  23986. option.element = element;
  23987. element.disabled = option.disabled;
  23988. if (option.value !== element.value) element.value = option.selectValue;
  23989. if (option.label !== element.label) {
  23990. element.label = option.label;
  23991. element.textContent = option.label;
  23992. }
  23993. }
  23994. function addOrReuseElement(parent, current, type, templateElement) {
  23995. var element;
  23996. // Check whether we can reuse the next element
  23997. if (current && lowercase(current.nodeName) === type) {
  23998. // The next element is the right type so reuse it
  23999. element = current;
  24000. } else {
  24001. // The next element is not the right type so create a new one
  24002. element = templateElement.cloneNode(false);
  24003. if (!current) {
  24004. // There are no more elements so just append it to the select
  24005. parent.appendChild(element);
  24006. } else {
  24007. // The next element is not a group so insert the new one
  24008. parent.insertBefore(element, current);
  24009. }
  24010. }
  24011. return element;
  24012. }
  24013. function removeExcessElements(current) {
  24014. var next;
  24015. while (current) {
  24016. next = current.nextSibling;
  24017. jqLiteRemove(current);
  24018. current = next;
  24019. }
  24020. }
  24021. function skipEmptyAndUnknownOptions(current) {
  24022. var emptyOption_ = emptyOption && emptyOption[0];
  24023. var unknownOption_ = unknownOption && unknownOption[0];
  24024. if (emptyOption_ || unknownOption_) {
  24025. while (current &&
  24026. (current === emptyOption_ ||
  24027. current === unknownOption_)) {
  24028. current = current.nextSibling;
  24029. }
  24030. }
  24031. return current;
  24032. }
  24033. function updateOptions() {
  24034. var previousValue = options && selectCtrl.readValue();
  24035. options = ngOptions.getOptions();
  24036. var groupMap = {};
  24037. var currentElement = selectElement[0].firstChild;
  24038. // Ensure that the empty option is always there if it was explicitly provided
  24039. if (providedEmptyOption) {
  24040. selectElement.prepend(emptyOption);
  24041. }
  24042. currentElement = skipEmptyAndUnknownOptions(currentElement);
  24043. options.items.forEach(function updateOption(option) {
  24044. var group;
  24045. var groupElement;
  24046. var optionElement;
  24047. if (option.group) {
  24048. // This option is to live in a group
  24049. // See if we have already created this group
  24050. group = groupMap[option.group];
  24051. if (!group) {
  24052. // We have not already created this group
  24053. groupElement = addOrReuseElement(selectElement[0],
  24054. currentElement,
  24055. 'optgroup',
  24056. optGroupTemplate);
  24057. // Move to the next element
  24058. currentElement = groupElement.nextSibling;
  24059. // Update the label on the group element
  24060. groupElement.label = option.group;
  24061. // Store it for use later
  24062. group = groupMap[option.group] = {
  24063. groupElement: groupElement,
  24064. currentOptionElement: groupElement.firstChild
  24065. };
  24066. }
  24067. // So now we have a group for this option we add the option to the group
  24068. optionElement = addOrReuseElement(group.groupElement,
  24069. group.currentOptionElement,
  24070. 'option',
  24071. optionTemplate);
  24072. updateOptionElement(option, optionElement);
  24073. // Move to the next element
  24074. group.currentOptionElement = optionElement.nextSibling;
  24075. } else {
  24076. // This option is not in a group
  24077. optionElement = addOrReuseElement(selectElement[0],
  24078. currentElement,
  24079. 'option',
  24080. optionTemplate);
  24081. updateOptionElement(option, optionElement);
  24082. // Move to the next element
  24083. currentElement = optionElement.nextSibling;
  24084. }
  24085. });
  24086. // Now remove all excess options and group
  24087. Object.keys(groupMap).forEach(function(key) {
  24088. removeExcessElements(groupMap[key].currentOptionElement);
  24089. });
  24090. removeExcessElements(currentElement);
  24091. ngModelCtrl.$render();
  24092. // Check to see if the value has changed due to the update to the options
  24093. if (!ngModelCtrl.$isEmpty(previousValue)) {
  24094. var nextValue = selectCtrl.readValue();
  24095. if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  24096. ngModelCtrl.$setViewValue(nextValue);
  24097. ngModelCtrl.$render();
  24098. }
  24099. }
  24100. }
  24101. }
  24102. };
  24103. }];
  24104. /**
  24105. * @ngdoc directive
  24106. * @name ngPluralize
  24107. * @restrict EA
  24108. *
  24109. * @description
  24110. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  24111. * These rules are bundled with angular.js, but can be overridden
  24112. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  24113. * by specifying the mappings between
  24114. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24115. * and the strings to be displayed.
  24116. *
  24117. * # Plural categories and explicit number rules
  24118. * There are two
  24119. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24120. * in Angular's default en-US locale: "one" and "other".
  24121. *
  24122. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  24123. * any number that is not 1), an explicit number rule can only match one number. For example, the
  24124. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  24125. * and explicit number rules throughout the rest of this documentation.
  24126. *
  24127. * # Configuring ngPluralize
  24128. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  24129. * You can also provide an optional attribute, `offset`.
  24130. *
  24131. * The value of the `count` attribute can be either a string or an {@link guide/expression
  24132. * Angular expression}; these are evaluated on the current scope for its bound value.
  24133. *
  24134. * The `when` attribute specifies the mappings between plural categories and the actual
  24135. * string to be displayed. The value of the attribute should be a JSON object.
  24136. *
  24137. * The following example shows how to configure ngPluralize:
  24138. *
  24139. * ```html
  24140. * <ng-pluralize count="personCount"
  24141. when="{'0': 'Nobody is viewing.',
  24142. * 'one': '1 person is viewing.',
  24143. * 'other': '{} people are viewing.'}">
  24144. * </ng-pluralize>
  24145. *```
  24146. *
  24147. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  24148. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  24149. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  24150. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  24151. * show "a dozen people are viewing".
  24152. *
  24153. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  24154. * into pluralized strings. In the previous example, Angular will replace `{}` with
  24155. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  24156. * for <span ng-non-bindable>{{numberExpression}}</span>.
  24157. *
  24158. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  24159. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  24160. *
  24161. * # Configuring ngPluralize with offset
  24162. * The `offset` attribute allows further customization of pluralized text, which can result in
  24163. * a better user experience. For example, instead of the message "4 people are viewing this document",
  24164. * you might display "John, Kate and 2 others are viewing this document".
  24165. * The offset attribute allows you to offset a number by any desired value.
  24166. * Let's take a look at an example:
  24167. *
  24168. * ```html
  24169. * <ng-pluralize count="personCount" offset=2
  24170. * when="{'0': 'Nobody is viewing.',
  24171. * '1': '{{person1}} is viewing.',
  24172. * '2': '{{person1}} and {{person2}} are viewing.',
  24173. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24174. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24175. * </ng-pluralize>
  24176. * ```
  24177. *
  24178. * Notice that we are still using two plural categories(one, other), but we added
  24179. * three explicit number rules 0, 1 and 2.
  24180. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  24181. * When three people view the document, no explicit number rule is found, so
  24182. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  24183. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  24184. * is shown.
  24185. *
  24186. * Note that when you specify offsets, you must provide explicit number rules for
  24187. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  24188. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  24189. * plural categories "one" and "other".
  24190. *
  24191. * @param {string|expression} count The variable to be bound to.
  24192. * @param {string} when The mapping between plural category to its corresponding strings.
  24193. * @param {number=} offset Offset to deduct from the total number.
  24194. *
  24195. * @example
  24196. <example module="pluralizeExample">
  24197. <file name="index.html">
  24198. <script>
  24199. angular.module('pluralizeExample', [])
  24200. .controller('ExampleController', ['$scope', function($scope) {
  24201. $scope.person1 = 'Igor';
  24202. $scope.person2 = 'Misko';
  24203. $scope.personCount = 1;
  24204. }]);
  24205. </script>
  24206. <div ng-controller="ExampleController">
  24207. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  24208. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  24209. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  24210. <!--- Example with simple pluralization rules for en locale --->
  24211. Without Offset:
  24212. <ng-pluralize count="personCount"
  24213. when="{'0': 'Nobody is viewing.',
  24214. 'one': '1 person is viewing.',
  24215. 'other': '{} people are viewing.'}">
  24216. </ng-pluralize><br>
  24217. <!--- Example with offset --->
  24218. With Offset(2):
  24219. <ng-pluralize count="personCount" offset=2
  24220. when="{'0': 'Nobody is viewing.',
  24221. '1': '{{person1}} is viewing.',
  24222. '2': '{{person1}} and {{person2}} are viewing.',
  24223. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24224. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24225. </ng-pluralize>
  24226. </div>
  24227. </file>
  24228. <file name="protractor.js" type="protractor">
  24229. it('should show correct pluralized string', function() {
  24230. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  24231. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24232. var countInput = element(by.model('personCount'));
  24233. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  24234. expect(withOffset.getText()).toEqual('Igor is viewing.');
  24235. countInput.clear();
  24236. countInput.sendKeys('0');
  24237. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  24238. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  24239. countInput.clear();
  24240. countInput.sendKeys('2');
  24241. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  24242. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  24243. countInput.clear();
  24244. countInput.sendKeys('3');
  24245. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  24246. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  24247. countInput.clear();
  24248. countInput.sendKeys('4');
  24249. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  24250. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  24251. });
  24252. it('should show data-bound names', function() {
  24253. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24254. var personCount = element(by.model('personCount'));
  24255. var person1 = element(by.model('person1'));
  24256. var person2 = element(by.model('person2'));
  24257. personCount.clear();
  24258. personCount.sendKeys('4');
  24259. person1.clear();
  24260. person1.sendKeys('Di');
  24261. person2.clear();
  24262. person2.sendKeys('Vojta');
  24263. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  24264. });
  24265. </file>
  24266. </example>
  24267. */
  24268. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  24269. var BRACE = /{}/g,
  24270. IS_WHEN = /^when(Minus)?(.+)$/;
  24271. return {
  24272. link: function(scope, element, attr) {
  24273. var numberExp = attr.count,
  24274. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  24275. offset = attr.offset || 0,
  24276. whens = scope.$eval(whenExp) || {},
  24277. whensExpFns = {},
  24278. startSymbol = $interpolate.startSymbol(),
  24279. endSymbol = $interpolate.endSymbol(),
  24280. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  24281. watchRemover = angular.noop,
  24282. lastCount;
  24283. forEach(attr, function(expression, attributeName) {
  24284. var tmpMatch = IS_WHEN.exec(attributeName);
  24285. if (tmpMatch) {
  24286. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  24287. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  24288. }
  24289. });
  24290. forEach(whens, function(expression, key) {
  24291. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  24292. });
  24293. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  24294. var count = parseFloat(newVal);
  24295. var countIsNaN = isNaN(count);
  24296. if (!countIsNaN && !(count in whens)) {
  24297. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  24298. // Otherwise, check it against pluralization rules in $locale service.
  24299. count = $locale.pluralCat(count - offset);
  24300. }
  24301. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  24302. // In JS `NaN !== NaN`, so we have to exlicitly check.
  24303. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  24304. watchRemover();
  24305. var whenExpFn = whensExpFns[count];
  24306. if (isUndefined(whenExpFn)) {
  24307. if (newVal != null) {
  24308. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  24309. }
  24310. watchRemover = noop;
  24311. updateElementText();
  24312. } else {
  24313. watchRemover = scope.$watch(whenExpFn, updateElementText);
  24314. }
  24315. lastCount = count;
  24316. }
  24317. });
  24318. function updateElementText(newText) {
  24319. element.text(newText || '');
  24320. }
  24321. }
  24322. };
  24323. }];
  24324. /**
  24325. * @ngdoc directive
  24326. * @name ngRepeat
  24327. * @multiElement
  24328. *
  24329. * @description
  24330. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  24331. * instance gets its own scope, where the given loop variable is set to the current collection item,
  24332. * and `$index` is set to the item index or key.
  24333. *
  24334. * Special properties are exposed on the local scope of each template instance, including:
  24335. *
  24336. * | Variable | Type | Details |
  24337. * |-----------|-----------------|-----------------------------------------------------------------------------|
  24338. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  24339. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  24340. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  24341. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  24342. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  24343. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  24344. *
  24345. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  24346. * This may be useful when, for instance, nesting ngRepeats.
  24347. *
  24348. *
  24349. * # Iterating over object properties
  24350. *
  24351. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  24352. * syntax:
  24353. *
  24354. * ```js
  24355. * <div ng-repeat="(key, value) in myObj"> ... </div>
  24356. * ```
  24357. *
  24358. * You need to be aware that the JavaScript specification does not define the order of keys
  24359. * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
  24360. * used to sort the keys alphabetically.)
  24361. *
  24362. * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
  24363. * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
  24364. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  24365. * and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
  24366. *
  24367. * If this is not desired, the recommended workaround is to convert your object into an array
  24368. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  24369. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  24370. * or implement a `$watch` on the object yourself.
  24371. *
  24372. *
  24373. * # Tracking and Duplicates
  24374. *
  24375. * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
  24376. *
  24377. * * When an item is added, a new instance of the template is added to the DOM.
  24378. * * When an item is removed, its template instance is removed from the DOM.
  24379. * * When items are reordered, their respective templates are reordered in the DOM.
  24380. *
  24381. * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
  24382. * there are duplicates, it is not possible to maintain a one-to-one mapping between collection
  24383. * items and DOM elements.
  24384. *
  24385. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  24386. * with your own using the `track by` expression.
  24387. *
  24388. * For example, you may track items by the index of each item in the collection, using the
  24389. * special scope property `$index`:
  24390. * ```html
  24391. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  24392. * {{n}}
  24393. * </div>
  24394. * ```
  24395. *
  24396. * You may use arbitrary expressions in `track by`, including references to custom functions
  24397. * on the scope:
  24398. * ```html
  24399. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  24400. * {{n}}
  24401. * </div>
  24402. * ```
  24403. *
  24404. * If you are working with objects that have an identifier property, you can track
  24405. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  24406. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  24407. * JavaScript objects in the collection have been substituted for new ones:
  24408. * ```html
  24409. * <div ng-repeat="model in collection track by model.id">
  24410. * {{model.name}}
  24411. * </div>
  24412. * ```
  24413. *
  24414. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  24415. * `$id` function, which tracks items by their identity:
  24416. * ```html
  24417. * <div ng-repeat="obj in collection track by $id(obj)">
  24418. * {{obj.prop}}
  24419. * </div>
  24420. * ```
  24421. *
  24422. * <div class="alert alert-warning">
  24423. * **Note:** `track by` must always be the last expression:
  24424. * </div>
  24425. * ```
  24426. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  24427. * {{model.name}}
  24428. * </div>
  24429. * ```
  24430. *
  24431. * # Special repeat start and end points
  24432. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  24433. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  24434. * 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)
  24435. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  24436. *
  24437. * The example below makes use of this feature:
  24438. * ```html
  24439. * <header ng-repeat-start="item in items">
  24440. * Header {{ item }}
  24441. * </header>
  24442. * <div class="body">
  24443. * Body {{ item }}
  24444. * </div>
  24445. * <footer ng-repeat-end>
  24446. * Footer {{ item }}
  24447. * </footer>
  24448. * ```
  24449. *
  24450. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  24451. * ```html
  24452. * <header>
  24453. * Header A
  24454. * </header>
  24455. * <div class="body">
  24456. * Body A
  24457. * </div>
  24458. * <footer>
  24459. * Footer A
  24460. * </footer>
  24461. * <header>
  24462. * Header B
  24463. * </header>
  24464. * <div class="body">
  24465. * Body B
  24466. * </div>
  24467. * <footer>
  24468. * Footer B
  24469. * </footer>
  24470. * ```
  24471. *
  24472. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  24473. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  24474. *
  24475. * @animations
  24476. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  24477. *
  24478. * **.leave** - when an item is removed from the list or when an item is filtered out
  24479. *
  24480. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  24481. *
  24482. * @element ANY
  24483. * @scope
  24484. * @priority 1000
  24485. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  24486. * formats are currently supported:
  24487. *
  24488. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  24489. * is a scope expression giving the collection to enumerate.
  24490. *
  24491. * For example: `album in artist.albums`.
  24492. *
  24493. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  24494. * and `expression` is the scope expression giving the collection to enumerate.
  24495. *
  24496. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  24497. *
  24498. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  24499. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  24500. * is specified, ng-repeat associates elements by identity. It is an error to have
  24501. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  24502. * mapped to the same DOM element, which is not possible.)
  24503. *
  24504. * Note that the tracking expression must come last, after any filters, and the alias expression.
  24505. *
  24506. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  24507. * will be associated by item identity in the array.
  24508. *
  24509. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  24510. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  24511. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  24512. * element in the same way in the DOM.
  24513. *
  24514. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  24515. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  24516. * property is same.
  24517. *
  24518. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  24519. * to items in conjunction with a tracking expression.
  24520. *
  24521. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  24522. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  24523. * when a filter is active on the repeater, but the filtered result set is empty.
  24524. *
  24525. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  24526. * the items have been processed through the filter.
  24527. *
  24528. * 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
  24529. * (and not as operator, inside an expression).
  24530. *
  24531. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  24532. *
  24533. * @example
  24534. * This example initializes the scope to a list of names and
  24535. * then uses `ngRepeat` to display every person:
  24536. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24537. <file name="index.html">
  24538. <div ng-init="friends = [
  24539. {name:'John', age:25, gender:'boy'},
  24540. {name:'Jessie', age:30, gender:'girl'},
  24541. {name:'Johanna', age:28, gender:'girl'},
  24542. {name:'Joy', age:15, gender:'girl'},
  24543. {name:'Mary', age:28, gender:'girl'},
  24544. {name:'Peter', age:95, gender:'boy'},
  24545. {name:'Sebastian', age:50, gender:'boy'},
  24546. {name:'Erika', age:27, gender:'girl'},
  24547. {name:'Patrick', age:40, gender:'boy'},
  24548. {name:'Samantha', age:60, gender:'girl'}
  24549. ]">
  24550. I have {{friends.length}} friends. They are:
  24551. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  24552. <ul class="example-animate-container">
  24553. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  24554. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  24555. </li>
  24556. <li class="animate-repeat" ng-if="results.length == 0">
  24557. <strong>No results found...</strong>
  24558. </li>
  24559. </ul>
  24560. </div>
  24561. </file>
  24562. <file name="animations.css">
  24563. .example-animate-container {
  24564. background:white;
  24565. border:1px solid black;
  24566. list-style:none;
  24567. margin:0;
  24568. padding:0 10px;
  24569. }
  24570. .animate-repeat {
  24571. line-height:40px;
  24572. list-style:none;
  24573. box-sizing:border-box;
  24574. }
  24575. .animate-repeat.ng-move,
  24576. .animate-repeat.ng-enter,
  24577. .animate-repeat.ng-leave {
  24578. -webkit-transition:all linear 0.5s;
  24579. transition:all linear 0.5s;
  24580. }
  24581. .animate-repeat.ng-leave.ng-leave-active,
  24582. .animate-repeat.ng-move,
  24583. .animate-repeat.ng-enter {
  24584. opacity:0;
  24585. max-height:0;
  24586. }
  24587. .animate-repeat.ng-leave,
  24588. .animate-repeat.ng-move.ng-move-active,
  24589. .animate-repeat.ng-enter.ng-enter-active {
  24590. opacity:1;
  24591. max-height:40px;
  24592. }
  24593. </file>
  24594. <file name="protractor.js" type="protractor">
  24595. var friends = element.all(by.repeater('friend in friends'));
  24596. it('should render initial data set', function() {
  24597. expect(friends.count()).toBe(10);
  24598. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  24599. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  24600. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  24601. expect(element(by.binding('friends.length')).getText())
  24602. .toMatch("I have 10 friends. They are:");
  24603. });
  24604. it('should update repeater when filter predicate changes', function() {
  24605. expect(friends.count()).toBe(10);
  24606. element(by.model('q')).sendKeys('ma');
  24607. expect(friends.count()).toBe(2);
  24608. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  24609. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  24610. });
  24611. </file>
  24612. </example>
  24613. */
  24614. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  24615. var NG_REMOVED = '$$NG_REMOVED';
  24616. var ngRepeatMinErr = minErr('ngRepeat');
  24617. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  24618. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  24619. scope[valueIdentifier] = value;
  24620. if (keyIdentifier) scope[keyIdentifier] = key;
  24621. scope.$index = index;
  24622. scope.$first = (index === 0);
  24623. scope.$last = (index === (arrayLength - 1));
  24624. scope.$middle = !(scope.$first || scope.$last);
  24625. // jshint bitwise: false
  24626. scope.$odd = !(scope.$even = (index&1) === 0);
  24627. // jshint bitwise: true
  24628. };
  24629. var getBlockStart = function(block) {
  24630. return block.clone[0];
  24631. };
  24632. var getBlockEnd = function(block) {
  24633. return block.clone[block.clone.length - 1];
  24634. };
  24635. return {
  24636. restrict: 'A',
  24637. multiElement: true,
  24638. transclude: 'element',
  24639. priority: 1000,
  24640. terminal: true,
  24641. $$tlb: true,
  24642. compile: function ngRepeatCompile($element, $attr) {
  24643. var expression = $attr.ngRepeat;
  24644. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  24645. 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*$/);
  24646. if (!match) {
  24647. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  24648. expression);
  24649. }
  24650. var lhs = match[1];
  24651. var rhs = match[2];
  24652. var aliasAs = match[3];
  24653. var trackByExp = match[4];
  24654. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  24655. if (!match) {
  24656. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  24657. lhs);
  24658. }
  24659. var valueIdentifier = match[3] || match[1];
  24660. var keyIdentifier = match[2];
  24661. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  24662. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  24663. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  24664. aliasAs);
  24665. }
  24666. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  24667. var hashFnLocals = {$id: hashKey};
  24668. if (trackByExp) {
  24669. trackByExpGetter = $parse(trackByExp);
  24670. } else {
  24671. trackByIdArrayFn = function(key, value) {
  24672. return hashKey(value);
  24673. };
  24674. trackByIdObjFn = function(key) {
  24675. return key;
  24676. };
  24677. }
  24678. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  24679. if (trackByExpGetter) {
  24680. trackByIdExpFn = function(key, value, index) {
  24681. // assign key, value, and $index to the locals so that they can be used in hash functions
  24682. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  24683. hashFnLocals[valueIdentifier] = value;
  24684. hashFnLocals.$index = index;
  24685. return trackByExpGetter($scope, hashFnLocals);
  24686. };
  24687. }
  24688. // Store a list of elements from previous run. This is a hash where key is the item from the
  24689. // iterator, and the value is objects with following properties.
  24690. // - scope: bound scope
  24691. // - element: previous element.
  24692. // - index: position
  24693. //
  24694. // We are using no-proto object so that we don't need to guard against inherited props via
  24695. // hasOwnProperty.
  24696. var lastBlockMap = createMap();
  24697. //watch props
  24698. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  24699. var index, length,
  24700. previousNode = $element[0], // node that cloned nodes should be inserted after
  24701. // initialized to the comment node anchor
  24702. nextNode,
  24703. // Same as lastBlockMap but it has the current state. It will become the
  24704. // lastBlockMap on the next iteration.
  24705. nextBlockMap = createMap(),
  24706. collectionLength,
  24707. key, value, // key/value of iteration
  24708. trackById,
  24709. trackByIdFn,
  24710. collectionKeys,
  24711. block, // last object information {scope, element, id}
  24712. nextBlockOrder,
  24713. elementsToRemove;
  24714. if (aliasAs) {
  24715. $scope[aliasAs] = collection;
  24716. }
  24717. if (isArrayLike(collection)) {
  24718. collectionKeys = collection;
  24719. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  24720. } else {
  24721. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  24722. // if object, extract keys, in enumeration order, unsorted
  24723. collectionKeys = [];
  24724. for (var itemKey in collection) {
  24725. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  24726. collectionKeys.push(itemKey);
  24727. }
  24728. }
  24729. }
  24730. collectionLength = collectionKeys.length;
  24731. nextBlockOrder = new Array(collectionLength);
  24732. // locate existing items
  24733. for (index = 0; index < collectionLength; index++) {
  24734. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24735. value = collection[key];
  24736. trackById = trackByIdFn(key, value, index);
  24737. if (lastBlockMap[trackById]) {
  24738. // found previously seen block
  24739. block = lastBlockMap[trackById];
  24740. delete lastBlockMap[trackById];
  24741. nextBlockMap[trackById] = block;
  24742. nextBlockOrder[index] = block;
  24743. } else if (nextBlockMap[trackById]) {
  24744. // if collision detected. restore lastBlockMap and throw an error
  24745. forEach(nextBlockOrder, function(block) {
  24746. if (block && block.scope) lastBlockMap[block.id] = block;
  24747. });
  24748. throw ngRepeatMinErr('dupes',
  24749. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  24750. expression, trackById, value);
  24751. } else {
  24752. // new never before seen block
  24753. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  24754. nextBlockMap[trackById] = true;
  24755. }
  24756. }
  24757. // remove leftover items
  24758. for (var blockKey in lastBlockMap) {
  24759. block = lastBlockMap[blockKey];
  24760. elementsToRemove = getBlockNodes(block.clone);
  24761. $animate.leave(elementsToRemove);
  24762. if (elementsToRemove[0].parentNode) {
  24763. // if the element was not removed yet because of pending animation, mark it as deleted
  24764. // so that we can ignore it later
  24765. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  24766. elementsToRemove[index][NG_REMOVED] = true;
  24767. }
  24768. }
  24769. block.scope.$destroy();
  24770. }
  24771. // we are not using forEach for perf reasons (trying to avoid #call)
  24772. for (index = 0; index < collectionLength; index++) {
  24773. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24774. value = collection[key];
  24775. block = nextBlockOrder[index];
  24776. if (block.scope) {
  24777. // if we have already seen this object, then we need to reuse the
  24778. // associated scope/element
  24779. nextNode = previousNode;
  24780. // skip nodes that are already pending removal via leave animation
  24781. do {
  24782. nextNode = nextNode.nextSibling;
  24783. } while (nextNode && nextNode[NG_REMOVED]);
  24784. if (getBlockStart(block) != nextNode) {
  24785. // existing item which got moved
  24786. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  24787. }
  24788. previousNode = getBlockEnd(block);
  24789. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24790. } else {
  24791. // new item which we don't know about
  24792. $transclude(function ngRepeatTransclude(clone, scope) {
  24793. block.scope = scope;
  24794. // http://jsperf.com/clone-vs-createcomment
  24795. var endNode = ngRepeatEndComment.cloneNode(false);
  24796. clone[clone.length++] = endNode;
  24797. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  24798. $animate.enter(clone, null, jqLite(previousNode));
  24799. previousNode = endNode;
  24800. // Note: We only need the first/last node of the cloned nodes.
  24801. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  24802. // by a directive with templateUrl when its template arrives.
  24803. block.clone = clone;
  24804. nextBlockMap[block.id] = block;
  24805. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24806. });
  24807. }
  24808. }
  24809. lastBlockMap = nextBlockMap;
  24810. });
  24811. };
  24812. }
  24813. };
  24814. }];
  24815. var NG_HIDE_CLASS = 'ng-hide';
  24816. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  24817. /**
  24818. * @ngdoc directive
  24819. * @name ngShow
  24820. * @multiElement
  24821. *
  24822. * @description
  24823. * The `ngShow` directive shows or hides the given HTML element based on the expression
  24824. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  24825. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  24826. * in AngularJS and sets the display style to none (using an !important flag).
  24827. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24828. *
  24829. * ```html
  24830. * <!-- when $scope.myValue is truthy (element is visible) -->
  24831. * <div ng-show="myValue"></div>
  24832. *
  24833. * <!-- when $scope.myValue is falsy (element is hidden) -->
  24834. * <div ng-show="myValue" class="ng-hide"></div>
  24835. * ```
  24836. *
  24837. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  24838. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  24839. * from the element causing the element not to appear hidden.
  24840. *
  24841. * ## Why is !important used?
  24842. *
  24843. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  24844. * can be easily overridden by heavier selectors. For example, something as simple
  24845. * as changing the display style on a HTML list item would make hidden elements appear visible.
  24846. * This also becomes a bigger issue when dealing with CSS frameworks.
  24847. *
  24848. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  24849. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  24850. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  24851. *
  24852. * ### Overriding `.ng-hide`
  24853. *
  24854. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  24855. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  24856. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  24857. * with extra animation classes that can be added.
  24858. *
  24859. * ```css
  24860. * .ng-hide:not(.ng-hide-animate) {
  24861. * /&#42; this is just another form of hiding an element &#42;/
  24862. * display: block!important;
  24863. * position: absolute;
  24864. * top: -9999px;
  24865. * left: -9999px;
  24866. * }
  24867. * ```
  24868. *
  24869. * By default you don't need to override in CSS anything and the animations will work around the display style.
  24870. *
  24871. * ## A note about animations with `ngShow`
  24872. *
  24873. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  24874. * is true and false. This system works like the animation system present with ngClass except that
  24875. * you must also include the !important flag to override the display property
  24876. * so that you can perform an animation when the element is hidden during the time of the animation.
  24877. *
  24878. * ```css
  24879. * //
  24880. * //a working example can be found at the bottom of this page
  24881. * //
  24882. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  24883. * /&#42; this is required as of 1.3x to properly
  24884. * apply all styling in a show/hide animation &#42;/
  24885. * transition: 0s linear all;
  24886. * }
  24887. *
  24888. * .my-element.ng-hide-add-active,
  24889. * .my-element.ng-hide-remove-active {
  24890. * /&#42; the transition is defined in the active class &#42;/
  24891. * transition: 1s linear all;
  24892. * }
  24893. *
  24894. * .my-element.ng-hide-add { ... }
  24895. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  24896. * .my-element.ng-hide-remove { ... }
  24897. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  24898. * ```
  24899. *
  24900. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  24901. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  24902. *
  24903. * @animations
  24904. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  24905. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  24906. *
  24907. * @element ANY
  24908. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  24909. * then the element is shown or hidden respectively.
  24910. *
  24911. * @example
  24912. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24913. <file name="index.html">
  24914. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  24915. <div>
  24916. Show:
  24917. <div class="check-element animate-show" ng-show="checked">
  24918. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  24919. </div>
  24920. </div>
  24921. <div>
  24922. Hide:
  24923. <div class="check-element animate-show" ng-hide="checked">
  24924. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  24925. </div>
  24926. </div>
  24927. </file>
  24928. <file name="glyphicons.css">
  24929. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  24930. </file>
  24931. <file name="animations.css">
  24932. .animate-show {
  24933. line-height: 20px;
  24934. opacity: 1;
  24935. padding: 10px;
  24936. border: 1px solid black;
  24937. background: white;
  24938. }
  24939. .animate-show.ng-hide-add.ng-hide-add-active,
  24940. .animate-show.ng-hide-remove.ng-hide-remove-active {
  24941. -webkit-transition: all linear 0.5s;
  24942. transition: all linear 0.5s;
  24943. }
  24944. .animate-show.ng-hide {
  24945. line-height: 0;
  24946. opacity: 0;
  24947. padding: 0 10px;
  24948. }
  24949. .check-element {
  24950. padding: 10px;
  24951. border: 1px solid black;
  24952. background: white;
  24953. }
  24954. </file>
  24955. <file name="protractor.js" type="protractor">
  24956. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  24957. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  24958. it('should check ng-show / ng-hide', function() {
  24959. expect(thumbsUp.isDisplayed()).toBeFalsy();
  24960. expect(thumbsDown.isDisplayed()).toBeTruthy();
  24961. element(by.model('checked')).click();
  24962. expect(thumbsUp.isDisplayed()).toBeTruthy();
  24963. expect(thumbsDown.isDisplayed()).toBeFalsy();
  24964. });
  24965. </file>
  24966. </example>
  24967. */
  24968. var ngShowDirective = ['$animate', function($animate) {
  24969. return {
  24970. restrict: 'A',
  24971. multiElement: true,
  24972. link: function(scope, element, attr) {
  24973. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  24974. // we're adding a temporary, animation-specific class for ng-hide since this way
  24975. // we can control when the element is actually displayed on screen without having
  24976. // to have a global/greedy CSS selector that breaks when other animations are run.
  24977. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  24978. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  24979. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  24980. });
  24981. });
  24982. }
  24983. };
  24984. }];
  24985. /**
  24986. * @ngdoc directive
  24987. * @name ngHide
  24988. * @multiElement
  24989. *
  24990. * @description
  24991. * The `ngHide` directive shows or hides the given HTML element based on the expression
  24992. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  24993. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  24994. * in AngularJS and sets the display style to none (using an !important flag).
  24995. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24996. *
  24997. * ```html
  24998. * <!-- when $scope.myValue is truthy (element is hidden) -->
  24999. * <div ng-hide="myValue" class="ng-hide"></div>
  25000. *
  25001. * <!-- when $scope.myValue is falsy (element is visible) -->
  25002. * <div ng-hide="myValue"></div>
  25003. * ```
  25004. *
  25005. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  25006. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  25007. * from the element causing the element not to appear hidden.
  25008. *
  25009. * ## Why is !important used?
  25010. *
  25011. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  25012. * can be easily overridden by heavier selectors. For example, something as simple
  25013. * as changing the display style on a HTML list item would make hidden elements appear visible.
  25014. * This also becomes a bigger issue when dealing with CSS frameworks.
  25015. *
  25016. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  25017. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  25018. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  25019. *
  25020. * ### Overriding `.ng-hide`
  25021. *
  25022. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  25023. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  25024. * class in CSS:
  25025. *
  25026. * ```css
  25027. * .ng-hide {
  25028. * /&#42; this is just another form of hiding an element &#42;/
  25029. * display: block!important;
  25030. * position: absolute;
  25031. * top: -9999px;
  25032. * left: -9999px;
  25033. * }
  25034. * ```
  25035. *
  25036. * By default you don't need to override in CSS anything and the animations will work around the display style.
  25037. *
  25038. * ## A note about animations with `ngHide`
  25039. *
  25040. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  25041. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  25042. * CSS class is added and removed for you instead of your own CSS class.
  25043. *
  25044. * ```css
  25045. * //
  25046. * //a working example can be found at the bottom of this page
  25047. * //
  25048. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  25049. * transition: 0.5s linear all;
  25050. * }
  25051. *
  25052. * .my-element.ng-hide-add { ... }
  25053. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  25054. * .my-element.ng-hide-remove { ... }
  25055. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  25056. * ```
  25057. *
  25058. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  25059. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  25060. *
  25061. * @animations
  25062. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  25063. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  25064. *
  25065. * @element ANY
  25066. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  25067. * the element is shown or hidden respectively.
  25068. *
  25069. * @example
  25070. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25071. <file name="index.html">
  25072. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  25073. <div>
  25074. Show:
  25075. <div class="check-element animate-hide" ng-show="checked">
  25076. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  25077. </div>
  25078. </div>
  25079. <div>
  25080. Hide:
  25081. <div class="check-element animate-hide" ng-hide="checked">
  25082. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25083. </div>
  25084. </div>
  25085. </file>
  25086. <file name="glyphicons.css">
  25087. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25088. </file>
  25089. <file name="animations.css">
  25090. .animate-hide {
  25091. -webkit-transition: all linear 0.5s;
  25092. transition: all linear 0.5s;
  25093. line-height: 20px;
  25094. opacity: 1;
  25095. padding: 10px;
  25096. border: 1px solid black;
  25097. background: white;
  25098. }
  25099. .animate-hide.ng-hide {
  25100. line-height: 0;
  25101. opacity: 0;
  25102. padding: 0 10px;
  25103. }
  25104. .check-element {
  25105. padding: 10px;
  25106. border: 1px solid black;
  25107. background: white;
  25108. }
  25109. </file>
  25110. <file name="protractor.js" type="protractor">
  25111. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25112. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25113. it('should check ng-show / ng-hide', function() {
  25114. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25115. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25116. element(by.model('checked')).click();
  25117. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25118. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25119. });
  25120. </file>
  25121. </example>
  25122. */
  25123. var ngHideDirective = ['$animate', function($animate) {
  25124. return {
  25125. restrict: 'A',
  25126. multiElement: true,
  25127. link: function(scope, element, attr) {
  25128. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  25129. // The comment inside of the ngShowDirective explains why we add and
  25130. // remove a temporary class for the show/hide animation
  25131. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  25132. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25133. });
  25134. });
  25135. }
  25136. };
  25137. }];
  25138. /**
  25139. * @ngdoc directive
  25140. * @name ngStyle
  25141. * @restrict AC
  25142. *
  25143. * @description
  25144. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  25145. *
  25146. * @element ANY
  25147. * @param {expression} ngStyle
  25148. *
  25149. * {@link guide/expression Expression} which evals to an
  25150. * object whose keys are CSS style names and values are corresponding values for those CSS
  25151. * keys.
  25152. *
  25153. * Since some CSS style names are not valid keys for an object, they must be quoted.
  25154. * See the 'background-color' style in the example below.
  25155. *
  25156. * @example
  25157. <example>
  25158. <file name="index.html">
  25159. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  25160. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  25161. <input type="button" value="clear" ng-click="myStyle={}">
  25162. <br/>
  25163. <span ng-style="myStyle">Sample Text</span>
  25164. <pre>myStyle={{myStyle}}</pre>
  25165. </file>
  25166. <file name="style.css">
  25167. span {
  25168. color: black;
  25169. }
  25170. </file>
  25171. <file name="protractor.js" type="protractor">
  25172. var colorSpan = element(by.css('span'));
  25173. it('should check ng-style', function() {
  25174. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25175. element(by.css('input[value=\'set color\']')).click();
  25176. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  25177. element(by.css('input[value=clear]')).click();
  25178. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25179. });
  25180. </file>
  25181. </example>
  25182. */
  25183. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  25184. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  25185. if (oldStyles && (newStyles !== oldStyles)) {
  25186. forEach(oldStyles, function(val, style) { element.css(style, '');});
  25187. }
  25188. if (newStyles) element.css(newStyles);
  25189. }, true);
  25190. });
  25191. /**
  25192. * @ngdoc directive
  25193. * @name ngSwitch
  25194. * @restrict EA
  25195. *
  25196. * @description
  25197. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  25198. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  25199. * as specified in the template.
  25200. *
  25201. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  25202. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  25203. * matches the value obtained from the evaluated expression. In other words, you define a container element
  25204. * (where you place the directive), place an expression on the **`on="..."` attribute**
  25205. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  25206. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  25207. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  25208. * attribute is displayed.
  25209. *
  25210. * <div class="alert alert-info">
  25211. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  25212. * as literal string values to match against.
  25213. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  25214. * value of the expression `$scope.someVal`.
  25215. * </div>
  25216. * @animations
  25217. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  25218. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  25219. *
  25220. * @usage
  25221. *
  25222. * ```
  25223. * <ANY ng-switch="expression">
  25224. * <ANY ng-switch-when="matchValue1">...</ANY>
  25225. * <ANY ng-switch-when="matchValue2">...</ANY>
  25226. * <ANY ng-switch-default>...</ANY>
  25227. * </ANY>
  25228. * ```
  25229. *
  25230. *
  25231. * @scope
  25232. * @priority 1200
  25233. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  25234. * On child elements add:
  25235. *
  25236. * * `ngSwitchWhen`: the case statement to match against. If match then this
  25237. * case will be displayed. If the same match appears multiple times, all the
  25238. * elements will be displayed.
  25239. * * `ngSwitchDefault`: the default case when no other case match. If there
  25240. * are multiple default cases, all of them will be displayed when no other
  25241. * case match.
  25242. *
  25243. *
  25244. * @example
  25245. <example module="switchExample" deps="angular-animate.js" animations="true">
  25246. <file name="index.html">
  25247. <div ng-controller="ExampleController">
  25248. <select ng-model="selection" ng-options="item for item in items">
  25249. </select>
  25250. <code>selection={{selection}}</code>
  25251. <hr/>
  25252. <div class="animate-switch-container"
  25253. ng-switch on="selection">
  25254. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  25255. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  25256. <div class="animate-switch" ng-switch-default>default</div>
  25257. </div>
  25258. </div>
  25259. </file>
  25260. <file name="script.js">
  25261. angular.module('switchExample', ['ngAnimate'])
  25262. .controller('ExampleController', ['$scope', function($scope) {
  25263. $scope.items = ['settings', 'home', 'other'];
  25264. $scope.selection = $scope.items[0];
  25265. }]);
  25266. </file>
  25267. <file name="animations.css">
  25268. .animate-switch-container {
  25269. position:relative;
  25270. background:white;
  25271. border:1px solid black;
  25272. height:40px;
  25273. overflow:hidden;
  25274. }
  25275. .animate-switch {
  25276. padding:10px;
  25277. }
  25278. .animate-switch.ng-animate {
  25279. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25280. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25281. position:absolute;
  25282. top:0;
  25283. left:0;
  25284. right:0;
  25285. bottom:0;
  25286. }
  25287. .animate-switch.ng-leave.ng-leave-active,
  25288. .animate-switch.ng-enter {
  25289. top:-50px;
  25290. }
  25291. .animate-switch.ng-leave,
  25292. .animate-switch.ng-enter.ng-enter-active {
  25293. top:0;
  25294. }
  25295. </file>
  25296. <file name="protractor.js" type="protractor">
  25297. var switchElem = element(by.css('[ng-switch]'));
  25298. var select = element(by.model('selection'));
  25299. it('should start in settings', function() {
  25300. expect(switchElem.getText()).toMatch(/Settings Div/);
  25301. });
  25302. it('should change to home', function() {
  25303. select.all(by.css('option')).get(1).click();
  25304. expect(switchElem.getText()).toMatch(/Home Span/);
  25305. });
  25306. it('should select default', function() {
  25307. select.all(by.css('option')).get(2).click();
  25308. expect(switchElem.getText()).toMatch(/default/);
  25309. });
  25310. </file>
  25311. </example>
  25312. */
  25313. var ngSwitchDirective = ['$animate', function($animate) {
  25314. return {
  25315. require: 'ngSwitch',
  25316. // asks for $scope to fool the BC controller module
  25317. controller: ['$scope', function ngSwitchController() {
  25318. this.cases = {};
  25319. }],
  25320. link: function(scope, element, attr, ngSwitchController) {
  25321. var watchExpr = attr.ngSwitch || attr.on,
  25322. selectedTranscludes = [],
  25323. selectedElements = [],
  25324. previousLeaveAnimations = [],
  25325. selectedScopes = [];
  25326. var spliceFactory = function(array, index) {
  25327. return function() { array.splice(index, 1); };
  25328. };
  25329. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  25330. var i, ii;
  25331. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  25332. $animate.cancel(previousLeaveAnimations[i]);
  25333. }
  25334. previousLeaveAnimations.length = 0;
  25335. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  25336. var selected = getBlockNodes(selectedElements[i].clone);
  25337. selectedScopes[i].$destroy();
  25338. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  25339. promise.then(spliceFactory(previousLeaveAnimations, i));
  25340. }
  25341. selectedElements.length = 0;
  25342. selectedScopes.length = 0;
  25343. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  25344. forEach(selectedTranscludes, function(selectedTransclude) {
  25345. selectedTransclude.transclude(function(caseElement, selectedScope) {
  25346. selectedScopes.push(selectedScope);
  25347. var anchor = selectedTransclude.element;
  25348. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  25349. var block = { clone: caseElement };
  25350. selectedElements.push(block);
  25351. $animate.enter(caseElement, anchor.parent(), anchor);
  25352. });
  25353. });
  25354. }
  25355. });
  25356. }
  25357. };
  25358. }];
  25359. var ngSwitchWhenDirective = ngDirective({
  25360. transclude: 'element',
  25361. priority: 1200,
  25362. require: '^ngSwitch',
  25363. multiElement: true,
  25364. link: function(scope, element, attrs, ctrl, $transclude) {
  25365. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  25366. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  25367. }
  25368. });
  25369. var ngSwitchDefaultDirective = ngDirective({
  25370. transclude: 'element',
  25371. priority: 1200,
  25372. require: '^ngSwitch',
  25373. multiElement: true,
  25374. link: function(scope, element, attr, ctrl, $transclude) {
  25375. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  25376. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  25377. }
  25378. });
  25379. /**
  25380. * @ngdoc directive
  25381. * @name ngTransclude
  25382. * @restrict EAC
  25383. *
  25384. * @description
  25385. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  25386. *
  25387. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  25388. *
  25389. * @element ANY
  25390. *
  25391. * @example
  25392. <example module="transcludeExample">
  25393. <file name="index.html">
  25394. <script>
  25395. angular.module('transcludeExample', [])
  25396. .directive('pane', function(){
  25397. return {
  25398. restrict: 'E',
  25399. transclude: true,
  25400. scope: { title:'@' },
  25401. template: '<div style="border: 1px solid black;">' +
  25402. '<div style="background-color: gray">{{title}}</div>' +
  25403. '<ng-transclude></ng-transclude>' +
  25404. '</div>'
  25405. };
  25406. })
  25407. .controller('ExampleController', ['$scope', function($scope) {
  25408. $scope.title = 'Lorem Ipsum';
  25409. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  25410. }]);
  25411. </script>
  25412. <div ng-controller="ExampleController">
  25413. <input ng-model="title" aria-label="title"> <br/>
  25414. <textarea ng-model="text" aria-label="text"></textarea> <br/>
  25415. <pane title="{{title}}">{{text}}</pane>
  25416. </div>
  25417. </file>
  25418. <file name="protractor.js" type="protractor">
  25419. it('should have transcluded', function() {
  25420. var titleElement = element(by.model('title'));
  25421. titleElement.clear();
  25422. titleElement.sendKeys('TITLE');
  25423. var textElement = element(by.model('text'));
  25424. textElement.clear();
  25425. textElement.sendKeys('TEXT');
  25426. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  25427. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  25428. });
  25429. </file>
  25430. </example>
  25431. *
  25432. */
  25433. var ngTranscludeDirective = ngDirective({
  25434. restrict: 'EAC',
  25435. link: function($scope, $element, $attrs, controller, $transclude) {
  25436. if (!$transclude) {
  25437. throw minErr('ngTransclude')('orphan',
  25438. 'Illegal use of ngTransclude directive in the template! ' +
  25439. 'No parent directive that requires a transclusion found. ' +
  25440. 'Element: {0}',
  25441. startingTag($element));
  25442. }
  25443. $transclude(function(clone) {
  25444. $element.empty();
  25445. $element.append(clone);
  25446. });
  25447. }
  25448. });
  25449. /**
  25450. * @ngdoc directive
  25451. * @name script
  25452. * @restrict E
  25453. *
  25454. * @description
  25455. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  25456. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  25457. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  25458. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  25459. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  25460. *
  25461. * @param {string} type Must be set to `'text/ng-template'`.
  25462. * @param {string} id Cache name of the template.
  25463. *
  25464. * @example
  25465. <example>
  25466. <file name="index.html">
  25467. <script type="text/ng-template" id="/tpl.html">
  25468. Content of the template.
  25469. </script>
  25470. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  25471. <div id="tpl-content" ng-include src="currentTpl"></div>
  25472. </file>
  25473. <file name="protractor.js" type="protractor">
  25474. it('should load template defined inside script tag', function() {
  25475. element(by.css('#tpl-link')).click();
  25476. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  25477. });
  25478. </file>
  25479. </example>
  25480. */
  25481. var scriptDirective = ['$templateCache', function($templateCache) {
  25482. return {
  25483. restrict: 'E',
  25484. terminal: true,
  25485. compile: function(element, attr) {
  25486. if (attr.type == 'text/ng-template') {
  25487. var templateUrl = attr.id,
  25488. text = element[0].text;
  25489. $templateCache.put(templateUrl, text);
  25490. }
  25491. }
  25492. };
  25493. }];
  25494. var noopNgModelController = { $setViewValue: noop, $render: noop };
  25495. /**
  25496. * @ngdoc type
  25497. * @name select.SelectController
  25498. * @description
  25499. * The controller for the `<select>` directive. This provides support for reading
  25500. * and writing the selected value(s) of the control and also coordinates dynamically
  25501. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  25502. */
  25503. var SelectController =
  25504. ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  25505. var self = this,
  25506. optionsMap = new HashMap();
  25507. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  25508. self.ngModelCtrl = noopNgModelController;
  25509. // The "unknown" option is one that is prepended to the list if the viewValue
  25510. // does not match any of the options. When it is rendered the value of the unknown
  25511. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  25512. //
  25513. // We can't just jqLite('<option>') since jqLite is not smart enough
  25514. // to create it in <select> and IE barfs otherwise.
  25515. self.unknownOption = jqLite(document.createElement('option'));
  25516. self.renderUnknownOption = function(val) {
  25517. var unknownVal = '? ' + hashKey(val) + ' ?';
  25518. self.unknownOption.val(unknownVal);
  25519. $element.prepend(self.unknownOption);
  25520. $element.val(unknownVal);
  25521. };
  25522. $scope.$on('$destroy', function() {
  25523. // disable unknown option so that we don't do work when the whole select is being destroyed
  25524. self.renderUnknownOption = noop;
  25525. });
  25526. self.removeUnknownOption = function() {
  25527. if (self.unknownOption.parent()) self.unknownOption.remove();
  25528. };
  25529. // Read the value of the select control, the implementation of this changes depending
  25530. // upon whether the select can have multiple values and whether ngOptions is at work.
  25531. self.readValue = function readSingleValue() {
  25532. self.removeUnknownOption();
  25533. return $element.val();
  25534. };
  25535. // Write the value to the select control, the implementation of this changes depending
  25536. // upon whether the select can have multiple values and whether ngOptions is at work.
  25537. self.writeValue = function writeSingleValue(value) {
  25538. if (self.hasOption(value)) {
  25539. self.removeUnknownOption();
  25540. $element.val(value);
  25541. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  25542. } else {
  25543. if (value == null && self.emptyOption) {
  25544. self.removeUnknownOption();
  25545. $element.val('');
  25546. } else {
  25547. self.renderUnknownOption(value);
  25548. }
  25549. }
  25550. };
  25551. // Tell the select control that an option, with the given value, has been added
  25552. self.addOption = function(value, element) {
  25553. assertNotHasOwnProperty(value, '"option value"');
  25554. if (value === '') {
  25555. self.emptyOption = element;
  25556. }
  25557. var count = optionsMap.get(value) || 0;
  25558. optionsMap.put(value, count + 1);
  25559. };
  25560. // Tell the select control that an option, with the given value, has been removed
  25561. self.removeOption = function(value) {
  25562. var count = optionsMap.get(value);
  25563. if (count) {
  25564. if (count === 1) {
  25565. optionsMap.remove(value);
  25566. if (value === '') {
  25567. self.emptyOption = undefined;
  25568. }
  25569. } else {
  25570. optionsMap.put(value, count - 1);
  25571. }
  25572. }
  25573. };
  25574. // Check whether the select control has an option matching the given value
  25575. self.hasOption = function(value) {
  25576. return !!optionsMap.get(value);
  25577. };
  25578. }];
  25579. /**
  25580. * @ngdoc directive
  25581. * @name select
  25582. * @restrict E
  25583. *
  25584. * @description
  25585. * HTML `SELECT` element with angular data-binding.
  25586. *
  25587. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  25588. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits such as reducing
  25589. * memory and increasing speed by not creating a new scope for each repeated instance, as well as providing
  25590. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  25591. * comprehension expression.
  25592. *
  25593. * When an item in the `<select>` menu is selected, the array element or object property
  25594. * represented by the selected option will be bound to the model identified by the `ngModel`
  25595. * directive.
  25596. *
  25597. * If the viewValue contains a value that doesn't match any of the options then the control
  25598. * will automatically add an "unknown" option, which it then removes when this is resolved.
  25599. *
  25600. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  25601. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  25602. * option. See example below for demonstration.
  25603. *
  25604. * <div class="alert alert-info">
  25605. * The value of a `select` directive used without `ngOptions` is always a string.
  25606. * When the model needs to be bound to a non-string value, you must either explictly convert it
  25607. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  25608. * This is because an option element can only be bound to string values at present.
  25609. * </div>
  25610. *
  25611. * ### Example (binding `select` to a non-string value)
  25612. *
  25613. * <example name="select-with-non-string-options" module="nonStringSelect">
  25614. * <file name="index.html">
  25615. * <select ng-model="model.id" convert-to-number>
  25616. * <option value="0">Zero</option>
  25617. * <option value="1">One</option>
  25618. * <option value="2">Two</option>
  25619. * </select>
  25620. * {{ model }}
  25621. * </file>
  25622. * <file name="app.js">
  25623. * angular.module('nonStringSelect', [])
  25624. * .run(function($rootScope) {
  25625. * $rootScope.model = { id: 2 };
  25626. * })
  25627. * .directive('convertToNumber', function() {
  25628. * return {
  25629. * require: 'ngModel',
  25630. * link: function(scope, element, attrs, ngModel) {
  25631. * ngModel.$parsers.push(function(val) {
  25632. * return parseInt(val, 10);
  25633. * });
  25634. * ngModel.$formatters.push(function(val) {
  25635. * return '' + val;
  25636. * });
  25637. * }
  25638. * };
  25639. * });
  25640. * </file>
  25641. * <file name="protractor.js" type="protractor">
  25642. * it('should initialize to model', function() {
  25643. * var select = element(by.css('select'));
  25644. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  25645. * });
  25646. * </file>
  25647. * </example>
  25648. *
  25649. */
  25650. var selectDirective = function() {
  25651. return {
  25652. restrict: 'E',
  25653. require: ['select', '?ngModel'],
  25654. controller: SelectController,
  25655. link: function(scope, element, attr, ctrls) {
  25656. // if ngModel is not defined, we don't need to do anything
  25657. var ngModelCtrl = ctrls[1];
  25658. if (!ngModelCtrl) return;
  25659. var selectCtrl = ctrls[0];
  25660. selectCtrl.ngModelCtrl = ngModelCtrl;
  25661. // We delegate rendering to the `writeValue` method, which can be changed
  25662. // if the select can have multiple selected values or if the options are being
  25663. // generated by `ngOptions`
  25664. ngModelCtrl.$render = function() {
  25665. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  25666. };
  25667. // When the selected item(s) changes we delegate getting the value of the select control
  25668. // to the `readValue` method, which can be changed if the select can have multiple
  25669. // selected values or if the options are being generated by `ngOptions`
  25670. element.on('change', function() {
  25671. scope.$apply(function() {
  25672. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  25673. });
  25674. });
  25675. // If the select allows multiple values then we need to modify how we read and write
  25676. // values from and to the control; also what it means for the value to be empty and
  25677. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  25678. // doesn't trigger rendering if only an item in the array changes.
  25679. if (attr.multiple) {
  25680. // Read value now needs to check each option to see if it is selected
  25681. selectCtrl.readValue = function readMultipleValue() {
  25682. var array = [];
  25683. forEach(element.find('option'), function(option) {
  25684. if (option.selected) {
  25685. array.push(option.value);
  25686. }
  25687. });
  25688. return array;
  25689. };
  25690. // Write value now needs to set the selected property of each matching option
  25691. selectCtrl.writeValue = function writeMultipleValue(value) {
  25692. var items = new HashMap(value);
  25693. forEach(element.find('option'), function(option) {
  25694. option.selected = isDefined(items.get(option.value));
  25695. });
  25696. };
  25697. // we have to do it on each watch since ngModel watches reference, but
  25698. // we need to work of an array, so we need to see if anything was inserted/removed
  25699. var lastView, lastViewRef = NaN;
  25700. scope.$watch(function selectMultipleWatch() {
  25701. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  25702. lastView = shallowCopy(ngModelCtrl.$viewValue);
  25703. ngModelCtrl.$render();
  25704. }
  25705. lastViewRef = ngModelCtrl.$viewValue;
  25706. });
  25707. // If we are a multiple select then value is now a collection
  25708. // so the meaning of $isEmpty changes
  25709. ngModelCtrl.$isEmpty = function(value) {
  25710. return !value || value.length === 0;
  25711. };
  25712. }
  25713. }
  25714. };
  25715. };
  25716. // The option directive is purely designed to communicate the existence (or lack of)
  25717. // of dynamically created (and destroyed) option elements to their containing select
  25718. // directive via its controller.
  25719. var optionDirective = ['$interpolate', function($interpolate) {
  25720. function chromeHack(optionElement) {
  25721. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  25722. // Adding an <option selected="selected"> element to a <select required="required"> should
  25723. // automatically select the new element
  25724. if (optionElement[0].hasAttribute('selected')) {
  25725. optionElement[0].selected = true;
  25726. }
  25727. }
  25728. return {
  25729. restrict: 'E',
  25730. priority: 100,
  25731. compile: function(element, attr) {
  25732. // If the value attribute is not defined then we fall back to the
  25733. // text content of the option element, which may be interpolated
  25734. if (isUndefined(attr.value)) {
  25735. var interpolateFn = $interpolate(element.text(), true);
  25736. if (!interpolateFn) {
  25737. attr.$set('value', element.text());
  25738. }
  25739. }
  25740. return function(scope, element, attr) {
  25741. // This is an optimization over using ^^ since we don't want to have to search
  25742. // all the way to the root of the DOM for every single option element
  25743. var selectCtrlName = '$selectController',
  25744. parent = element.parent(),
  25745. selectCtrl = parent.data(selectCtrlName) ||
  25746. parent.parent().data(selectCtrlName); // in case we are in optgroup
  25747. // Only update trigger option updates if this is an option within a `select`
  25748. // that also has `ngModel` attached
  25749. if (selectCtrl && selectCtrl.ngModelCtrl) {
  25750. if (interpolateFn) {
  25751. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  25752. attr.$set('value', newVal);
  25753. if (oldVal !== newVal) {
  25754. selectCtrl.removeOption(oldVal);
  25755. }
  25756. selectCtrl.addOption(newVal, element);
  25757. selectCtrl.ngModelCtrl.$render();
  25758. chromeHack(element);
  25759. });
  25760. } else {
  25761. selectCtrl.addOption(attr.value, element);
  25762. selectCtrl.ngModelCtrl.$render();
  25763. chromeHack(element);
  25764. }
  25765. element.on('$destroy', function() {
  25766. selectCtrl.removeOption(attr.value);
  25767. selectCtrl.ngModelCtrl.$render();
  25768. });
  25769. }
  25770. };
  25771. }
  25772. };
  25773. }];
  25774. var styleDirective = valueFn({
  25775. restrict: 'E',
  25776. terminal: false
  25777. });
  25778. var requiredDirective = function() {
  25779. return {
  25780. restrict: 'A',
  25781. require: '?ngModel',
  25782. link: function(scope, elm, attr, ctrl) {
  25783. if (!ctrl) return;
  25784. attr.required = true; // force truthy in case we are on non input element
  25785. ctrl.$validators.required = function(modelValue, viewValue) {
  25786. return !attr.required || !ctrl.$isEmpty(viewValue);
  25787. };
  25788. attr.$observe('required', function() {
  25789. ctrl.$validate();
  25790. });
  25791. }
  25792. };
  25793. };
  25794. var patternDirective = function() {
  25795. return {
  25796. restrict: 'A',
  25797. require: '?ngModel',
  25798. link: function(scope, elm, attr, ctrl) {
  25799. if (!ctrl) return;
  25800. var regexp, patternExp = attr.ngPattern || attr.pattern;
  25801. attr.$observe('pattern', function(regex) {
  25802. if (isString(regex) && regex.length > 0) {
  25803. regex = new RegExp('^' + regex + '$');
  25804. }
  25805. if (regex && !regex.test) {
  25806. throw minErr('ngPattern')('noregexp',
  25807. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  25808. regex, startingTag(elm));
  25809. }
  25810. regexp = regex || undefined;
  25811. ctrl.$validate();
  25812. });
  25813. ctrl.$validators.pattern = function(value) {
  25814. return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
  25815. };
  25816. }
  25817. };
  25818. };
  25819. var maxlengthDirective = function() {
  25820. return {
  25821. restrict: 'A',
  25822. require: '?ngModel',
  25823. link: function(scope, elm, attr, ctrl) {
  25824. if (!ctrl) return;
  25825. var maxlength = -1;
  25826. attr.$observe('maxlength', function(value) {
  25827. var intVal = toInt(value);
  25828. maxlength = isNaN(intVal) ? -1 : intVal;
  25829. ctrl.$validate();
  25830. });
  25831. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  25832. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  25833. };
  25834. }
  25835. };
  25836. };
  25837. var minlengthDirective = function() {
  25838. return {
  25839. restrict: 'A',
  25840. require: '?ngModel',
  25841. link: function(scope, elm, attr, ctrl) {
  25842. if (!ctrl) return;
  25843. var minlength = 0;
  25844. attr.$observe('minlength', function(value) {
  25845. minlength = toInt(value) || 0;
  25846. ctrl.$validate();
  25847. });
  25848. ctrl.$validators.minlength = function(modelValue, viewValue) {
  25849. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  25850. };
  25851. }
  25852. };
  25853. };
  25854. if (window.angular.bootstrap) {
  25855. //AngularJS is already loaded, so we can return here...
  25856. console.log('WARNING: Tried to load angular more than once.');
  25857. return;
  25858. }
  25859. //try to bind to jquery now so that one can write jqLite(document).ready()
  25860. //but we will rebind on bootstrap again.
  25861. bindJQuery();
  25862. publishExternalAPI(angular);
  25863. jqLite(document).ready(function() {
  25864. angularInit(document, bootstrap);
  25865. });
  25866. })(window, document);
  25867. !window.angular.$$csp() && 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>');